three.cjs 2.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848
  1. /**
  2. * @license
  3. * Copyright 2010-2026 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '183dev';
  8. /**
  9. * Represents mouse buttons and interaction types in context of controls.
  10. *
  11. * @type {ConstantsMouse}
  12. * @constant
  13. */
  14. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  15. /**
  16. * Represents touch interaction types in context of controls.
  17. *
  18. * @type {ConstantsTouch}
  19. * @constant
  20. */
  21. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  22. /**
  23. * Disables face culling.
  24. *
  25. * @type {number}
  26. * @constant
  27. */
  28. const CullFaceNone = 0;
  29. /**
  30. * Culls back faces.
  31. *
  32. * @type {number}
  33. * @constant
  34. */
  35. const CullFaceBack = 1;
  36. /**
  37. * Culls front faces.
  38. *
  39. * @type {number}
  40. * @constant
  41. */
  42. const CullFaceFront = 2;
  43. /**
  44. * Culls both front and back faces.
  45. *
  46. * @type {number}
  47. * @constant
  48. */
  49. const CullFaceFrontBack = 3;
  50. /**
  51. * Gives unfiltered shadow maps - fastest, but lowest quality.
  52. *
  53. * @type {number}
  54. * @constant
  55. */
  56. const BasicShadowMap = 0;
  57. /**
  58. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  59. *
  60. * @type {number}
  61. * @constant
  62. */
  63. const PCFShadowMap = 1;
  64. /**
  65. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  66. * better soft shadows especially when using low-resolution shadow maps.
  67. *
  68. * @type {number}
  69. * @constant
  70. */
  71. const PCFSoftShadowMap = 2;
  72. /**
  73. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  74. * When using VSMShadowMap all shadow receivers will also cast shadows.
  75. *
  76. * @type {number}
  77. * @constant
  78. */
  79. const VSMShadowMap = 3;
  80. /**
  81. * Only front faces are rendered.
  82. *
  83. * @type {number}
  84. * @constant
  85. */
  86. const FrontSide = 0;
  87. /**
  88. * Only back faces are rendered.
  89. *
  90. * @type {number}
  91. * @constant
  92. */
  93. const BackSide = 1;
  94. /**
  95. * Both front and back faces are rendered.
  96. *
  97. * @type {number}
  98. * @constant
  99. */
  100. const DoubleSide = 2;
  101. /**
  102. * No blending is performed which effectively disables
  103. * alpha transparency.
  104. *
  105. * @type {number}
  106. * @constant
  107. */
  108. const NoBlending = 0;
  109. /**
  110. * The default blending.
  111. *
  112. * @type {number}
  113. * @constant
  114. */
  115. const NormalBlending = 1;
  116. /**
  117. * Represents additive blending.
  118. *
  119. * @type {number}
  120. * @constant
  121. */
  122. const AdditiveBlending = 2;
  123. /**
  124. * Represents subtractive blending.
  125. *
  126. * @type {number}
  127. * @constant
  128. */
  129. const SubtractiveBlending = 3;
  130. /**
  131. * Represents multiply blending.
  132. *
  133. * @type {number}
  134. * @constant
  135. */
  136. const MultiplyBlending = 4;
  137. /**
  138. * Represents custom blending.
  139. *
  140. * @type {number}
  141. * @constant
  142. */
  143. const CustomBlending = 5;
  144. /**
  145. * Represents material blending.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const MaterialBlending = 6;
  151. /**
  152. * A `source + destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const AddEquation = 100;
  158. /**
  159. * A `source - destination` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const SubtractEquation = 101;
  165. /**
  166. * A `destination - source` blending equation.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const ReverseSubtractEquation = 102;
  172. /**
  173. * A blend equation that uses the minimum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MinEquation = 103;
  179. /**
  180. * A blend equation that uses the maximum of source and destination.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const MaxEquation = 104;
  186. /**
  187. * Multiplies all colors by `0`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const ZeroFactor = 200;
  193. /**
  194. * Multiplies all colors by `1`.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const OneFactor = 201;
  200. /**
  201. * Multiplies all colors by the source colors.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const SrcColorFactor = 202;
  207. /**
  208. * Multiplies all colors by `1` minus each source color.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const OneMinusSrcColorFactor = 203;
  214. /**
  215. * Multiplies all colors by the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const SrcAlphaFactor = 204;
  221. /**
  222. * Multiplies all colors by 1 minus the source alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const OneMinusSrcAlphaFactor = 205;
  228. /**
  229. * Multiplies all colors by the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const DstAlphaFactor = 206;
  235. /**
  236. * Multiplies all colors by `1` minus the destination alpha value.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const OneMinusDstAlphaFactor = 207;
  242. /**
  243. * Multiplies all colors by the destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const DstColorFactor = 208;
  249. /**
  250. * Multiplies all colors by `1` minus each destination color.
  251. *
  252. * @type {number}
  253. * @constant
  254. */
  255. const OneMinusDstColorFactor = 209;
  256. /**
  257. * Multiplies the RGB colors by the smaller of either the source alpha
  258. * value or the value of `1` minus the destination alpha value. The alpha
  259. * value is multiplied by `1`.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const SrcAlphaSaturateFactor = 210;
  265. /**
  266. * Multiplies all colors by a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const ConstantColorFactor = 211;
  272. /**
  273. * Multiplies all colors by `1` minus a constant color.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const OneMinusConstantColorFactor = 212;
  279. /**
  280. * Multiplies all colors by a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const ConstantAlphaFactor = 213;
  286. /**
  287. * Multiplies all colors by 1 minus a constant alpha value.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const OneMinusConstantAlphaFactor = 214;
  293. /**
  294. * Never pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const NeverDepth = 0;
  300. /**
  301. * Always pass.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const AlwaysDepth = 1;
  307. /**
  308. * Pass if the incoming value is less than the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessDepth = 2;
  314. /**
  315. * Pass if the incoming value is less than or equal to the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const LessEqualDepth = 3;
  321. /**
  322. * Pass if the incoming value equals the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const EqualDepth = 4;
  328. /**
  329. * Pass if the incoming value is greater than or equal to the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterEqualDepth = 5;
  335. /**
  336. * Pass if the incoming value is greater than the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const GreaterDepth = 6;
  342. /**
  343. * Pass if the incoming value is not equal to the depth buffer value.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const NotEqualDepth = 7;
  349. /**
  350. * Multiplies the environment map color with the surface color.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MultiplyOperation = 0;
  356. /**
  357. * Uses reflectivity to blend between the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const MixOperation = 1;
  363. /**
  364. * Adds the two colors.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const AddOperation = 2;
  370. /**
  371. * No tone mapping is applied.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const NoToneMapping = 0;
  377. /**
  378. * Linear tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const LinearToneMapping = 1;
  384. /**
  385. * Reinhard tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const ReinhardToneMapping = 2;
  391. /**
  392. * Cineon tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const CineonToneMapping = 3;
  398. /**
  399. * ACES Filmic tone mapping.
  400. *
  401. * @type {number}
  402. * @constant
  403. */
  404. const ACESFilmicToneMapping = 4;
  405. /**
  406. * Custom tone mapping.
  407. *
  408. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const CustomToneMapping = 5;
  414. /**
  415. * AgX tone mapping.
  416. *
  417. * @type {number}
  418. * @constant
  419. */
  420. const AgXToneMapping = 6;
  421. /**
  422. * Neutral tone mapping.
  423. *
  424. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  425. *
  426. * @type {number}
  427. * @constant
  428. */
  429. const NeutralToneMapping = 7;
  430. /**
  431. * The skinned mesh shares the same world space as the skeleton.
  432. *
  433. * @type {string}
  434. * @constant
  435. */
  436. const AttachedBindMode = 'attached';
  437. /**
  438. * The skinned mesh does not share the same world space as the skeleton.
  439. * This is useful when a skeleton is shared across multiple skinned meshes.
  440. *
  441. * @type {string}
  442. * @constant
  443. */
  444. const DetachedBindMode = 'detached';
  445. /**
  446. * Maps textures using the geometry's UV coordinates.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const UVMapping = 300;
  452. /**
  453. * Reflection mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeReflectionMapping = 301;
  459. /**
  460. * Refraction mapping for cube textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const CubeRefractionMapping = 302;
  466. /**
  467. * Reflection mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularReflectionMapping = 303;
  473. /**
  474. * Refraction mapping for equirectangular textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const EquirectangularRefractionMapping = 304;
  480. /**
  481. * Reflection mapping for PMREM textures.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const CubeUVReflectionMapping = 306;
  487. /**
  488. * The texture will simply repeat to infinity.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const RepeatWrapping = 1000;
  494. /**
  495. * The last pixel of the texture stretches to the edge of the mesh.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const ClampToEdgeWrapping = 1001;
  501. /**
  502. * The texture will repeats to infinity, mirroring on each repeat.
  503. *
  504. * @type {number}
  505. * @constant
  506. */
  507. const MirroredRepeatWrapping = 1002;
  508. /**
  509. * Returns the value of the texture element that is nearest (in Manhattan distance)
  510. * to the specified texture coordinates.
  511. *
  512. * @type {number}
  513. * @constant
  514. */
  515. const NearestFilter = 1003;
  516. /**
  517. * Chooses the mipmap that most closely matches the size of the pixel being textured
  518. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  519. * to produce a texture value.
  520. *
  521. * @type {number}
  522. * @constant
  523. */
  524. const NearestMipmapNearestFilter = 1004;
  525. const NearestMipMapNearestFilter = 1004; // legacy
  526. /**
  527. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  528. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  529. * The final texture value is a weighted average of those two values.
  530. *
  531. * @type {number}
  532. * @constant
  533. */
  534. const NearestMipmapLinearFilter = 1005;
  535. const NearestMipMapLinearFilter = 1005; // legacy
  536. /**
  537. * Returns the weighted average of the four texture elements that are closest to the specified
  538. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  539. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  540. *
  541. * @type {number}
  542. * @constant
  543. */
  544. const LinearFilter = 1006;
  545. /**
  546. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  547. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  548. * center of the pixel) to produce a texture value.
  549. *
  550. * @type {number}
  551. * @constant
  552. */
  553. const LinearMipmapNearestFilter = 1007;
  554. const LinearMipMapNearestFilter = 1007; // legacy
  555. /**
  556. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  557. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  558. * is a weighted average of those two values.
  559. *
  560. * @type {number}
  561. * @constant
  562. */
  563. const LinearMipmapLinearFilter = 1008;
  564. const LinearMipMapLinearFilter = 1008; // legacy
  565. /**
  566. * An unsigned byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const UnsignedByteType = 1009;
  572. /**
  573. * A byte data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ByteType = 1010;
  579. /**
  580. * A short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const ShortType = 1011;
  586. /**
  587. * An unsigned short data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const UnsignedShortType = 1012;
  593. /**
  594. * An int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const IntType = 1013;
  600. /**
  601. * An unsigned int data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const UnsignedIntType = 1014;
  607. /**
  608. * A float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const FloatType = 1015;
  614. /**
  615. * A half float data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const HalfFloatType = 1016;
  621. /**
  622. * An unsigned short 4_4_4_4 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort4444Type = 1017;
  628. /**
  629. * An unsigned short 5_5_5_1 (packed) data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedShort5551Type = 1018;
  635. /**
  636. * An unsigned int 24_8 data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt248Type = 1020;
  642. /**
  643. * An unsigned int 5_9_9_9 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt5999Type = 35902;
  649. /**
  650. * An unsigned int 10_11_11 (packed) data type for textures.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const UnsignedInt101111Type = 35899;
  656. /**
  657. * Discards the red, green and blue components and reads just the alpha component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const AlphaFormat = 1021;
  663. /**
  664. * Discards the alpha component and reads the red, green and blue component.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBFormat = 1022;
  670. /**
  671. * Reads the red, green, blue and alpha components.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const RGBAFormat = 1023;
  677. /**
  678. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  679. *
  680. * @type {number}
  681. * @constant
  682. */
  683. const DepthFormat = 1026;
  684. /**
  685. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  686. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const DepthStencilFormat = 1027;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedFormat = 1028;
  699. /**
  700. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RedIntegerFormat = 1029;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGFormat = 1030;
  713. /**
  714. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGIntegerFormat = 1031;
  720. /**
  721. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBIntegerFormat = 1032;
  727. /**
  728. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGBAIntegerFormat = 1033;
  734. /**
  735. * A DXT1-compressed image in an RGB image format.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGB_S3TC_DXT1_Format = 33776;
  741. /**
  742. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT1_Format = 33777;
  748. /**
  749. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  750. *
  751. * @type {number}
  752. * @constant
  753. */
  754. const RGBA_S3TC_DXT3_Format = 33778;
  755. /**
  756. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  757. * compression in how the alpha compression is done.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGBA_S3TC_DXT5_Format = 33779;
  763. /**
  764. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_4BPPV1_Format = 35840;
  770. /**
  771. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGB_PVRTC_2BPPV1_Format = 35841;
  777. /**
  778. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_4BPPV1_Format = 35842;
  784. /**
  785. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGBA_PVRTC_2BPPV1_Format = 35843;
  791. /**
  792. * ETC1 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC1_Format = 36196;
  798. /**
  799. * ETC2 RGB format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGB_ETC2_Format = 37492;
  805. /**
  806. * ETC2 RGBA format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ETC2_EAC_Format = 37496;
  812. /**
  813. * EAC R11 UNORM format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const R11_EAC_Format = 37488; // 0x9270
  819. /**
  820. * EAC R11 SNORM format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  826. /**
  827. * EAC RG11 UNORM format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RG11_EAC_Format = 37490; // 0x9272
  833. /**
  834. * EAC RG11 SNORM format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  840. /**
  841. * ASTC RGBA 4x4 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_4x4_Format = 37808;
  847. /**
  848. * ASTC RGBA 5x4 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_5x4_Format = 37809;
  854. /**
  855. * ASTC RGBA 5x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_5x5_Format = 37810;
  861. /**
  862. * ASTC RGBA 6x5 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_6x5_Format = 37811;
  868. /**
  869. * ASTC RGBA 6x6 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_6x6_Format = 37812;
  875. /**
  876. * ASTC RGBA 8x5 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_8x5_Format = 37813;
  882. /**
  883. * ASTC RGBA 8x6 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_8x6_Format = 37814;
  889. /**
  890. * ASTC RGBA 8x8 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_8x8_Format = 37815;
  896. /**
  897. * ASTC RGBA 10x5 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_10x5_Format = 37816;
  903. /**
  904. * ASTC RGBA 10x6 format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_ASTC_10x6_Format = 37817;
  910. /**
  911. * ASTC RGBA 10x8 format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGBA_ASTC_10x8_Format = 37818;
  917. /**
  918. * ASTC RGBA 10x10 format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGBA_ASTC_10x10_Format = 37819;
  924. /**
  925. * ASTC RGBA 12x10 format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RGBA_ASTC_12x10_Format = 37820;
  931. /**
  932. * ASTC RGBA 12x12 format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RGBA_ASTC_12x12_Format = 37821;
  938. /**
  939. * BPTC RGBA format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RGBA_BPTC_Format = 36492;
  945. /**
  946. * BPTC Signed RGB format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const RGB_BPTC_SIGNED_Format = 36494;
  952. /**
  953. * BPTC Unsigned RGB format.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const RGB_BPTC_UNSIGNED_Format = 36495;
  959. /**
  960. * RGTC1 Red format.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const RED_RGTC1_Format = 36283;
  966. /**
  967. * RGTC1 Signed Red format.
  968. *
  969. * @type {number}
  970. * @constant
  971. */
  972. const SIGNED_RED_RGTC1_Format = 36284;
  973. /**
  974. * RGTC2 Red Green format.
  975. *
  976. * @type {number}
  977. * @constant
  978. */
  979. const RED_GREEN_RGTC2_Format = 36285;
  980. /**
  981. * RGTC2 Signed Red Green format.
  982. *
  983. * @type {number}
  984. * @constant
  985. */
  986. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  987. /**
  988. * Animations are played once.
  989. *
  990. * @type {number}
  991. * @constant
  992. */
  993. const LoopOnce = 2200;
  994. /**
  995. * Animations are played with a chosen number of repetitions, each time jumping from
  996. * the end of the clip directly to its beginning.
  997. *
  998. * @type {number}
  999. * @constant
  1000. */
  1001. const LoopRepeat = 2201;
  1002. /**
  1003. * Animations are played with a chosen number of repetitions, alternately playing forward
  1004. * and backward.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const LoopPingPong = 2202;
  1010. /**
  1011. * Discrete interpolation mode for keyframe tracks.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const InterpolateDiscrete = 2300;
  1017. /**
  1018. * Linear interpolation mode for keyframe tracks.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const InterpolateLinear = 2301;
  1024. /**
  1025. * Smooth interpolation mode for keyframe tracks.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const InterpolateSmooth = 2302;
  1031. /**
  1032. * Zero curvature ending for animations.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const ZeroCurvatureEnding = 2400;
  1038. /**
  1039. * Zero slope ending for animations.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const ZeroSlopeEnding = 2401;
  1045. /**
  1046. * Wrap around ending for animations.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const WrapAroundEnding = 2402;
  1052. /**
  1053. * Default animation blend mode.
  1054. *
  1055. * @type {number}
  1056. * @constant
  1057. */
  1058. const NormalAnimationBlendMode = 2500;
  1059. /**
  1060. * Additive animation blend mode. Can be used to layer motions on top of
  1061. * each other to build complex performances from smaller re-usable assets.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const AdditiveAnimationBlendMode = 2501;
  1067. /**
  1068. * For every three vertices draw a single triangle.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const TrianglesDrawMode = 0;
  1074. /**
  1075. * For each vertex draw a triangle from the last three vertices.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TriangleStripDrawMode = 1;
  1081. /**
  1082. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const TriangleFanDrawMode = 2;
  1088. /**
  1089. * The depth value is inverted (1.0 - z) for visualization purposes.
  1090. *
  1091. * @type {number}
  1092. * @constant
  1093. */
  1094. const BasicDepthPacking = 3200;
  1095. /**
  1096. * The depth value is packed into 32 bit RGBA.
  1097. *
  1098. * @type {number}
  1099. * @constant
  1100. */
  1101. const RGBADepthPacking = 3201;
  1102. /**
  1103. * The depth value is packed into 24 bit RGB.
  1104. *
  1105. * @type {number}
  1106. * @constant
  1107. */
  1108. const RGBDepthPacking = 3202;
  1109. /**
  1110. * The depth value is packed into 16 bit RG.
  1111. *
  1112. * @type {number}
  1113. * @constant
  1114. */
  1115. const RGDepthPacking = 3203;
  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. * Compatibility flags for features that may not be supported across all platforms.
  1493. *
  1494. * @type {Object}
  1495. * @constant
  1496. */
  1497. const Compatibility = {
  1498. TEXTURE_COMPARE: 'depthTextureCompare'
  1499. };
  1500. /**
  1501. * This type represents mouse buttons and interaction types in context of controls.
  1502. *
  1503. * @typedef {Object} ConstantsMouse
  1504. * @property {number} MIDDLE - The left mouse button.
  1505. * @property {number} LEFT - The middle mouse button.
  1506. * @property {number} RIGHT - The right mouse button.
  1507. * @property {number} ROTATE - A rotate interaction.
  1508. * @property {number} DOLLY - A dolly interaction.
  1509. * @property {number} PAN - A pan interaction.
  1510. **/
  1511. /**
  1512. * This type represents touch interaction types in context of controls.
  1513. *
  1514. * @typedef {Object} ConstantsTouch
  1515. * @property {number} ROTATE - A rotate interaction.
  1516. * @property {number} PAN - A pan interaction.
  1517. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1518. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1519. **/
  1520. /**
  1521. * This type represents the different timestamp query types.
  1522. *
  1523. * @typedef {Object} ConstantsTimestampQuery
  1524. * @property {string} COMPUTE - A `compute` timestamp query.
  1525. * @property {string} RENDER - A `render` timestamp query.
  1526. **/
  1527. /**
  1528. * Represents the different interpolation sampling types.
  1529. *
  1530. * @typedef {Object} ConstantsInterpolationSamplingType
  1531. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1532. * @property {string} LINEAR - Linear interpolation.
  1533. * @property {string} FLAT - Flat interpolation.
  1534. */
  1535. /**
  1536. * Represents the different interpolation sampling modes.
  1537. *
  1538. * @typedef {Object} ConstantsInterpolationSamplingMode
  1539. * @property {string} NORMAL - Normal sampling mode.
  1540. * @property {string} CENTROID - Centroid sampling mode.
  1541. * @property {string} SAMPLE - Sample-specific sampling mode.
  1542. * @property {string} FIRST - Flat interpolation using the first vertex.
  1543. * @property {string} EITHER - Flat interpolation using either vertex.
  1544. */
  1545. /**
  1546. * Finds the minimum value in an array.
  1547. *
  1548. * @private
  1549. * @param {Array<number>} array - The array to search for the minimum value.
  1550. * @return {number} The minimum value in the array, or Infinity if the array is empty.
  1551. */
  1552. /**
  1553. * Checks if an array contains values that require Uint32 representation.
  1554. *
  1555. * This function determines whether the array contains any values >= 65535,
  1556. * which would require a Uint32Array rather than a Uint16Array for proper storage.
  1557. * The function iterates from the end of the array, assuming larger values are
  1558. * typically located at the end.
  1559. *
  1560. * @private
  1561. * @param {Array<number>} array - The array to check.
  1562. * @return {boolean} True if the array contains values >= 65535, false otherwise.
  1563. */
  1564. function arrayNeedsUint32( array ) {
  1565. // assumes larger values usually on last
  1566. for ( let i = array.length - 1; i >= 0; -- i ) {
  1567. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1568. }
  1569. return false;
  1570. }
  1571. /**
  1572. * Map of typed array constructor names to their constructors.
  1573. * This mapping enables dynamic creation of typed arrays based on string type names.
  1574. *
  1575. * @private
  1576. * @constant
  1577. * @type {Object<string, TypedArrayConstructor>}
  1578. */
  1579. const TYPED_ARRAYS = {
  1580. Int8Array: Int8Array,
  1581. Uint8Array: Uint8Array,
  1582. Uint8ClampedArray: Uint8ClampedArray,
  1583. Int16Array: Int16Array,
  1584. Uint16Array: Uint16Array,
  1585. Int32Array: Int32Array,
  1586. Uint32Array: Uint32Array,
  1587. Float32Array: Float32Array,
  1588. Float64Array: Float64Array
  1589. };
  1590. /**
  1591. * Creates a typed array of the specified type from the given buffer.
  1592. *
  1593. * @private
  1594. * @param {string} type - The name of the typed array type (e.g., 'Float32Array', 'Uint16Array').
  1595. * @param {ArrayBuffer} buffer - The buffer to create the typed array from.
  1596. * @return {TypedArray} A new typed array of the specified type.
  1597. */
  1598. function getTypedArray( type, buffer ) {
  1599. return new TYPED_ARRAYS[ type ]( buffer );
  1600. }
  1601. /**
  1602. * Returns `true` if the given object is a typed array.
  1603. *
  1604. * @param {any} array - The object to check.
  1605. * @return {boolean} Whether the given object is a typed array.
  1606. */
  1607. function isTypedArray( array ) {
  1608. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1609. }
  1610. /**
  1611. * Creates an XHTML element with the specified tag name.
  1612. *
  1613. * This function uses the XHTML namespace to create DOM elements,
  1614. * ensuring proper element creation in XML-based contexts.
  1615. *
  1616. * @private
  1617. * @param {string} name - The tag name of the element to create (e.g., 'canvas', 'div').
  1618. * @return {HTMLElement} The created XHTML element.
  1619. */
  1620. function createElementNS( name ) {
  1621. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1622. }
  1623. /**
  1624. * Creates a canvas element configured for block display.
  1625. *
  1626. * This is a convenience function that creates a canvas element with
  1627. * display style set to 'block', which is commonly used in three.js
  1628. * rendering contexts to avoid inline element spacing issues.
  1629. *
  1630. * @return {HTMLCanvasElement} A canvas element with display set to 'block'.
  1631. */
  1632. function createCanvasElement() {
  1633. const canvas = createElementNS( 'canvas' );
  1634. canvas.style.display = 'block';
  1635. return canvas;
  1636. }
  1637. /**
  1638. * Internal cache for tracking warning messages to prevent duplicate warnings.
  1639. *
  1640. * @private
  1641. * @type {Object<string, boolean>}
  1642. */
  1643. const _cache = {};
  1644. /**
  1645. * Custom console function handler for intercepting log, warn, and error calls.
  1646. *
  1647. * @private
  1648. * @type {Function|null}
  1649. */
  1650. let _setConsoleFunction = null;
  1651. /**
  1652. * Sets a custom function to handle console output.
  1653. *
  1654. * This allows external code to intercept and handle console.log, console.warn,
  1655. * and console.error calls made by three.js, which is useful for custom logging,
  1656. * testing, or debugging workflows.
  1657. *
  1658. * @param {Function} fn - The function to handle console output. Should accept
  1659. * (type, message, ...params) where type is 'log', 'warn', or 'error'.
  1660. */
  1661. function setConsoleFunction( fn ) {
  1662. _setConsoleFunction = fn;
  1663. }
  1664. /**
  1665. * Gets the currently set custom console function.
  1666. *
  1667. * @return {Function|null} The custom console function, or null if not set.
  1668. */
  1669. function getConsoleFunction() {
  1670. return _setConsoleFunction;
  1671. }
  1672. /**
  1673. * Logs an informational message with the 'THREE.' prefix.
  1674. *
  1675. * If a custom console function is set via setConsoleFunction(), it will be used
  1676. * instead of the native console.log. The first parameter is treated as the
  1677. * method name and is automatically prefixed with 'THREE.'.
  1678. *
  1679. * @param {...any} params - The message components. The first param is used as
  1680. * the method name and prefixed with 'THREE.'.
  1681. */
  1682. function log( ...params ) {
  1683. const message = 'THREE.' + params.shift();
  1684. if ( _setConsoleFunction ) {
  1685. _setConsoleFunction( 'log', message, ...params );
  1686. } else {
  1687. console.log( message, ...params );
  1688. }
  1689. }
  1690. /**
  1691. * Logs a warning message with the 'THREE.' prefix.
  1692. *
  1693. * If a custom console function is set via setConsoleFunction(), it will be used
  1694. * instead of the native console.warn. The first parameter is treated as the
  1695. * method name and is automatically prefixed with 'THREE.'.
  1696. *
  1697. * @param {...any} params - The message components. The first param is used as
  1698. * the method name and prefixed with 'THREE.'.
  1699. */
  1700. function warn( ...params ) {
  1701. const message = 'THREE.' + params.shift();
  1702. if ( _setConsoleFunction ) {
  1703. _setConsoleFunction( 'warn', message, ...params );
  1704. } else {
  1705. console.warn( message, ...params );
  1706. }
  1707. }
  1708. /**
  1709. * Logs an error message with the 'THREE.' prefix.
  1710. *
  1711. * If a custom console function is set via setConsoleFunction(), it will be used
  1712. * instead of the native console.error. The first parameter is treated as the
  1713. * method name and is automatically prefixed with 'THREE.'.
  1714. *
  1715. * @param {...any} params - The message components. The first param is used as
  1716. * the method name and prefixed with 'THREE.'.
  1717. */
  1718. function error( ...params ) {
  1719. const message = 'THREE.' + params.shift();
  1720. if ( _setConsoleFunction ) {
  1721. _setConsoleFunction( 'error', message, ...params );
  1722. } else {
  1723. console.error( message, ...params );
  1724. }
  1725. }
  1726. /**
  1727. * Logs a warning message only once, preventing duplicate warnings.
  1728. *
  1729. * This function maintains an internal cache of warning messages and will only
  1730. * output each unique warning message once. Useful for warnings that may be
  1731. * triggered repeatedly but should only be shown to the user once.
  1732. *
  1733. * @param {...any} params - The warning message components.
  1734. */
  1735. function warnOnce( ...params ) {
  1736. const message = params.join( ' ' );
  1737. if ( message in _cache ) return;
  1738. _cache[ message ] = true;
  1739. warn( ...params );
  1740. }
  1741. /**
  1742. * Asynchronously probes for WebGL sync object completion.
  1743. *
  1744. * This function creates a promise that resolves when the WebGL sync object
  1745. * signals completion or rejects if the sync operation fails. It uses polling
  1746. * at the specified interval to check the sync status without blocking the
  1747. * main thread. This is useful for GPU-CPU synchronization in WebGL contexts.
  1748. *
  1749. * @private
  1750. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL rendering context.
  1751. * @param {WebGLSync} sync - The WebGL sync object to wait for.
  1752. * @param {number} interval - The polling interval in milliseconds.
  1753. * @return {Promise<void>} A promise that resolves when the sync completes or rejects if it fails.
  1754. */
  1755. function probeAsync( gl, sync, interval ) {
  1756. return new Promise( function ( resolve, reject ) {
  1757. function probe() {
  1758. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1759. case gl.WAIT_FAILED:
  1760. reject();
  1761. break;
  1762. case gl.TIMEOUT_EXPIRED:
  1763. setTimeout( probe, interval );
  1764. break;
  1765. default:
  1766. resolve();
  1767. }
  1768. }
  1769. setTimeout( probe, interval );
  1770. } );
  1771. }
  1772. /**
  1773. * This modules allows to dispatch event objects on custom JavaScript objects.
  1774. *
  1775. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1776. *
  1777. * Code Example:
  1778. * ```js
  1779. * class Car extends EventDispatcher {
  1780. * start() {
  1781. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1782. * }
  1783. *};
  1784. *
  1785. * // Using events with the custom object
  1786. * const car = new Car();
  1787. * car.addEventListener( 'start', function ( event ) {
  1788. * alert( event.message );
  1789. * } );
  1790. *
  1791. * car.start();
  1792. * ```
  1793. */
  1794. class EventDispatcher {
  1795. /**
  1796. * Adds the given event listener to the given event type.
  1797. *
  1798. * @param {string} type - The type of event to listen to.
  1799. * @param {Function} listener - The function that gets called when the event is fired.
  1800. */
  1801. addEventListener( type, listener ) {
  1802. if ( this._listeners === undefined ) this._listeners = {};
  1803. const listeners = this._listeners;
  1804. if ( listeners[ type ] === undefined ) {
  1805. listeners[ type ] = [];
  1806. }
  1807. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1808. listeners[ type ].push( listener );
  1809. }
  1810. }
  1811. /**
  1812. * Returns `true` if the given event listener has been added to the given event type.
  1813. *
  1814. * @param {string} type - The type of event.
  1815. * @param {Function} listener - The listener to check.
  1816. * @return {boolean} Whether the given event listener has been added to the given event type.
  1817. */
  1818. hasEventListener( type, listener ) {
  1819. const listeners = this._listeners;
  1820. if ( listeners === undefined ) return false;
  1821. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1822. }
  1823. /**
  1824. * Removes the given event listener from the given event type.
  1825. *
  1826. * @param {string} type - The type of event.
  1827. * @param {Function} listener - The listener to remove.
  1828. */
  1829. removeEventListener( type, listener ) {
  1830. const listeners = this._listeners;
  1831. if ( listeners === undefined ) return;
  1832. const listenerArray = listeners[ type ];
  1833. if ( listenerArray !== undefined ) {
  1834. const index = listenerArray.indexOf( listener );
  1835. if ( index !== -1 ) {
  1836. listenerArray.splice( index, 1 );
  1837. }
  1838. }
  1839. }
  1840. /**
  1841. * Dispatches an event object.
  1842. *
  1843. * @param {Object} event - The event that gets fired.
  1844. */
  1845. dispatchEvent( event ) {
  1846. const listeners = this._listeners;
  1847. if ( listeners === undefined ) return;
  1848. const listenerArray = listeners[ event.type ];
  1849. if ( listenerArray !== undefined ) {
  1850. event.target = this;
  1851. // Make a copy, in case listeners are removed while iterating.
  1852. const array = listenerArray.slice( 0 );
  1853. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1854. array[ i ].call( this, event );
  1855. }
  1856. event.target = null;
  1857. }
  1858. }
  1859. }
  1860. 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' ];
  1861. let _seed = 1234567;
  1862. const DEG2RAD = Math.PI / 180;
  1863. const RAD2DEG = 180 / Math.PI;
  1864. /**
  1865. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1866. * (universally unique identifier).
  1867. *
  1868. * @return {string} The UUID.
  1869. */
  1870. function generateUUID() {
  1871. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1872. const d0 = Math.random() * 0xffffffff | 0;
  1873. const d1 = Math.random() * 0xffffffff | 0;
  1874. const d2 = Math.random() * 0xffffffff | 0;
  1875. const d3 = Math.random() * 0xffffffff | 0;
  1876. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1877. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1878. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1879. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1880. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1881. return uuid.toLowerCase();
  1882. }
  1883. /**
  1884. * Clamps the given value between min and max.
  1885. *
  1886. * @param {number} value - The value to clamp.
  1887. * @param {number} min - The min value.
  1888. * @param {number} max - The max value.
  1889. * @return {number} The clamped value.
  1890. */
  1891. function clamp( value, min, max ) {
  1892. return Math.max( min, Math.min( max, value ) );
  1893. }
  1894. /**
  1895. * Computes the Euclidean modulo of the given parameters that
  1896. * is `( ( n % m ) + m ) % m`.
  1897. *
  1898. * @param {number} n - The first parameter.
  1899. * @param {number} m - The second parameter.
  1900. * @return {number} The Euclidean modulo.
  1901. */
  1902. function euclideanModulo( n, m ) {
  1903. // https://en.wikipedia.org/wiki/Modulo_operation
  1904. return ( ( n % m ) + m ) % m;
  1905. }
  1906. /**
  1907. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1908. * for the given value.
  1909. *
  1910. * @param {number} x - The value to be mapped.
  1911. * @param {number} a1 - Minimum value for range A.
  1912. * @param {number} a2 - Maximum value for range A.
  1913. * @param {number} b1 - Minimum value for range B.
  1914. * @param {number} b2 - Maximum value for range B.
  1915. * @return {number} The mapped value.
  1916. */
  1917. function mapLinear( x, a1, a2, b1, b2 ) {
  1918. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1919. }
  1920. /**
  1921. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1922. * between the start and end point.
  1923. *
  1924. * @param {number} x - The start point
  1925. * @param {number} y - The end point.
  1926. * @param {number} value - A value between start and end.
  1927. * @return {number} The interpolation factor.
  1928. */
  1929. function inverseLerp( x, y, value ) {
  1930. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1931. if ( x !== y ) {
  1932. return ( value - x ) / ( y - x );
  1933. } else {
  1934. return 0;
  1935. }
  1936. }
  1937. /**
  1938. * Returns a value linearly interpolated from two known points based on the given interval -
  1939. * `t = 0` will return `x` and `t = 1` will return `y`.
  1940. *
  1941. * @param {number} x - The start point
  1942. * @param {number} y - The end point.
  1943. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1944. * @return {number} The interpolated value.
  1945. */
  1946. function lerp( x, y, t ) {
  1947. return ( 1 - t ) * x + t * y;
  1948. }
  1949. /**
  1950. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1951. * time to maintain frame rate independent movement. For details, see
  1952. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1953. *
  1954. * @param {number} x - The current point.
  1955. * @param {number} y - The target point.
  1956. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1957. * and a lower value will make the movement more gradual.
  1958. * @param {number} dt - Delta time in seconds.
  1959. * @return {number} The interpolated value.
  1960. */
  1961. function damp( x, y, lambda, dt ) {
  1962. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1963. }
  1964. /**
  1965. * Returns a value that alternates between `0` and the given `length` parameter.
  1966. *
  1967. * @param {number} x - The value to pingpong.
  1968. * @param {number} [length=1] - The positive value the function will pingpong to.
  1969. * @return {number} The alternated value.
  1970. */
  1971. function pingpong( x, length = 1 ) {
  1972. // https://www.desmos.com/calculator/vcsjnyz7x4
  1973. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1974. }
  1975. /**
  1976. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1977. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1978. * the `min` and `max`.
  1979. *
  1980. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1981. *
  1982. * @param {number} x - The value to evaluate based on its position between min and max.
  1983. * @param {number} min - The min value. Any x value below min will be `0`.
  1984. * @param {number} max - The max value. Any x value above max will be `1`.
  1985. * @return {number} The alternated value.
  1986. */
  1987. function smoothstep( x, min, max ) {
  1988. if ( x <= min ) return 0;
  1989. if ( x >= max ) return 1;
  1990. x = ( x - min ) / ( max - min );
  1991. return x * x * ( 3 - 2 * x );
  1992. }
  1993. /**
  1994. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1995. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1996. *
  1997. * @param {number} x - The value to evaluate based on its position between min and max.
  1998. * @param {number} min - The min value. Any x value below min will be `0`.
  1999. * @param {number} max - The max value. Any x value above max will be `1`.
  2000. * @return {number} The alternated value.
  2001. */
  2002. function smootherstep( x, min, max ) {
  2003. if ( x <= min ) return 0;
  2004. if ( x >= max ) return 1;
  2005. x = ( x - min ) / ( max - min );
  2006. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  2007. }
  2008. /**
  2009. * Returns a random integer from `<low, high>` interval.
  2010. *
  2011. * @param {number} low - The lower value boundary.
  2012. * @param {number} high - The upper value boundary
  2013. * @return {number} A random integer.
  2014. */
  2015. function randInt( low, high ) {
  2016. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2017. }
  2018. /**
  2019. * Returns a random float from `<low, high>` interval.
  2020. *
  2021. * @param {number} low - The lower value boundary.
  2022. * @param {number} high - The upper value boundary
  2023. * @return {number} A random float.
  2024. */
  2025. function randFloat( low, high ) {
  2026. return low + Math.random() * ( high - low );
  2027. }
  2028. /**
  2029. * Returns a random integer from `<-range/2, range/2>` interval.
  2030. *
  2031. * @param {number} range - Defines the value range.
  2032. * @return {number} A random float.
  2033. */
  2034. function randFloatSpread( range ) {
  2035. return range * ( 0.5 - Math.random() );
  2036. }
  2037. /**
  2038. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2039. *
  2040. * @param {number} [s] - The integer seed.
  2041. * @return {number} A random float.
  2042. */
  2043. function seededRandom( s ) {
  2044. if ( s !== undefined ) _seed = s;
  2045. // Mulberry32 generator
  2046. let t = _seed += 0x6D2B79F5;
  2047. t = Math.imul( t ^ t >>> 15, t | 1 );
  2048. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  2049. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  2050. }
  2051. /**
  2052. * Converts degrees to radians.
  2053. *
  2054. * @param {number} degrees - A value in degrees.
  2055. * @return {number} The converted value in radians.
  2056. */
  2057. function degToRad( degrees ) {
  2058. return degrees * DEG2RAD;
  2059. }
  2060. /**
  2061. * Converts radians to degrees.
  2062. *
  2063. * @param {number} radians - A value in radians.
  2064. * @return {number} The converted value in degrees.
  2065. */
  2066. function radToDeg( radians ) {
  2067. return radians * RAD2DEG;
  2068. }
  2069. /**
  2070. * Returns `true` if the given number is a power of two.
  2071. *
  2072. * @param {number} value - The value to check.
  2073. * @return {boolean} Whether the given number is a power of two or not.
  2074. */
  2075. function isPowerOfTwo( value ) {
  2076. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  2077. }
  2078. /**
  2079. * Returns the smallest power of two that is greater than or equal to the given number.
  2080. *
  2081. * @param {number} value - The value to find a POT for.
  2082. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2083. */
  2084. function ceilPowerOfTwo( value ) {
  2085. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  2086. }
  2087. /**
  2088. * Returns the largest power of two that is less than or equal to the given number.
  2089. *
  2090. * @param {number} value - The value to find a POT for.
  2091. * @return {number} The largest power of two that is less than or equal to the given number.
  2092. */
  2093. function floorPowerOfTwo( value ) {
  2094. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  2095. }
  2096. /**
  2097. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2098. * defined by the given angles and order.
  2099. *
  2100. * Rotations are applied to the axes in the order specified by order:
  2101. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2102. *
  2103. * @param {Quaternion} q - The quaternion to set.
  2104. * @param {number} a - The rotation applied to the first axis, in radians.
  2105. * @param {number} b - The rotation applied to the second axis, in radians.
  2106. * @param {number} c - The rotation applied to the third axis, in radians.
  2107. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2108. */
  2109. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  2110. const cos = Math.cos;
  2111. const sin = Math.sin;
  2112. const c2 = cos( b / 2 );
  2113. const s2 = sin( b / 2 );
  2114. const c13 = cos( ( a + c ) / 2 );
  2115. const s13 = sin( ( a + c ) / 2 );
  2116. const c1_3 = cos( ( a - c ) / 2 );
  2117. const s1_3 = sin( ( a - c ) / 2 );
  2118. const c3_1 = cos( ( c - a ) / 2 );
  2119. const s3_1 = sin( ( c - a ) / 2 );
  2120. switch ( order ) {
  2121. case 'XYX':
  2122. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  2123. break;
  2124. case 'YZY':
  2125. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  2126. break;
  2127. case 'ZXZ':
  2128. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  2129. break;
  2130. case 'XZX':
  2131. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  2132. break;
  2133. case 'YXY':
  2134. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  2135. break;
  2136. case 'ZYZ':
  2137. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  2138. break;
  2139. default:
  2140. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  2141. }
  2142. }
  2143. /**
  2144. * Denormalizes the given value according to the given typed array.
  2145. *
  2146. * @param {number} value - The value to denormalize.
  2147. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2148. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2149. */
  2150. function denormalize( value, array ) {
  2151. switch ( array.constructor ) {
  2152. case Float32Array:
  2153. return value;
  2154. case Uint32Array:
  2155. return value / 4294967295.0;
  2156. case Uint16Array:
  2157. return value / 65535.0;
  2158. case Uint8Array:
  2159. return value / 255.0;
  2160. case Int32Array:
  2161. return Math.max( value / 2147483647.0, -1 );
  2162. case Int16Array:
  2163. return Math.max( value / 32767.0, -1 );
  2164. case Int8Array:
  2165. return Math.max( value / 127.0, -1 );
  2166. default:
  2167. throw new Error( 'Invalid component type.' );
  2168. }
  2169. }
  2170. /**
  2171. * Normalizes the given value according to the given typed array.
  2172. *
  2173. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2174. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2175. * @return {number} The normalize value.
  2176. */
  2177. function normalize( value, array ) {
  2178. switch ( array.constructor ) {
  2179. case Float32Array:
  2180. return value;
  2181. case Uint32Array:
  2182. return Math.round( value * 4294967295.0 );
  2183. case Uint16Array:
  2184. return Math.round( value * 65535.0 );
  2185. case Uint8Array:
  2186. return Math.round( value * 255.0 );
  2187. case Int32Array:
  2188. return Math.round( value * 2147483647.0 );
  2189. case Int16Array:
  2190. return Math.round( value * 32767.0 );
  2191. case Int8Array:
  2192. return Math.round( value * 127.0 );
  2193. default:
  2194. throw new Error( 'Invalid component type.' );
  2195. }
  2196. }
  2197. /**
  2198. * @class
  2199. * @classdesc A collection of math utility functions.
  2200. * @hideconstructor
  2201. */
  2202. const MathUtils = {
  2203. DEG2RAD: DEG2RAD,
  2204. RAD2DEG: RAD2DEG,
  2205. /**
  2206. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2207. * (universally unique identifier).
  2208. *
  2209. * @static
  2210. * @method
  2211. * @return {string} The UUID.
  2212. */
  2213. generateUUID: generateUUID,
  2214. /**
  2215. * Clamps the given value between min and max.
  2216. *
  2217. * @static
  2218. * @method
  2219. * @param {number} value - The value to clamp.
  2220. * @param {number} min - The min value.
  2221. * @param {number} max - The max value.
  2222. * @return {number} The clamped value.
  2223. */
  2224. clamp: clamp,
  2225. /**
  2226. * Computes the Euclidean modulo of the given parameters that
  2227. * is `( ( n % m ) + m ) % m`.
  2228. *
  2229. * @static
  2230. * @method
  2231. * @param {number} n - The first parameter.
  2232. * @param {number} m - The second parameter.
  2233. * @return {number} The Euclidean modulo.
  2234. */
  2235. euclideanModulo: euclideanModulo,
  2236. /**
  2237. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2238. * for the given value.
  2239. *
  2240. * @static
  2241. * @method
  2242. * @param {number} x - The value to be mapped.
  2243. * @param {number} a1 - Minimum value for range A.
  2244. * @param {number} a2 - Maximum value for range A.
  2245. * @param {number} b1 - Minimum value for range B.
  2246. * @param {number} b2 - Maximum value for range B.
  2247. * @return {number} The mapped value.
  2248. */
  2249. mapLinear: mapLinear,
  2250. /**
  2251. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2252. * between the start and end point.
  2253. *
  2254. * @static
  2255. * @method
  2256. * @param {number} x - The start point
  2257. * @param {number} y - The end point.
  2258. * @param {number} value - A value between start and end.
  2259. * @return {number} The interpolation factor.
  2260. */
  2261. inverseLerp: inverseLerp,
  2262. /**
  2263. * Returns a value linearly interpolated from two known points based on the given interval -
  2264. * `t = 0` will return `x` and `t = 1` will return `y`.
  2265. *
  2266. * @static
  2267. * @method
  2268. * @param {number} x - The start point
  2269. * @param {number} y - The end point.
  2270. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2271. * @return {number} The interpolated value.
  2272. */
  2273. lerp: lerp,
  2274. /**
  2275. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2276. * time to maintain frame rate independent movement. For details, see
  2277. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2278. *
  2279. * @static
  2280. * @method
  2281. * @param {number} x - The current point.
  2282. * @param {number} y - The target point.
  2283. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2284. * and a lower value will make the movement more gradual.
  2285. * @param {number} dt - Delta time in seconds.
  2286. * @return {number} The interpolated value.
  2287. */
  2288. damp: damp,
  2289. /**
  2290. * Returns a value that alternates between `0` and the given `length` parameter.
  2291. *
  2292. * @static
  2293. * @method
  2294. * @param {number} x - The value to pingpong.
  2295. * @param {number} [length=1] - The positive value the function will pingpong to.
  2296. * @return {number} The alternated value.
  2297. */
  2298. pingpong: pingpong,
  2299. /**
  2300. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2301. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2302. * the `min` and `max`.
  2303. *
  2304. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2305. *
  2306. * @static
  2307. * @method
  2308. * @param {number} x - The value to evaluate based on its position between min and max.
  2309. * @param {number} min - The min value. Any x value below min will be `0`.
  2310. * @param {number} max - The max value. Any x value above max will be `1`.
  2311. * @return {number} The alternated value.
  2312. */
  2313. smoothstep: smoothstep,
  2314. /**
  2315. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2316. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2317. *
  2318. * @static
  2319. * @method
  2320. * @param {number} x - The value to evaluate based on its position between min and max.
  2321. * @param {number} min - The min value. Any x value below min will be `0`.
  2322. * @param {number} max - The max value. Any x value above max will be `1`.
  2323. * @return {number} The alternated value.
  2324. */
  2325. smootherstep: smootherstep,
  2326. /**
  2327. * Returns a random integer from `<low, high>` interval.
  2328. *
  2329. * @static
  2330. * @method
  2331. * @param {number} low - The lower value boundary.
  2332. * @param {number} high - The upper value boundary
  2333. * @return {number} A random integer.
  2334. */
  2335. randInt: randInt,
  2336. /**
  2337. * Returns a random float from `<low, high>` interval.
  2338. *
  2339. * @static
  2340. * @method
  2341. * @param {number} low - The lower value boundary.
  2342. * @param {number} high - The upper value boundary
  2343. * @return {number} A random float.
  2344. */
  2345. randFloat: randFloat,
  2346. /**
  2347. * Returns a random integer from `<-range/2, range/2>` interval.
  2348. *
  2349. * @static
  2350. * @method
  2351. * @param {number} range - Defines the value range.
  2352. * @return {number} A random float.
  2353. */
  2354. randFloatSpread: randFloatSpread,
  2355. /**
  2356. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2357. *
  2358. * @static
  2359. * @method
  2360. * @param {number} [s] - The integer seed.
  2361. * @return {number} A random float.
  2362. */
  2363. seededRandom: seededRandom,
  2364. /**
  2365. * Converts degrees to radians.
  2366. *
  2367. * @static
  2368. * @method
  2369. * @param {number} degrees - A value in degrees.
  2370. * @return {number} The converted value in radians.
  2371. */
  2372. degToRad: degToRad,
  2373. /**
  2374. * Converts radians to degrees.
  2375. *
  2376. * @static
  2377. * @method
  2378. * @param {number} radians - A value in radians.
  2379. * @return {number} The converted value in degrees.
  2380. */
  2381. radToDeg: radToDeg,
  2382. /**
  2383. * Returns `true` if the given number is a power of two.
  2384. *
  2385. * @static
  2386. * @method
  2387. * @param {number} value - The value to check.
  2388. * @return {boolean} Whether the given number is a power of two or not.
  2389. */
  2390. isPowerOfTwo: isPowerOfTwo,
  2391. /**
  2392. * Returns the smallest power of two that is greater than or equal to the given number.
  2393. *
  2394. * @static
  2395. * @method
  2396. * @param {number} value - The value to find a POT for.
  2397. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2398. */
  2399. ceilPowerOfTwo: ceilPowerOfTwo,
  2400. /**
  2401. * Returns the largest power of two that is less than or equal to the given number.
  2402. *
  2403. * @static
  2404. * @method
  2405. * @param {number} value - The value to find a POT for.
  2406. * @return {number} The largest power of two that is less than or equal to the given number.
  2407. */
  2408. floorPowerOfTwo: floorPowerOfTwo,
  2409. /**
  2410. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2411. * defined by the given angles and order.
  2412. *
  2413. * Rotations are applied to the axes in the order specified by order:
  2414. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2415. *
  2416. * @static
  2417. * @method
  2418. * @param {Quaternion} q - The quaternion to set.
  2419. * @param {number} a - The rotation applied to the first axis, in radians.
  2420. * @param {number} b - The rotation applied to the second axis, in radians.
  2421. * @param {number} c - The rotation applied to the third axis, in radians.
  2422. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2423. */
  2424. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2425. /**
  2426. * Normalizes the given value according to the given typed array.
  2427. *
  2428. * @static
  2429. * @method
  2430. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2431. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2432. * @return {number} The normalize value.
  2433. */
  2434. normalize: normalize,
  2435. /**
  2436. * Denormalizes the given value according to the given typed array.
  2437. *
  2438. * @static
  2439. * @method
  2440. * @param {number} value - The value to denormalize.
  2441. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2442. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2443. */
  2444. denormalize: denormalize
  2445. };
  2446. /**
  2447. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2448. * (labeled x and y), which can be used to represent a number of things, such as:
  2449. *
  2450. * - A point in 2D space (i.e. a position on a plane).
  2451. * - A direction and length across a plane. In three.js the length will
  2452. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2453. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2454. * - Any arbitrary ordered pair of numbers.
  2455. *
  2456. * There are other things a 2D vector can be used to represent, such as
  2457. * momentum vectors, complex numbers and so on, however these are the most
  2458. * common uses in three.js.
  2459. *
  2460. * Iterating through a vector instance will yield its components `(x, y)` in
  2461. * the corresponding order.
  2462. * ```js
  2463. * const a = new THREE.Vector2( 0, 1 );
  2464. *
  2465. * //no arguments; will be initialised to (0, 0)
  2466. * const b = new THREE.Vector2( );
  2467. *
  2468. * const d = a.distanceTo( b );
  2469. * ```
  2470. */
  2471. class Vector2 {
  2472. /**
  2473. * Constructs a new 2D vector.
  2474. *
  2475. * @param {number} [x=0] - The x value of this vector.
  2476. * @param {number} [y=0] - The y value of this vector.
  2477. */
  2478. constructor( x = 0, y = 0 ) {
  2479. /**
  2480. * This flag can be used for type testing.
  2481. *
  2482. * @type {boolean}
  2483. * @readonly
  2484. * @default true
  2485. */
  2486. Vector2.prototype.isVector2 = true;
  2487. /**
  2488. * The x value of this vector.
  2489. *
  2490. * @type {number}
  2491. */
  2492. this.x = x;
  2493. /**
  2494. * The y value of this vector.
  2495. *
  2496. * @type {number}
  2497. */
  2498. this.y = y;
  2499. }
  2500. /**
  2501. * Alias for {@link Vector2#x}.
  2502. *
  2503. * @type {number}
  2504. */
  2505. get width() {
  2506. return this.x;
  2507. }
  2508. set width( value ) {
  2509. this.x = value;
  2510. }
  2511. /**
  2512. * Alias for {@link Vector2#y}.
  2513. *
  2514. * @type {number}
  2515. */
  2516. get height() {
  2517. return this.y;
  2518. }
  2519. set height( value ) {
  2520. this.y = value;
  2521. }
  2522. /**
  2523. * Sets the vector components.
  2524. *
  2525. * @param {number} x - The value of the x component.
  2526. * @param {number} y - The value of the y component.
  2527. * @return {Vector2} A reference to this vector.
  2528. */
  2529. set( x, y ) {
  2530. this.x = x;
  2531. this.y = y;
  2532. return this;
  2533. }
  2534. /**
  2535. * Sets the vector components to the same value.
  2536. *
  2537. * @param {number} scalar - The value to set for all vector components.
  2538. * @return {Vector2} A reference to this vector.
  2539. */
  2540. setScalar( scalar ) {
  2541. this.x = scalar;
  2542. this.y = scalar;
  2543. return this;
  2544. }
  2545. /**
  2546. * Sets the vector's x component to the given value
  2547. *
  2548. * @param {number} x - The value to set.
  2549. * @return {Vector2} A reference to this vector.
  2550. */
  2551. setX( x ) {
  2552. this.x = x;
  2553. return this;
  2554. }
  2555. /**
  2556. * Sets the vector's y component to the given value
  2557. *
  2558. * @param {number} y - The value to set.
  2559. * @return {Vector2} A reference to this vector.
  2560. */
  2561. setY( y ) {
  2562. this.y = y;
  2563. return this;
  2564. }
  2565. /**
  2566. * Allows to set a vector component with an index.
  2567. *
  2568. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2569. * @param {number} value - The value to set.
  2570. * @return {Vector2} A reference to this vector.
  2571. */
  2572. setComponent( index, value ) {
  2573. switch ( index ) {
  2574. case 0: this.x = value; break;
  2575. case 1: this.y = value; break;
  2576. default: throw new Error( 'index is out of range: ' + index );
  2577. }
  2578. return this;
  2579. }
  2580. /**
  2581. * Returns the value of the vector component which matches the given index.
  2582. *
  2583. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2584. * @return {number} A vector component value.
  2585. */
  2586. getComponent( index ) {
  2587. switch ( index ) {
  2588. case 0: return this.x;
  2589. case 1: return this.y;
  2590. default: throw new Error( 'index is out of range: ' + index );
  2591. }
  2592. }
  2593. /**
  2594. * Returns a new vector with copied values from this instance.
  2595. *
  2596. * @return {Vector2} A clone of this instance.
  2597. */
  2598. clone() {
  2599. return new this.constructor( this.x, this.y );
  2600. }
  2601. /**
  2602. * Copies the values of the given vector to this instance.
  2603. *
  2604. * @param {Vector2} v - The vector to copy.
  2605. * @return {Vector2} A reference to this vector.
  2606. */
  2607. copy( v ) {
  2608. this.x = v.x;
  2609. this.y = v.y;
  2610. return this;
  2611. }
  2612. /**
  2613. * Adds the given vector to this instance.
  2614. *
  2615. * @param {Vector2} v - The vector to add.
  2616. * @return {Vector2} A reference to this vector.
  2617. */
  2618. add( v ) {
  2619. this.x += v.x;
  2620. this.y += v.y;
  2621. return this;
  2622. }
  2623. /**
  2624. * Adds the given scalar value to all components of this instance.
  2625. *
  2626. * @param {number} s - The scalar to add.
  2627. * @return {Vector2} A reference to this vector.
  2628. */
  2629. addScalar( s ) {
  2630. this.x += s;
  2631. this.y += s;
  2632. return this;
  2633. }
  2634. /**
  2635. * Adds the given vectors and stores the result in this instance.
  2636. *
  2637. * @param {Vector2} a - The first vector.
  2638. * @param {Vector2} b - The second vector.
  2639. * @return {Vector2} A reference to this vector.
  2640. */
  2641. addVectors( a, b ) {
  2642. this.x = a.x + b.x;
  2643. this.y = a.y + b.y;
  2644. return this;
  2645. }
  2646. /**
  2647. * Adds the given vector scaled by the given factor to this instance.
  2648. *
  2649. * @param {Vector2} v - The vector.
  2650. * @param {number} s - The factor that scales `v`.
  2651. * @return {Vector2} A reference to this vector.
  2652. */
  2653. addScaledVector( v, s ) {
  2654. this.x += v.x * s;
  2655. this.y += v.y * s;
  2656. return this;
  2657. }
  2658. /**
  2659. * Subtracts the given vector from this instance.
  2660. *
  2661. * @param {Vector2} v - The vector to subtract.
  2662. * @return {Vector2} A reference to this vector.
  2663. */
  2664. sub( v ) {
  2665. this.x -= v.x;
  2666. this.y -= v.y;
  2667. return this;
  2668. }
  2669. /**
  2670. * Subtracts the given scalar value from all components of this instance.
  2671. *
  2672. * @param {number} s - The scalar to subtract.
  2673. * @return {Vector2} A reference to this vector.
  2674. */
  2675. subScalar( s ) {
  2676. this.x -= s;
  2677. this.y -= s;
  2678. return this;
  2679. }
  2680. /**
  2681. * Subtracts the given vectors and stores the result in this instance.
  2682. *
  2683. * @param {Vector2} a - The first vector.
  2684. * @param {Vector2} b - The second vector.
  2685. * @return {Vector2} A reference to this vector.
  2686. */
  2687. subVectors( a, b ) {
  2688. this.x = a.x - b.x;
  2689. this.y = a.y - b.y;
  2690. return this;
  2691. }
  2692. /**
  2693. * Multiplies the given vector with this instance.
  2694. *
  2695. * @param {Vector2} v - The vector to multiply.
  2696. * @return {Vector2} A reference to this vector.
  2697. */
  2698. multiply( v ) {
  2699. this.x *= v.x;
  2700. this.y *= v.y;
  2701. return this;
  2702. }
  2703. /**
  2704. * Multiplies the given scalar value with all components of this instance.
  2705. *
  2706. * @param {number} scalar - The scalar to multiply.
  2707. * @return {Vector2} A reference to this vector.
  2708. */
  2709. multiplyScalar( scalar ) {
  2710. this.x *= scalar;
  2711. this.y *= scalar;
  2712. return this;
  2713. }
  2714. /**
  2715. * Divides this instance by the given vector.
  2716. *
  2717. * @param {Vector2} v - The vector to divide.
  2718. * @return {Vector2} A reference to this vector.
  2719. */
  2720. divide( v ) {
  2721. this.x /= v.x;
  2722. this.y /= v.y;
  2723. return this;
  2724. }
  2725. /**
  2726. * Divides this vector by the given scalar.
  2727. *
  2728. * @param {number} scalar - The scalar to divide.
  2729. * @return {Vector2} A reference to this vector.
  2730. */
  2731. divideScalar( scalar ) {
  2732. return this.multiplyScalar( 1 / scalar );
  2733. }
  2734. /**
  2735. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2736. * the given 3x3 matrix.
  2737. *
  2738. * @param {Matrix3} m - The matrix to apply.
  2739. * @return {Vector2} A reference to this vector.
  2740. */
  2741. applyMatrix3( m ) {
  2742. const x = this.x, y = this.y;
  2743. const e = m.elements;
  2744. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2745. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2746. return this;
  2747. }
  2748. /**
  2749. * If this vector's x or y value is greater than the given vector's x or y
  2750. * value, replace that value with the corresponding min value.
  2751. *
  2752. * @param {Vector2} v - The vector.
  2753. * @return {Vector2} A reference to this vector.
  2754. */
  2755. min( v ) {
  2756. this.x = Math.min( this.x, v.x );
  2757. this.y = Math.min( this.y, v.y );
  2758. return this;
  2759. }
  2760. /**
  2761. * If this vector's x or y value is less than the given vector's x or y
  2762. * value, replace that value with the corresponding max value.
  2763. *
  2764. * @param {Vector2} v - The vector.
  2765. * @return {Vector2} A reference to this vector.
  2766. */
  2767. max( v ) {
  2768. this.x = Math.max( this.x, v.x );
  2769. this.y = Math.max( this.y, v.y );
  2770. return this;
  2771. }
  2772. /**
  2773. * If this vector's x or y value is greater than the max vector's x or y
  2774. * value, it is replaced by the corresponding value.
  2775. * If this vector's x or y value is less than the min vector's x or y value,
  2776. * it is replaced by the corresponding value.
  2777. *
  2778. * @param {Vector2} min - The minimum x and y values.
  2779. * @param {Vector2} max - The maximum x and y values in the desired range.
  2780. * @return {Vector2} A reference to this vector.
  2781. */
  2782. clamp( min, max ) {
  2783. // assumes min < max, componentwise
  2784. this.x = clamp( this.x, min.x, max.x );
  2785. this.y = clamp( this.y, min.y, max.y );
  2786. return this;
  2787. }
  2788. /**
  2789. * If this vector's x or y values are greater than the max value, they are
  2790. * replaced by the max value.
  2791. * If this vector's x or y values are less than the min value, they are
  2792. * replaced by the min value.
  2793. *
  2794. * @param {number} minVal - The minimum value the components will be clamped to.
  2795. * @param {number} maxVal - The maximum value the components will be clamped to.
  2796. * @return {Vector2} A reference to this vector.
  2797. */
  2798. clampScalar( minVal, maxVal ) {
  2799. this.x = clamp( this.x, minVal, maxVal );
  2800. this.y = clamp( this.y, minVal, maxVal );
  2801. return this;
  2802. }
  2803. /**
  2804. * If this vector's length is greater than the max value, it is replaced by
  2805. * the max value.
  2806. * If this vector's length is less than the min value, it is replaced by the
  2807. * min value.
  2808. *
  2809. * @param {number} min - The minimum value the vector length will be clamped to.
  2810. * @param {number} max - The maximum value the vector length will be clamped to.
  2811. * @return {Vector2} A reference to this vector.
  2812. */
  2813. clampLength( min, max ) {
  2814. const length = this.length();
  2815. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2816. }
  2817. /**
  2818. * The components of this vector are rounded down to the nearest integer value.
  2819. *
  2820. * @return {Vector2} A reference to this vector.
  2821. */
  2822. floor() {
  2823. this.x = Math.floor( this.x );
  2824. this.y = Math.floor( this.y );
  2825. return this;
  2826. }
  2827. /**
  2828. * The components of this vector are rounded up to the nearest integer value.
  2829. *
  2830. * @return {Vector2} A reference to this vector.
  2831. */
  2832. ceil() {
  2833. this.x = Math.ceil( this.x );
  2834. this.y = Math.ceil( this.y );
  2835. return this;
  2836. }
  2837. /**
  2838. * The components of this vector are rounded to the nearest integer value
  2839. *
  2840. * @return {Vector2} A reference to this vector.
  2841. */
  2842. round() {
  2843. this.x = Math.round( this.x );
  2844. this.y = Math.round( this.y );
  2845. return this;
  2846. }
  2847. /**
  2848. * The components of this vector are rounded towards zero (up if negative,
  2849. * down if positive) to an integer value.
  2850. *
  2851. * @return {Vector2} A reference to this vector.
  2852. */
  2853. roundToZero() {
  2854. this.x = Math.trunc( this.x );
  2855. this.y = Math.trunc( this.y );
  2856. return this;
  2857. }
  2858. /**
  2859. * Inverts this vector - i.e. sets x = -x and y = -y.
  2860. *
  2861. * @return {Vector2} A reference to this vector.
  2862. */
  2863. negate() {
  2864. this.x = - this.x;
  2865. this.y = - this.y;
  2866. return this;
  2867. }
  2868. /**
  2869. * Calculates the dot product of the given vector with this instance.
  2870. *
  2871. * @param {Vector2} v - The vector to compute the dot product with.
  2872. * @return {number} The result of the dot product.
  2873. */
  2874. dot( v ) {
  2875. return this.x * v.x + this.y * v.y;
  2876. }
  2877. /**
  2878. * Calculates the cross product of the given vector with this instance.
  2879. *
  2880. * @param {Vector2} v - The vector to compute the cross product with.
  2881. * @return {number} The result of the cross product.
  2882. */
  2883. cross( v ) {
  2884. return this.x * v.y - this.y * v.x;
  2885. }
  2886. /**
  2887. * Computes the square of the Euclidean length (straight-line length) from
  2888. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2889. * compare the length squared instead as it is slightly more efficient to calculate.
  2890. *
  2891. * @return {number} The square length of this vector.
  2892. */
  2893. lengthSq() {
  2894. return this.x * this.x + this.y * this.y;
  2895. }
  2896. /**
  2897. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2898. *
  2899. * @return {number} The length of this vector.
  2900. */
  2901. length() {
  2902. return Math.sqrt( this.x * this.x + this.y * this.y );
  2903. }
  2904. /**
  2905. * Computes the Manhattan length of this vector.
  2906. *
  2907. * @return {number} The length of this vector.
  2908. */
  2909. manhattanLength() {
  2910. return Math.abs( this.x ) + Math.abs( this.y );
  2911. }
  2912. /**
  2913. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2914. * with the same direction as this one, but with a vector length of `1`.
  2915. *
  2916. * @return {Vector2} A reference to this vector.
  2917. */
  2918. normalize() {
  2919. return this.divideScalar( this.length() || 1 );
  2920. }
  2921. /**
  2922. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2923. *
  2924. * @return {number} The angle in radians.
  2925. */
  2926. angle() {
  2927. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2928. return angle;
  2929. }
  2930. /**
  2931. * Returns the angle between the given vector and this instance in radians.
  2932. *
  2933. * @param {Vector2} v - The vector to compute the angle with.
  2934. * @return {number} The angle in radians.
  2935. */
  2936. angleTo( v ) {
  2937. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2938. if ( denominator === 0 ) return Math.PI / 2;
  2939. const theta = this.dot( v ) / denominator;
  2940. // clamp, to handle numerical problems
  2941. return Math.acos( clamp( theta, -1, 1 ) );
  2942. }
  2943. /**
  2944. * Computes the distance from the given vector to this instance.
  2945. *
  2946. * @param {Vector2} v - The vector to compute the distance to.
  2947. * @return {number} The distance.
  2948. */
  2949. distanceTo( v ) {
  2950. return Math.sqrt( this.distanceToSquared( v ) );
  2951. }
  2952. /**
  2953. * Computes the squared distance from the given vector to this instance.
  2954. * If you are just comparing the distance with another distance, you should compare
  2955. * the distance squared instead as it is slightly more efficient to calculate.
  2956. *
  2957. * @param {Vector2} v - The vector to compute the squared distance to.
  2958. * @return {number} The squared distance.
  2959. */
  2960. distanceToSquared( v ) {
  2961. const dx = this.x - v.x, dy = this.y - v.y;
  2962. return dx * dx + dy * dy;
  2963. }
  2964. /**
  2965. * Computes the Manhattan distance from the given vector to this instance.
  2966. *
  2967. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2968. * @return {number} The Manhattan distance.
  2969. */
  2970. manhattanDistanceTo( v ) {
  2971. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2972. }
  2973. /**
  2974. * Sets this vector to a vector with the same direction as this one, but
  2975. * with the specified length.
  2976. *
  2977. * @param {number} length - The new length of this vector.
  2978. * @return {Vector2} A reference to this vector.
  2979. */
  2980. setLength( length ) {
  2981. return this.normalize().multiplyScalar( length );
  2982. }
  2983. /**
  2984. * Linearly interpolates between the given vector and this instance, where
  2985. * alpha is the percent distance along the line - alpha = 0 will be this
  2986. * vector, and alpha = 1 will be the given one.
  2987. *
  2988. * @param {Vector2} v - The vector to interpolate towards.
  2989. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2990. * @return {Vector2} A reference to this vector.
  2991. */
  2992. lerp( v, alpha ) {
  2993. this.x += ( v.x - this.x ) * alpha;
  2994. this.y += ( v.y - this.y ) * alpha;
  2995. return this;
  2996. }
  2997. /**
  2998. * Linearly interpolates between the given vectors, where alpha is the percent
  2999. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  3000. * be the second one. The result is stored in this instance.
  3001. *
  3002. * @param {Vector2} v1 - The first vector.
  3003. * @param {Vector2} v2 - The second vector.
  3004. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  3005. * @return {Vector2} A reference to this vector.
  3006. */
  3007. lerpVectors( v1, v2, alpha ) {
  3008. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  3009. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  3010. return this;
  3011. }
  3012. /**
  3013. * Returns `true` if this vector is equal with the given one.
  3014. *
  3015. * @param {Vector2} v - The vector to test for equality.
  3016. * @return {boolean} Whether this vector is equal with the given one.
  3017. */
  3018. equals( v ) {
  3019. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  3020. }
  3021. /**
  3022. * Sets this vector's x value to be `array[ offset ]` and y
  3023. * value to be `array[ offset + 1 ]`.
  3024. *
  3025. * @param {Array<number>} array - An array holding the vector component values.
  3026. * @param {number} [offset=0] - The offset into the array.
  3027. * @return {Vector2} A reference to this vector.
  3028. */
  3029. fromArray( array, offset = 0 ) {
  3030. this.x = array[ offset ];
  3031. this.y = array[ offset + 1 ];
  3032. return this;
  3033. }
  3034. /**
  3035. * Writes the components of this vector to the given array. If no array is provided,
  3036. * the method returns a new instance.
  3037. *
  3038. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  3039. * @param {number} [offset=0] - Index of the first element in the array.
  3040. * @return {Array<number>} The vector components.
  3041. */
  3042. toArray( array = [], offset = 0 ) {
  3043. array[ offset ] = this.x;
  3044. array[ offset + 1 ] = this.y;
  3045. return array;
  3046. }
  3047. /**
  3048. * Sets the components of this vector from the given buffer attribute.
  3049. *
  3050. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  3051. * @param {number} index - The index into the attribute.
  3052. * @return {Vector2} A reference to this vector.
  3053. */
  3054. fromBufferAttribute( attribute, index ) {
  3055. this.x = attribute.getX( index );
  3056. this.y = attribute.getY( index );
  3057. return this;
  3058. }
  3059. /**
  3060. * Rotates this vector around the given center by the given angle.
  3061. *
  3062. * @param {Vector2} center - The point around which to rotate.
  3063. * @param {number} angle - The angle to rotate, in radians.
  3064. * @return {Vector2} A reference to this vector.
  3065. */
  3066. rotateAround( center, angle ) {
  3067. const c = Math.cos( angle ), s = Math.sin( angle );
  3068. const x = this.x - center.x;
  3069. const y = this.y - center.y;
  3070. this.x = x * c - y * s + center.x;
  3071. this.y = x * s + y * c + center.y;
  3072. return this;
  3073. }
  3074. /**
  3075. * Sets each component of this vector to a pseudo-random value between `0` and
  3076. * `1`, excluding `1`.
  3077. *
  3078. * @return {Vector2} A reference to this vector.
  3079. */
  3080. random() {
  3081. this.x = Math.random();
  3082. this.y = Math.random();
  3083. return this;
  3084. }
  3085. *[ Symbol.iterator ]() {
  3086. yield this.x;
  3087. yield this.y;
  3088. }
  3089. }
  3090. /**
  3091. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  3092. *
  3093. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  3094. * the corresponding order.
  3095. *
  3096. * Note that three.js expects Quaternions to be normalized.
  3097. * ```js
  3098. * const quaternion = new THREE.Quaternion();
  3099. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  3100. *
  3101. * const vector = new THREE.Vector3( 1, 0, 0 );
  3102. * vector.applyQuaternion( quaternion );
  3103. * ```
  3104. */
  3105. class Quaternion {
  3106. /**
  3107. * Constructs a new quaternion.
  3108. *
  3109. * @param {number} [x=0] - The x value of this quaternion.
  3110. * @param {number} [y=0] - The y value of this quaternion.
  3111. * @param {number} [z=0] - The z value of this quaternion.
  3112. * @param {number} [w=1] - The w value of this quaternion.
  3113. */
  3114. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  3115. /**
  3116. * This flag can be used for type testing.
  3117. *
  3118. * @type {boolean}
  3119. * @readonly
  3120. * @default true
  3121. */
  3122. this.isQuaternion = true;
  3123. this._x = x;
  3124. this._y = y;
  3125. this._z = z;
  3126. this._w = w;
  3127. }
  3128. /**
  3129. * Interpolates between two quaternions via SLERP. This implementation assumes the
  3130. * quaternion data are managed in flat arrays.
  3131. *
  3132. * @param {Array<number>} dst - The destination array.
  3133. * @param {number} dstOffset - An offset into the destination array.
  3134. * @param {Array<number>} src0 - The source array of the first quaternion.
  3135. * @param {number} srcOffset0 - An offset into the first source array.
  3136. * @param {Array<number>} src1 - The source array of the second quaternion.
  3137. * @param {number} srcOffset1 - An offset into the second source array.
  3138. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3139. * @see {@link Quaternion#slerp}
  3140. */
  3141. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  3142. let x0 = src0[ srcOffset0 + 0 ],
  3143. y0 = src0[ srcOffset0 + 1 ],
  3144. z0 = src0[ srcOffset0 + 2 ],
  3145. w0 = src0[ srcOffset0 + 3 ];
  3146. let x1 = src1[ srcOffset1 + 0 ],
  3147. y1 = src1[ srcOffset1 + 1 ],
  3148. z1 = src1[ srcOffset1 + 2 ],
  3149. w1 = src1[ srcOffset1 + 3 ];
  3150. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3151. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3152. if ( dot < 0 ) {
  3153. x1 = - x1;
  3154. y1 = - y1;
  3155. z1 = - z1;
  3156. w1 = - w1;
  3157. dot = - dot;
  3158. }
  3159. let s = 1 - t;
  3160. if ( dot < 0.9995 ) {
  3161. // slerp
  3162. const theta = Math.acos( dot );
  3163. const sin = Math.sin( theta );
  3164. s = Math.sin( s * theta ) / sin;
  3165. t = Math.sin( t * theta ) / sin;
  3166. x0 = x0 * s + x1 * t;
  3167. y0 = y0 * s + y1 * t;
  3168. z0 = z0 * s + z1 * t;
  3169. w0 = w0 * s + w1 * t;
  3170. } else {
  3171. // for small angles, lerp then normalize
  3172. x0 = x0 * s + x1 * t;
  3173. y0 = y0 * s + y1 * t;
  3174. z0 = z0 * s + z1 * t;
  3175. w0 = w0 * s + w1 * t;
  3176. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3177. x0 *= f;
  3178. y0 *= f;
  3179. z0 *= f;
  3180. w0 *= f;
  3181. }
  3182. }
  3183. dst[ dstOffset ] = x0;
  3184. dst[ dstOffset + 1 ] = y0;
  3185. dst[ dstOffset + 2 ] = z0;
  3186. dst[ dstOffset + 3 ] = w0;
  3187. }
  3188. /**
  3189. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3190. * in flat arrays.
  3191. *
  3192. * @param {Array<number>} dst - The destination array.
  3193. * @param {number} dstOffset - An offset into the destination array.
  3194. * @param {Array<number>} src0 - The source array of the first quaternion.
  3195. * @param {number} srcOffset0 - An offset into the first source array.
  3196. * @param {Array<number>} src1 - The source array of the second quaternion.
  3197. * @param {number} srcOffset1 - An offset into the second source array.
  3198. * @return {Array<number>} The destination array.
  3199. * @see {@link Quaternion#multiplyQuaternions}.
  3200. */
  3201. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3202. const x0 = src0[ srcOffset0 ];
  3203. const y0 = src0[ srcOffset0 + 1 ];
  3204. const z0 = src0[ srcOffset0 + 2 ];
  3205. const w0 = src0[ srcOffset0 + 3 ];
  3206. const x1 = src1[ srcOffset1 ];
  3207. const y1 = src1[ srcOffset1 + 1 ];
  3208. const z1 = src1[ srcOffset1 + 2 ];
  3209. const w1 = src1[ srcOffset1 + 3 ];
  3210. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3211. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3212. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3213. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3214. return dst;
  3215. }
  3216. /**
  3217. * The x value of this quaternion.
  3218. *
  3219. * @type {number}
  3220. * @default 0
  3221. */
  3222. get x() {
  3223. return this._x;
  3224. }
  3225. set x( value ) {
  3226. this._x = value;
  3227. this._onChangeCallback();
  3228. }
  3229. /**
  3230. * The y value of this quaternion.
  3231. *
  3232. * @type {number}
  3233. * @default 0
  3234. */
  3235. get y() {
  3236. return this._y;
  3237. }
  3238. set y( value ) {
  3239. this._y = value;
  3240. this._onChangeCallback();
  3241. }
  3242. /**
  3243. * The z value of this quaternion.
  3244. *
  3245. * @type {number}
  3246. * @default 0
  3247. */
  3248. get z() {
  3249. return this._z;
  3250. }
  3251. set z( value ) {
  3252. this._z = value;
  3253. this._onChangeCallback();
  3254. }
  3255. /**
  3256. * The w value of this quaternion.
  3257. *
  3258. * @type {number}
  3259. * @default 1
  3260. */
  3261. get w() {
  3262. return this._w;
  3263. }
  3264. set w( value ) {
  3265. this._w = value;
  3266. this._onChangeCallback();
  3267. }
  3268. /**
  3269. * Sets the quaternion components.
  3270. *
  3271. * @param {number} x - The x value of this quaternion.
  3272. * @param {number} y - The y value of this quaternion.
  3273. * @param {number} z - The z value of this quaternion.
  3274. * @param {number} w - The w value of this quaternion.
  3275. * @return {Quaternion} A reference to this quaternion.
  3276. */
  3277. set( x, y, z, w ) {
  3278. this._x = x;
  3279. this._y = y;
  3280. this._z = z;
  3281. this._w = w;
  3282. this._onChangeCallback();
  3283. return this;
  3284. }
  3285. /**
  3286. * Returns a new quaternion with copied values from this instance.
  3287. *
  3288. * @return {Quaternion} A clone of this instance.
  3289. */
  3290. clone() {
  3291. return new this.constructor( this._x, this._y, this._z, this._w );
  3292. }
  3293. /**
  3294. * Copies the values of the given quaternion to this instance.
  3295. *
  3296. * @param {Quaternion} quaternion - The quaternion to copy.
  3297. * @return {Quaternion} A reference to this quaternion.
  3298. */
  3299. copy( quaternion ) {
  3300. this._x = quaternion.x;
  3301. this._y = quaternion.y;
  3302. this._z = quaternion.z;
  3303. this._w = quaternion.w;
  3304. this._onChangeCallback();
  3305. return this;
  3306. }
  3307. /**
  3308. * Sets this quaternion from the rotation specified by the given
  3309. * Euler angles.
  3310. *
  3311. * @param {Euler} euler - The Euler angles.
  3312. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3313. * @return {Quaternion} A reference to this quaternion.
  3314. */
  3315. setFromEuler( euler, update = true ) {
  3316. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3317. // http://www.mathworks.com/matlabcentral/fileexchange/
  3318. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3319. // content/SpinCalc.m
  3320. const cos = Math.cos;
  3321. const sin = Math.sin;
  3322. const c1 = cos( x / 2 );
  3323. const c2 = cos( y / 2 );
  3324. const c3 = cos( z / 2 );
  3325. const s1 = sin( x / 2 );
  3326. const s2 = sin( y / 2 );
  3327. const s3 = sin( z / 2 );
  3328. switch ( order ) {
  3329. case 'XYZ':
  3330. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3331. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3332. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3333. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3334. break;
  3335. case 'YXZ':
  3336. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3337. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3338. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3339. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3340. break;
  3341. case 'ZXY':
  3342. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3343. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3344. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3345. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3346. break;
  3347. case 'ZYX':
  3348. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3349. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3350. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3351. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3352. break;
  3353. case 'YZX':
  3354. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3355. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3356. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3357. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3358. break;
  3359. case 'XZY':
  3360. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3361. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3362. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3363. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3364. break;
  3365. default:
  3366. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3367. }
  3368. if ( update === true ) this._onChangeCallback();
  3369. return this;
  3370. }
  3371. /**
  3372. * Sets this quaternion from the given axis and angle.
  3373. *
  3374. * @param {Vector3} axis - The normalized axis.
  3375. * @param {number} angle - The angle in radians.
  3376. * @return {Quaternion} A reference to this quaternion.
  3377. */
  3378. setFromAxisAngle( axis, angle ) {
  3379. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3380. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3381. this._x = axis.x * s;
  3382. this._y = axis.y * s;
  3383. this._z = axis.z * s;
  3384. this._w = Math.cos( halfAngle );
  3385. this._onChangeCallback();
  3386. return this;
  3387. }
  3388. /**
  3389. * Sets this quaternion from the given rotation matrix.
  3390. *
  3391. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3392. * @return {Quaternion} A reference to this quaternion.
  3393. */
  3394. setFromRotationMatrix( m ) {
  3395. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3396. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3397. const te = m.elements,
  3398. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3399. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3400. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3401. trace = m11 + m22 + m33;
  3402. if ( trace > 0 ) {
  3403. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3404. this._w = 0.25 / s;
  3405. this._x = ( m32 - m23 ) * s;
  3406. this._y = ( m13 - m31 ) * s;
  3407. this._z = ( m21 - m12 ) * s;
  3408. } else if ( m11 > m22 && m11 > m33 ) {
  3409. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3410. this._w = ( m32 - m23 ) / s;
  3411. this._x = 0.25 * s;
  3412. this._y = ( m12 + m21 ) / s;
  3413. this._z = ( m13 + m31 ) / s;
  3414. } else if ( m22 > m33 ) {
  3415. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3416. this._w = ( m13 - m31 ) / s;
  3417. this._x = ( m12 + m21 ) / s;
  3418. this._y = 0.25 * s;
  3419. this._z = ( m23 + m32 ) / s;
  3420. } else {
  3421. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3422. this._w = ( m21 - m12 ) / s;
  3423. this._x = ( m13 + m31 ) / s;
  3424. this._y = ( m23 + m32 ) / s;
  3425. this._z = 0.25 * s;
  3426. }
  3427. this._onChangeCallback();
  3428. return this;
  3429. }
  3430. /**
  3431. * Sets this quaternion to the rotation required to rotate the direction vector
  3432. * `vFrom` to the direction vector `vTo`.
  3433. *
  3434. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3435. * @param {Vector3} vTo - The second (normalized) direction vector.
  3436. * @return {Quaternion} A reference to this quaternion.
  3437. */
  3438. setFromUnitVectors( vFrom, vTo ) {
  3439. // assumes direction vectors vFrom and vTo are normalized
  3440. let r = vFrom.dot( vTo ) + 1;
  3441. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3442. // vFrom and vTo point in opposite directions
  3443. r = 0;
  3444. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3445. this._x = - vFrom.y;
  3446. this._y = vFrom.x;
  3447. this._z = 0;
  3448. this._w = r;
  3449. } else {
  3450. this._x = 0;
  3451. this._y = - vFrom.z;
  3452. this._z = vFrom.y;
  3453. this._w = r;
  3454. }
  3455. } else {
  3456. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3457. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3458. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3459. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3460. this._w = r;
  3461. }
  3462. return this.normalize();
  3463. }
  3464. /**
  3465. * Returns the angle between this quaternion and the given one in radians.
  3466. *
  3467. * @param {Quaternion} q - The quaternion to compute the angle with.
  3468. * @return {number} The angle in radians.
  3469. */
  3470. angleTo( q ) {
  3471. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3472. }
  3473. /**
  3474. * Rotates this quaternion by a given angular step to the given quaternion.
  3475. * The method ensures that the final quaternion will not overshoot `q`.
  3476. *
  3477. * @param {Quaternion} q - The target quaternion.
  3478. * @param {number} step - The angular step in radians.
  3479. * @return {Quaternion} A reference to this quaternion.
  3480. */
  3481. rotateTowards( q, step ) {
  3482. const angle = this.angleTo( q );
  3483. if ( angle === 0 ) return this;
  3484. const t = Math.min( 1, step / angle );
  3485. this.slerp( q, t );
  3486. return this;
  3487. }
  3488. /**
  3489. * Sets this quaternion to the identity quaternion; that is, to the
  3490. * quaternion that represents "no rotation".
  3491. *
  3492. * @return {Quaternion} A reference to this quaternion.
  3493. */
  3494. identity() {
  3495. return this.set( 0, 0, 0, 1 );
  3496. }
  3497. /**
  3498. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3499. * quaternion is assumed to have unit length.
  3500. *
  3501. * @return {Quaternion} A reference to this quaternion.
  3502. */
  3503. invert() {
  3504. return this.conjugate();
  3505. }
  3506. /**
  3507. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3508. * quaternion represents the same rotation in the opposite direction about
  3509. * the rotational axis.
  3510. *
  3511. * @return {Quaternion} A reference to this quaternion.
  3512. */
  3513. conjugate() {
  3514. this._x *= -1;
  3515. this._y *= -1;
  3516. this._z *= -1;
  3517. this._onChangeCallback();
  3518. return this;
  3519. }
  3520. /**
  3521. * Calculates the dot product of this quaternion and the given one.
  3522. *
  3523. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3524. * @return {number} The result of the dot product.
  3525. */
  3526. dot( v ) {
  3527. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3528. }
  3529. /**
  3530. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3531. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3532. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3533. * {@link Quaternion#length}.
  3534. *
  3535. * @return {number} The squared Euclidean length.
  3536. */
  3537. lengthSq() {
  3538. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3539. }
  3540. /**
  3541. * Computes the Euclidean length (straight-line length) of this quaternion,
  3542. * considered as a 4 dimensional vector.
  3543. *
  3544. * @return {number} The Euclidean length.
  3545. */
  3546. length() {
  3547. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3548. }
  3549. /**
  3550. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3551. * the same rotation as this one, but has a length equal to `1`.
  3552. *
  3553. * @return {Quaternion} A reference to this quaternion.
  3554. */
  3555. normalize() {
  3556. let l = this.length();
  3557. if ( l === 0 ) {
  3558. this._x = 0;
  3559. this._y = 0;
  3560. this._z = 0;
  3561. this._w = 1;
  3562. } else {
  3563. l = 1 / l;
  3564. this._x = this._x * l;
  3565. this._y = this._y * l;
  3566. this._z = this._z * l;
  3567. this._w = this._w * l;
  3568. }
  3569. this._onChangeCallback();
  3570. return this;
  3571. }
  3572. /**
  3573. * Multiplies this quaternion by the given one.
  3574. *
  3575. * @param {Quaternion} q - The quaternion.
  3576. * @return {Quaternion} A reference to this quaternion.
  3577. */
  3578. multiply( q ) {
  3579. return this.multiplyQuaternions( this, q );
  3580. }
  3581. /**
  3582. * Pre-multiplies this quaternion by the given one.
  3583. *
  3584. * @param {Quaternion} q - The quaternion.
  3585. * @return {Quaternion} A reference to this quaternion.
  3586. */
  3587. premultiply( q ) {
  3588. return this.multiplyQuaternions( q, this );
  3589. }
  3590. /**
  3591. * Multiplies the given quaternions and stores the result in this instance.
  3592. *
  3593. * @param {Quaternion} a - The first quaternion.
  3594. * @param {Quaternion} b - The second quaternion.
  3595. * @return {Quaternion} A reference to this quaternion.
  3596. */
  3597. multiplyQuaternions( a, b ) {
  3598. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3599. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3600. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3601. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3602. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3603. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3604. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3605. this._onChangeCallback();
  3606. return this;
  3607. }
  3608. /**
  3609. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3610. *
  3611. * @param {Quaternion} qb - The target quaternion.
  3612. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3613. * @return {Quaternion} A reference to this quaternion.
  3614. */
  3615. slerp( qb, t ) {
  3616. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3617. let dot = this.dot( qb );
  3618. if ( dot < 0 ) {
  3619. x = - x;
  3620. y = - y;
  3621. z = - z;
  3622. w = - w;
  3623. dot = - dot;
  3624. }
  3625. let s = 1 - t;
  3626. if ( dot < 0.9995 ) {
  3627. // slerp
  3628. const theta = Math.acos( dot );
  3629. const sin = Math.sin( theta );
  3630. s = Math.sin( s * theta ) / sin;
  3631. t = Math.sin( t * theta ) / sin;
  3632. this._x = this._x * s + x * t;
  3633. this._y = this._y * s + y * t;
  3634. this._z = this._z * s + z * t;
  3635. this._w = this._w * s + w * t;
  3636. this._onChangeCallback();
  3637. } else {
  3638. // for small angles, lerp then normalize
  3639. this._x = this._x * s + x * t;
  3640. this._y = this._y * s + y * t;
  3641. this._z = this._z * s + z * t;
  3642. this._w = this._w * s + w * t;
  3643. this.normalize(); // normalize calls _onChangeCallback()
  3644. }
  3645. return this;
  3646. }
  3647. /**
  3648. * Performs a spherical linear interpolation between the given quaternions
  3649. * and stores the result in this quaternion.
  3650. *
  3651. * @param {Quaternion} qa - The source quaternion.
  3652. * @param {Quaternion} qb - The target quaternion.
  3653. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3654. * @return {Quaternion} A reference to this quaternion.
  3655. */
  3656. slerpQuaternions( qa, qb, t ) {
  3657. return this.copy( qa ).slerp( qb, t );
  3658. }
  3659. /**
  3660. * Sets this quaternion to a uniformly random, normalized quaternion.
  3661. *
  3662. * @return {Quaternion} A reference to this quaternion.
  3663. */
  3664. random() {
  3665. // Ken Shoemake
  3666. // Uniform random rotations
  3667. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3668. const theta1 = 2 * Math.PI * Math.random();
  3669. const theta2 = 2 * Math.PI * Math.random();
  3670. const x0 = Math.random();
  3671. const r1 = Math.sqrt( 1 - x0 );
  3672. const r2 = Math.sqrt( x0 );
  3673. return this.set(
  3674. r1 * Math.sin( theta1 ),
  3675. r1 * Math.cos( theta1 ),
  3676. r2 * Math.sin( theta2 ),
  3677. r2 * Math.cos( theta2 ),
  3678. );
  3679. }
  3680. /**
  3681. * Returns `true` if this quaternion is equal with the given one.
  3682. *
  3683. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3684. * @return {boolean} Whether this quaternion is equal with the given one.
  3685. */
  3686. equals( quaternion ) {
  3687. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3688. }
  3689. /**
  3690. * Sets this quaternion's components from the given array.
  3691. *
  3692. * @param {Array<number>} array - An array holding the quaternion component values.
  3693. * @param {number} [offset=0] - The offset into the array.
  3694. * @return {Quaternion} A reference to this quaternion.
  3695. */
  3696. fromArray( array, offset = 0 ) {
  3697. this._x = array[ offset ];
  3698. this._y = array[ offset + 1 ];
  3699. this._z = array[ offset + 2 ];
  3700. this._w = array[ offset + 3 ];
  3701. this._onChangeCallback();
  3702. return this;
  3703. }
  3704. /**
  3705. * Writes the components of this quaternion to the given array. If no array is provided,
  3706. * the method returns a new instance.
  3707. *
  3708. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3709. * @param {number} [offset=0] - Index of the first element in the array.
  3710. * @return {Array<number>} The quaternion components.
  3711. */
  3712. toArray( array = [], offset = 0 ) {
  3713. array[ offset ] = this._x;
  3714. array[ offset + 1 ] = this._y;
  3715. array[ offset + 2 ] = this._z;
  3716. array[ offset + 3 ] = this._w;
  3717. return array;
  3718. }
  3719. /**
  3720. * Sets the components of this quaternion from the given buffer attribute.
  3721. *
  3722. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3723. * @param {number} index - The index into the attribute.
  3724. * @return {Quaternion} A reference to this quaternion.
  3725. */
  3726. fromBufferAttribute( attribute, index ) {
  3727. this._x = attribute.getX( index );
  3728. this._y = attribute.getY( index );
  3729. this._z = attribute.getZ( index );
  3730. this._w = attribute.getW( index );
  3731. this._onChangeCallback();
  3732. return this;
  3733. }
  3734. /**
  3735. * This methods defines the serialization result of this class. Returns the
  3736. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3737. *
  3738. * @return {Array<number>} The serialized quaternion.
  3739. */
  3740. toJSON() {
  3741. return this.toArray();
  3742. }
  3743. _onChange( callback ) {
  3744. this._onChangeCallback = callback;
  3745. return this;
  3746. }
  3747. _onChangeCallback() {}
  3748. *[ Symbol.iterator ]() {
  3749. yield this._x;
  3750. yield this._y;
  3751. yield this._z;
  3752. yield this._w;
  3753. }
  3754. }
  3755. /**
  3756. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3757. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3758. *
  3759. * - A point in 3D space.
  3760. * - A direction and length in 3D space. In three.js the length will
  3761. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3762. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3763. * - Any arbitrary ordered triplet of numbers.
  3764. *
  3765. * There are other things a 3D vector can be used to represent, such as
  3766. * momentum vectors and so on, however these are the most
  3767. * common uses in three.js.
  3768. *
  3769. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3770. * the corresponding order.
  3771. * ```js
  3772. * const a = new THREE.Vector3( 0, 1, 0 );
  3773. *
  3774. * //no arguments; will be initialised to (0, 0, 0)
  3775. * const b = new THREE.Vector3( );
  3776. *
  3777. * const d = a.distanceTo( b );
  3778. * ```
  3779. */
  3780. class Vector3 {
  3781. /**
  3782. * Constructs a new 3D vector.
  3783. *
  3784. * @param {number} [x=0] - The x value of this vector.
  3785. * @param {number} [y=0] - The y value of this vector.
  3786. * @param {number} [z=0] - The z value of this vector.
  3787. */
  3788. constructor( x = 0, y = 0, z = 0 ) {
  3789. /**
  3790. * This flag can be used for type testing.
  3791. *
  3792. * @type {boolean}
  3793. * @readonly
  3794. * @default true
  3795. */
  3796. Vector3.prototype.isVector3 = true;
  3797. /**
  3798. * The x value of this vector.
  3799. *
  3800. * @type {number}
  3801. */
  3802. this.x = x;
  3803. /**
  3804. * The y value of this vector.
  3805. *
  3806. * @type {number}
  3807. */
  3808. this.y = y;
  3809. /**
  3810. * The z value of this vector.
  3811. *
  3812. * @type {number}
  3813. */
  3814. this.z = z;
  3815. }
  3816. /**
  3817. * Sets the vector components.
  3818. *
  3819. * @param {number} x - The value of the x component.
  3820. * @param {number} y - The value of the y component.
  3821. * @param {number} z - The value of the z component.
  3822. * @return {Vector3} A reference to this vector.
  3823. */
  3824. set( x, y, z ) {
  3825. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3826. this.x = x;
  3827. this.y = y;
  3828. this.z = z;
  3829. return this;
  3830. }
  3831. /**
  3832. * Sets the vector components to the same value.
  3833. *
  3834. * @param {number} scalar - The value to set for all vector components.
  3835. * @return {Vector3} A reference to this vector.
  3836. */
  3837. setScalar( scalar ) {
  3838. this.x = scalar;
  3839. this.y = scalar;
  3840. this.z = scalar;
  3841. return this;
  3842. }
  3843. /**
  3844. * Sets the vector's x component to the given value.
  3845. *
  3846. * @param {number} x - The value to set.
  3847. * @return {Vector3} A reference to this vector.
  3848. */
  3849. setX( x ) {
  3850. this.x = x;
  3851. return this;
  3852. }
  3853. /**
  3854. * Sets the vector's y component to the given value.
  3855. *
  3856. * @param {number} y - The value to set.
  3857. * @return {Vector3} A reference to this vector.
  3858. */
  3859. setY( y ) {
  3860. this.y = y;
  3861. return this;
  3862. }
  3863. /**
  3864. * Sets the vector's z component to the given value.
  3865. *
  3866. * @param {number} z - The value to set.
  3867. * @return {Vector3} A reference to this vector.
  3868. */
  3869. setZ( z ) {
  3870. this.z = z;
  3871. return this;
  3872. }
  3873. /**
  3874. * Allows to set a vector component with an index.
  3875. *
  3876. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3877. * @param {number} value - The value to set.
  3878. * @return {Vector3} A reference to this vector.
  3879. */
  3880. setComponent( index, value ) {
  3881. switch ( index ) {
  3882. case 0: this.x = value; break;
  3883. case 1: this.y = value; break;
  3884. case 2: this.z = value; break;
  3885. default: throw new Error( 'index is out of range: ' + index );
  3886. }
  3887. return this;
  3888. }
  3889. /**
  3890. * Returns the value of the vector component which matches the given index.
  3891. *
  3892. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3893. * @return {number} A vector component value.
  3894. */
  3895. getComponent( index ) {
  3896. switch ( index ) {
  3897. case 0: return this.x;
  3898. case 1: return this.y;
  3899. case 2: return this.z;
  3900. default: throw new Error( 'index is out of range: ' + index );
  3901. }
  3902. }
  3903. /**
  3904. * Returns a new vector with copied values from this instance.
  3905. *
  3906. * @return {Vector3} A clone of this instance.
  3907. */
  3908. clone() {
  3909. return new this.constructor( this.x, this.y, this.z );
  3910. }
  3911. /**
  3912. * Copies the values of the given vector to this instance.
  3913. *
  3914. * @param {Vector3} v - The vector to copy.
  3915. * @return {Vector3} A reference to this vector.
  3916. */
  3917. copy( v ) {
  3918. this.x = v.x;
  3919. this.y = v.y;
  3920. this.z = v.z;
  3921. return this;
  3922. }
  3923. /**
  3924. * Adds the given vector to this instance.
  3925. *
  3926. * @param {Vector3} v - The vector to add.
  3927. * @return {Vector3} A reference to this vector.
  3928. */
  3929. add( v ) {
  3930. this.x += v.x;
  3931. this.y += v.y;
  3932. this.z += v.z;
  3933. return this;
  3934. }
  3935. /**
  3936. * Adds the given scalar value to all components of this instance.
  3937. *
  3938. * @param {number} s - The scalar to add.
  3939. * @return {Vector3} A reference to this vector.
  3940. */
  3941. addScalar( s ) {
  3942. this.x += s;
  3943. this.y += s;
  3944. this.z += s;
  3945. return this;
  3946. }
  3947. /**
  3948. * Adds the given vectors and stores the result in this instance.
  3949. *
  3950. * @param {Vector3} a - The first vector.
  3951. * @param {Vector3} b - The second vector.
  3952. * @return {Vector3} A reference to this vector.
  3953. */
  3954. addVectors( a, b ) {
  3955. this.x = a.x + b.x;
  3956. this.y = a.y + b.y;
  3957. this.z = a.z + b.z;
  3958. return this;
  3959. }
  3960. /**
  3961. * Adds the given vector scaled by the given factor to this instance.
  3962. *
  3963. * @param {Vector3|Vector4} v - The vector.
  3964. * @param {number} s - The factor that scales `v`.
  3965. * @return {Vector3} A reference to this vector.
  3966. */
  3967. addScaledVector( v, s ) {
  3968. this.x += v.x * s;
  3969. this.y += v.y * s;
  3970. this.z += v.z * s;
  3971. return this;
  3972. }
  3973. /**
  3974. * Subtracts the given vector from this instance.
  3975. *
  3976. * @param {Vector3} v - The vector to subtract.
  3977. * @return {Vector3} A reference to this vector.
  3978. */
  3979. sub( v ) {
  3980. this.x -= v.x;
  3981. this.y -= v.y;
  3982. this.z -= v.z;
  3983. return this;
  3984. }
  3985. /**
  3986. * Subtracts the given scalar value from all components of this instance.
  3987. *
  3988. * @param {number} s - The scalar to subtract.
  3989. * @return {Vector3} A reference to this vector.
  3990. */
  3991. subScalar( s ) {
  3992. this.x -= s;
  3993. this.y -= s;
  3994. this.z -= s;
  3995. return this;
  3996. }
  3997. /**
  3998. * Subtracts the given vectors and stores the result in this instance.
  3999. *
  4000. * @param {Vector3} a - The first vector.
  4001. * @param {Vector3} b - The second vector.
  4002. * @return {Vector3} A reference to this vector.
  4003. */
  4004. subVectors( a, b ) {
  4005. this.x = a.x - b.x;
  4006. this.y = a.y - b.y;
  4007. this.z = a.z - b.z;
  4008. return this;
  4009. }
  4010. /**
  4011. * Multiplies the given vector with this instance.
  4012. *
  4013. * @param {Vector3} v - The vector to multiply.
  4014. * @return {Vector3} A reference to this vector.
  4015. */
  4016. multiply( v ) {
  4017. this.x *= v.x;
  4018. this.y *= v.y;
  4019. this.z *= v.z;
  4020. return this;
  4021. }
  4022. /**
  4023. * Multiplies the given scalar value with all components of this instance.
  4024. *
  4025. * @param {number} scalar - The scalar to multiply.
  4026. * @return {Vector3} A reference to this vector.
  4027. */
  4028. multiplyScalar( scalar ) {
  4029. this.x *= scalar;
  4030. this.y *= scalar;
  4031. this.z *= scalar;
  4032. return this;
  4033. }
  4034. /**
  4035. * Multiplies the given vectors and stores the result in this instance.
  4036. *
  4037. * @param {Vector3} a - The first vector.
  4038. * @param {Vector3} b - The second vector.
  4039. * @return {Vector3} A reference to this vector.
  4040. */
  4041. multiplyVectors( a, b ) {
  4042. this.x = a.x * b.x;
  4043. this.y = a.y * b.y;
  4044. this.z = a.z * b.z;
  4045. return this;
  4046. }
  4047. /**
  4048. * Applies the given Euler rotation to this vector.
  4049. *
  4050. * @param {Euler} euler - The Euler angles.
  4051. * @return {Vector3} A reference to this vector.
  4052. */
  4053. applyEuler( euler ) {
  4054. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  4055. }
  4056. /**
  4057. * Applies a rotation specified by an axis and an angle to this vector.
  4058. *
  4059. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  4060. * @param {number} angle - The angle in radians.
  4061. * @return {Vector3} A reference to this vector.
  4062. */
  4063. applyAxisAngle( axis, angle ) {
  4064. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  4065. }
  4066. /**
  4067. * Multiplies this vector with the given 3x3 matrix.
  4068. *
  4069. * @param {Matrix3} m - The 3x3 matrix.
  4070. * @return {Vector3} A reference to this vector.
  4071. */
  4072. applyMatrix3( m ) {
  4073. const x = this.x, y = this.y, z = this.z;
  4074. const e = m.elements;
  4075. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  4076. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  4077. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  4078. return this;
  4079. }
  4080. /**
  4081. * Multiplies this vector by the given normal matrix and normalizes
  4082. * the result.
  4083. *
  4084. * @param {Matrix3} m - The normal matrix.
  4085. * @return {Vector3} A reference to this vector.
  4086. */
  4087. applyNormalMatrix( m ) {
  4088. return this.applyMatrix3( m ).normalize();
  4089. }
  4090. /**
  4091. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  4092. * divides by perspective.
  4093. *
  4094. * @param {Matrix4} m - The matrix to apply.
  4095. * @return {Vector3} A reference to this vector.
  4096. */
  4097. applyMatrix4( m ) {
  4098. const x = this.x, y = this.y, z = this.z;
  4099. const e = m.elements;
  4100. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  4101. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  4102. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  4103. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  4104. return this;
  4105. }
  4106. /**
  4107. * Applies the given Quaternion to this vector.
  4108. *
  4109. * @param {Quaternion} q - The Quaternion.
  4110. * @return {Vector3} A reference to this vector.
  4111. */
  4112. applyQuaternion( q ) {
  4113. // quaternion q is assumed to have unit length
  4114. const vx = this.x, vy = this.y, vz = this.z;
  4115. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  4116. // t = 2 * cross( q.xyz, v );
  4117. const tx = 2 * ( qy * vz - qz * vy );
  4118. const ty = 2 * ( qz * vx - qx * vz );
  4119. const tz = 2 * ( qx * vy - qy * vx );
  4120. // v + q.w * t + cross( q.xyz, t );
  4121. this.x = vx + qw * tx + qy * tz - qz * ty;
  4122. this.y = vy + qw * ty + qz * tx - qx * tz;
  4123. this.z = vz + qw * tz + qx * ty - qy * tx;
  4124. return this;
  4125. }
  4126. /**
  4127. * Projects this vector from world space into the camera's normalized
  4128. * device coordinate (NDC) space.
  4129. *
  4130. * @param {Camera} camera - The camera.
  4131. * @return {Vector3} A reference to this vector.
  4132. */
  4133. project( camera ) {
  4134. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4135. }
  4136. /**
  4137. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4138. * space into world space.
  4139. *
  4140. * @param {Camera} camera - The camera.
  4141. * @return {Vector3} A reference to this vector.
  4142. */
  4143. unproject( camera ) {
  4144. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4145. }
  4146. /**
  4147. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4148. * subset of the given 4x4 matrix and then normalizes the result.
  4149. *
  4150. * @param {Matrix4} m - The matrix.
  4151. * @return {Vector3} A reference to this vector.
  4152. */
  4153. transformDirection( m ) {
  4154. // input: THREE.Matrix4 affine matrix
  4155. // vector interpreted as a direction
  4156. const x = this.x, y = this.y, z = this.z;
  4157. const e = m.elements;
  4158. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4159. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4160. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4161. return this.normalize();
  4162. }
  4163. /**
  4164. * Divides this instance by the given vector.
  4165. *
  4166. * @param {Vector3} v - The vector to divide.
  4167. * @return {Vector3} A reference to this vector.
  4168. */
  4169. divide( v ) {
  4170. this.x /= v.x;
  4171. this.y /= v.y;
  4172. this.z /= v.z;
  4173. return this;
  4174. }
  4175. /**
  4176. * Divides this vector by the given scalar.
  4177. *
  4178. * @param {number} scalar - The scalar to divide.
  4179. * @return {Vector3} A reference to this vector.
  4180. */
  4181. divideScalar( scalar ) {
  4182. return this.multiplyScalar( 1 / scalar );
  4183. }
  4184. /**
  4185. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4186. * value, replace that value with the corresponding min value.
  4187. *
  4188. * @param {Vector3} v - The vector.
  4189. * @return {Vector3} A reference to this vector.
  4190. */
  4191. min( v ) {
  4192. this.x = Math.min( this.x, v.x );
  4193. this.y = Math.min( this.y, v.y );
  4194. this.z = Math.min( this.z, v.z );
  4195. return this;
  4196. }
  4197. /**
  4198. * If this vector's x, y or z value is less than the given vector's x, y or z
  4199. * value, replace that value with the corresponding max value.
  4200. *
  4201. * @param {Vector3} v - The vector.
  4202. * @return {Vector3} A reference to this vector.
  4203. */
  4204. max( v ) {
  4205. this.x = Math.max( this.x, v.x );
  4206. this.y = Math.max( this.y, v.y );
  4207. this.z = Math.max( this.z, v.z );
  4208. return this;
  4209. }
  4210. /**
  4211. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4212. * value, it is replaced by the corresponding value.
  4213. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4214. * it is replaced by the corresponding value.
  4215. *
  4216. * @param {Vector3} min - The minimum x, y and z values.
  4217. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4218. * @return {Vector3} A reference to this vector.
  4219. */
  4220. clamp( min, max ) {
  4221. // assumes min < max, componentwise
  4222. this.x = clamp( this.x, min.x, max.x );
  4223. this.y = clamp( this.y, min.y, max.y );
  4224. this.z = clamp( this.z, min.z, max.z );
  4225. return this;
  4226. }
  4227. /**
  4228. * If this vector's x, y or z values are greater than the max value, they are
  4229. * replaced by the max value.
  4230. * If this vector's x, y or z values are less than the min value, they are
  4231. * replaced by the min value.
  4232. *
  4233. * @param {number} minVal - The minimum value the components will be clamped to.
  4234. * @param {number} maxVal - The maximum value the components will be clamped to.
  4235. * @return {Vector3} A reference to this vector.
  4236. */
  4237. clampScalar( minVal, maxVal ) {
  4238. this.x = clamp( this.x, minVal, maxVal );
  4239. this.y = clamp( this.y, minVal, maxVal );
  4240. this.z = clamp( this.z, minVal, maxVal );
  4241. return this;
  4242. }
  4243. /**
  4244. * If this vector's length is greater than the max value, it is replaced by
  4245. * the max value.
  4246. * If this vector's length is less than the min value, it is replaced by the
  4247. * min value.
  4248. *
  4249. * @param {number} min - The minimum value the vector length will be clamped to.
  4250. * @param {number} max - The maximum value the vector length will be clamped to.
  4251. * @return {Vector3} A reference to this vector.
  4252. */
  4253. clampLength( min, max ) {
  4254. const length = this.length();
  4255. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4256. }
  4257. /**
  4258. * The components of this vector are rounded down to the nearest integer value.
  4259. *
  4260. * @return {Vector3} A reference to this vector.
  4261. */
  4262. floor() {
  4263. this.x = Math.floor( this.x );
  4264. this.y = Math.floor( this.y );
  4265. this.z = Math.floor( this.z );
  4266. return this;
  4267. }
  4268. /**
  4269. * The components of this vector are rounded up to the nearest integer value.
  4270. *
  4271. * @return {Vector3} A reference to this vector.
  4272. */
  4273. ceil() {
  4274. this.x = Math.ceil( this.x );
  4275. this.y = Math.ceil( this.y );
  4276. this.z = Math.ceil( this.z );
  4277. return this;
  4278. }
  4279. /**
  4280. * The components of this vector are rounded to the nearest integer value
  4281. *
  4282. * @return {Vector3} A reference to this vector.
  4283. */
  4284. round() {
  4285. this.x = Math.round( this.x );
  4286. this.y = Math.round( this.y );
  4287. this.z = Math.round( this.z );
  4288. return this;
  4289. }
  4290. /**
  4291. * The components of this vector are rounded towards zero (up if negative,
  4292. * down if positive) to an integer value.
  4293. *
  4294. * @return {Vector3} A reference to this vector.
  4295. */
  4296. roundToZero() {
  4297. this.x = Math.trunc( this.x );
  4298. this.y = Math.trunc( this.y );
  4299. this.z = Math.trunc( this.z );
  4300. return this;
  4301. }
  4302. /**
  4303. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4304. *
  4305. * @return {Vector3} A reference to this vector.
  4306. */
  4307. negate() {
  4308. this.x = - this.x;
  4309. this.y = - this.y;
  4310. this.z = - this.z;
  4311. return this;
  4312. }
  4313. /**
  4314. * Calculates the dot product of the given vector with this instance.
  4315. *
  4316. * @param {Vector3} v - The vector to compute the dot product with.
  4317. * @return {number} The result of the dot product.
  4318. */
  4319. dot( v ) {
  4320. return this.x * v.x + this.y * v.y + this.z * v.z;
  4321. }
  4322. /**
  4323. * Computes the square of the Euclidean length (straight-line length) from
  4324. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4325. * compare the length squared instead as it is slightly more efficient to calculate.
  4326. *
  4327. * @return {number} The square length of this vector.
  4328. */
  4329. lengthSq() {
  4330. return this.x * this.x + this.y * this.y + this.z * this.z;
  4331. }
  4332. /**
  4333. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4334. *
  4335. * @return {number} The length of this vector.
  4336. */
  4337. length() {
  4338. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4339. }
  4340. /**
  4341. * Computes the Manhattan length of this vector.
  4342. *
  4343. * @return {number} The length of this vector.
  4344. */
  4345. manhattanLength() {
  4346. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4347. }
  4348. /**
  4349. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4350. * with the same direction as this one, but with a vector length of `1`.
  4351. *
  4352. * @return {Vector3} A reference to this vector.
  4353. */
  4354. normalize() {
  4355. return this.divideScalar( this.length() || 1 );
  4356. }
  4357. /**
  4358. * Sets this vector to a vector with the same direction as this one, but
  4359. * with the specified length.
  4360. *
  4361. * @param {number} length - The new length of this vector.
  4362. * @return {Vector3} A reference to this vector.
  4363. */
  4364. setLength( length ) {
  4365. return this.normalize().multiplyScalar( length );
  4366. }
  4367. /**
  4368. * Linearly interpolates between the given vector and this instance, where
  4369. * alpha is the percent distance along the line - alpha = 0 will be this
  4370. * vector, and alpha = 1 will be the given one.
  4371. *
  4372. * @param {Vector3} v - The vector to interpolate towards.
  4373. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4374. * @return {Vector3} A reference to this vector.
  4375. */
  4376. lerp( v, alpha ) {
  4377. this.x += ( v.x - this.x ) * alpha;
  4378. this.y += ( v.y - this.y ) * alpha;
  4379. this.z += ( v.z - this.z ) * alpha;
  4380. return this;
  4381. }
  4382. /**
  4383. * Linearly interpolates between the given vectors, where alpha is the percent
  4384. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4385. * be the second one. The result is stored in this instance.
  4386. *
  4387. * @param {Vector3} v1 - The first vector.
  4388. * @param {Vector3} v2 - The second vector.
  4389. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4390. * @return {Vector3} A reference to this vector.
  4391. */
  4392. lerpVectors( v1, v2, alpha ) {
  4393. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4394. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4395. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4396. return this;
  4397. }
  4398. /**
  4399. * Calculates the cross product of the given vector with this instance.
  4400. *
  4401. * @param {Vector3} v - The vector to compute the cross product with.
  4402. * @return {Vector3} The result of the cross product.
  4403. */
  4404. cross( v ) {
  4405. return this.crossVectors( this, v );
  4406. }
  4407. /**
  4408. * Calculates the cross product of the given vectors and stores the result
  4409. * in this instance.
  4410. *
  4411. * @param {Vector3} a - The first vector.
  4412. * @param {Vector3} b - The second vector.
  4413. * @return {Vector3} A reference to this vector.
  4414. */
  4415. crossVectors( a, b ) {
  4416. const ax = a.x, ay = a.y, az = a.z;
  4417. const bx = b.x, by = b.y, bz = b.z;
  4418. this.x = ay * bz - az * by;
  4419. this.y = az * bx - ax * bz;
  4420. this.z = ax * by - ay * bx;
  4421. return this;
  4422. }
  4423. /**
  4424. * Projects this vector onto the given one.
  4425. *
  4426. * @param {Vector3} v - The vector to project to.
  4427. * @return {Vector3} A reference to this vector.
  4428. */
  4429. projectOnVector( v ) {
  4430. const denominator = v.lengthSq();
  4431. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4432. const scalar = v.dot( this ) / denominator;
  4433. return this.copy( v ).multiplyScalar( scalar );
  4434. }
  4435. /**
  4436. * Projects this vector onto a plane by subtracting this
  4437. * vector projected onto the plane's normal from this vector.
  4438. *
  4439. * @param {Vector3} planeNormal - The plane normal.
  4440. * @return {Vector3} A reference to this vector.
  4441. */
  4442. projectOnPlane( planeNormal ) {
  4443. _vector$c.copy( this ).projectOnVector( planeNormal );
  4444. return this.sub( _vector$c );
  4445. }
  4446. /**
  4447. * Reflects this vector off a plane orthogonal to the given normal vector.
  4448. *
  4449. * @param {Vector3} normal - The (normalized) normal vector.
  4450. * @return {Vector3} A reference to this vector.
  4451. */
  4452. reflect( normal ) {
  4453. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4454. }
  4455. /**
  4456. * Returns the angle between the given vector and this instance in radians.
  4457. *
  4458. * @param {Vector3} v - The vector to compute the angle with.
  4459. * @return {number} The angle in radians.
  4460. */
  4461. angleTo( v ) {
  4462. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4463. if ( denominator === 0 ) return Math.PI / 2;
  4464. const theta = this.dot( v ) / denominator;
  4465. // clamp, to handle numerical problems
  4466. return Math.acos( clamp( theta, -1, 1 ) );
  4467. }
  4468. /**
  4469. * Computes the distance from the given vector to this instance.
  4470. *
  4471. * @param {Vector3} v - The vector to compute the distance to.
  4472. * @return {number} The distance.
  4473. */
  4474. distanceTo( v ) {
  4475. return Math.sqrt( this.distanceToSquared( v ) );
  4476. }
  4477. /**
  4478. * Computes the squared distance from the given vector to this instance.
  4479. * If you are just comparing the distance with another distance, you should compare
  4480. * the distance squared instead as it is slightly more efficient to calculate.
  4481. *
  4482. * @param {Vector3} v - The vector to compute the squared distance to.
  4483. * @return {number} The squared distance.
  4484. */
  4485. distanceToSquared( v ) {
  4486. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4487. return dx * dx + dy * dy + dz * dz;
  4488. }
  4489. /**
  4490. * Computes the Manhattan distance from the given vector to this instance.
  4491. *
  4492. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4493. * @return {number} The Manhattan distance.
  4494. */
  4495. manhattanDistanceTo( v ) {
  4496. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4497. }
  4498. /**
  4499. * Sets the vector components from the given spherical coordinates.
  4500. *
  4501. * @param {Spherical} s - The spherical coordinates.
  4502. * @return {Vector3} A reference to this vector.
  4503. */
  4504. setFromSpherical( s ) {
  4505. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4506. }
  4507. /**
  4508. * Sets the vector components from the given spherical coordinates.
  4509. *
  4510. * @param {number} radius - The radius.
  4511. * @param {number} phi - The phi angle in radians.
  4512. * @param {number} theta - The theta angle in radians.
  4513. * @return {Vector3} A reference to this vector.
  4514. */
  4515. setFromSphericalCoords( radius, phi, theta ) {
  4516. const sinPhiRadius = Math.sin( phi ) * radius;
  4517. this.x = sinPhiRadius * Math.sin( theta );
  4518. this.y = Math.cos( phi ) * radius;
  4519. this.z = sinPhiRadius * Math.cos( theta );
  4520. return this;
  4521. }
  4522. /**
  4523. * Sets the vector components from the given cylindrical coordinates.
  4524. *
  4525. * @param {Cylindrical} c - The cylindrical coordinates.
  4526. * @return {Vector3} A reference to this vector.
  4527. */
  4528. setFromCylindrical( c ) {
  4529. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4530. }
  4531. /**
  4532. * Sets the vector components from the given cylindrical coordinates.
  4533. *
  4534. * @param {number} radius - The radius.
  4535. * @param {number} theta - The theta angle in radians.
  4536. * @param {number} y - The y value.
  4537. * @return {Vector3} A reference to this vector.
  4538. */
  4539. setFromCylindricalCoords( radius, theta, y ) {
  4540. this.x = radius * Math.sin( theta );
  4541. this.y = y;
  4542. this.z = radius * Math.cos( theta );
  4543. return this;
  4544. }
  4545. /**
  4546. * Sets the vector components to the position elements of the
  4547. * given transformation matrix.
  4548. *
  4549. * @param {Matrix4} m - The 4x4 matrix.
  4550. * @return {Vector3} A reference to this vector.
  4551. */
  4552. setFromMatrixPosition( m ) {
  4553. const e = m.elements;
  4554. this.x = e[ 12 ];
  4555. this.y = e[ 13 ];
  4556. this.z = e[ 14 ];
  4557. return this;
  4558. }
  4559. /**
  4560. * Sets the vector components to the scale elements of the
  4561. * given transformation matrix.
  4562. *
  4563. * @param {Matrix4} m - The 4x4 matrix.
  4564. * @return {Vector3} A reference to this vector.
  4565. */
  4566. setFromMatrixScale( m ) {
  4567. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4568. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4569. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4570. this.x = sx;
  4571. this.y = sy;
  4572. this.z = sz;
  4573. return this;
  4574. }
  4575. /**
  4576. * Sets the vector components from the specified matrix column.
  4577. *
  4578. * @param {Matrix4} m - The 4x4 matrix.
  4579. * @param {number} index - The column index.
  4580. * @return {Vector3} A reference to this vector.
  4581. */
  4582. setFromMatrixColumn( m, index ) {
  4583. return this.fromArray( m.elements, index * 4 );
  4584. }
  4585. /**
  4586. * Sets the vector components from the specified matrix column.
  4587. *
  4588. * @param {Matrix3} m - The 3x3 matrix.
  4589. * @param {number} index - The column index.
  4590. * @return {Vector3} A reference to this vector.
  4591. */
  4592. setFromMatrix3Column( m, index ) {
  4593. return this.fromArray( m.elements, index * 3 );
  4594. }
  4595. /**
  4596. * Sets the vector components from the given Euler angles.
  4597. *
  4598. * @param {Euler} e - The Euler angles to set.
  4599. * @return {Vector3} A reference to this vector.
  4600. */
  4601. setFromEuler( e ) {
  4602. this.x = e._x;
  4603. this.y = e._y;
  4604. this.z = e._z;
  4605. return this;
  4606. }
  4607. /**
  4608. * Sets the vector components from the RGB components of the
  4609. * given color.
  4610. *
  4611. * @param {Color} c - The color to set.
  4612. * @return {Vector3} A reference to this vector.
  4613. */
  4614. setFromColor( c ) {
  4615. this.x = c.r;
  4616. this.y = c.g;
  4617. this.z = c.b;
  4618. return this;
  4619. }
  4620. /**
  4621. * Returns `true` if this vector is equal with the given one.
  4622. *
  4623. * @param {Vector3} v - The vector to test for equality.
  4624. * @return {boolean} Whether this vector is equal with the given one.
  4625. */
  4626. equals( v ) {
  4627. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4628. }
  4629. /**
  4630. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4631. * and z value to be `array[ offset + 2 ]`.
  4632. *
  4633. * @param {Array<number>} array - An array holding the vector component values.
  4634. * @param {number} [offset=0] - The offset into the array.
  4635. * @return {Vector3} A reference to this vector.
  4636. */
  4637. fromArray( array, offset = 0 ) {
  4638. this.x = array[ offset ];
  4639. this.y = array[ offset + 1 ];
  4640. this.z = array[ offset + 2 ];
  4641. return this;
  4642. }
  4643. /**
  4644. * Writes the components of this vector to the given array. If no array is provided,
  4645. * the method returns a new instance.
  4646. *
  4647. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4648. * @param {number} [offset=0] - Index of the first element in the array.
  4649. * @return {Array<number>} The vector components.
  4650. */
  4651. toArray( array = [], offset = 0 ) {
  4652. array[ offset ] = this.x;
  4653. array[ offset + 1 ] = this.y;
  4654. array[ offset + 2 ] = this.z;
  4655. return array;
  4656. }
  4657. /**
  4658. * Sets the components of this vector from the given buffer attribute.
  4659. *
  4660. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4661. * @param {number} index - The index into the attribute.
  4662. * @return {Vector3} A reference to this vector.
  4663. */
  4664. fromBufferAttribute( attribute, index ) {
  4665. this.x = attribute.getX( index );
  4666. this.y = attribute.getY( index );
  4667. this.z = attribute.getZ( index );
  4668. return this;
  4669. }
  4670. /**
  4671. * Sets each component of this vector to a pseudo-random value between `0` and
  4672. * `1`, excluding `1`.
  4673. *
  4674. * @return {Vector3} A reference to this vector.
  4675. */
  4676. random() {
  4677. this.x = Math.random();
  4678. this.y = Math.random();
  4679. this.z = Math.random();
  4680. return this;
  4681. }
  4682. /**
  4683. * Sets this vector to a uniformly random point on a unit sphere.
  4684. *
  4685. * @return {Vector3} A reference to this vector.
  4686. */
  4687. randomDirection() {
  4688. // https://mathworld.wolfram.com/SpherePointPicking.html
  4689. const theta = Math.random() * Math.PI * 2;
  4690. const u = Math.random() * 2 - 1;
  4691. const c = Math.sqrt( 1 - u * u );
  4692. this.x = c * Math.cos( theta );
  4693. this.y = u;
  4694. this.z = c * Math.sin( theta );
  4695. return this;
  4696. }
  4697. *[ Symbol.iterator ]() {
  4698. yield this.x;
  4699. yield this.y;
  4700. yield this.z;
  4701. }
  4702. }
  4703. const _vector$c = /*@__PURE__*/ new Vector3();
  4704. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4705. /**
  4706. * Represents a 3x3 matrix.
  4707. *
  4708. * A Note on Row-Major and Column-Major Ordering:
  4709. *
  4710. * The constructor and {@link Matrix3#set} method take arguments in
  4711. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4712. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4713. * This means that calling:
  4714. * ```js
  4715. * const m = new THREE.Matrix();
  4716. * m.set( 11, 12, 13,
  4717. * 21, 22, 23,
  4718. * 31, 32, 33 );
  4719. * ```
  4720. * will result in the elements array containing:
  4721. * ```js
  4722. * m.elements = [ 11, 21, 31,
  4723. * 12, 22, 32,
  4724. * 13, 23, 33 ];
  4725. * ```
  4726. * and internally all calculations are performed using column-major ordering.
  4727. * However, as the actual ordering makes no difference mathematically and
  4728. * most people are used to thinking about matrices in row-major order, the
  4729. * three.js documentation shows matrices in row-major order. Just bear in
  4730. * mind that if you are reading the source code, you'll have to take the
  4731. * transpose of any matrices outlined here to make sense of the calculations.
  4732. */
  4733. class Matrix3 {
  4734. /**
  4735. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4736. * in row-major order. If no arguments are provided, the constructor
  4737. * initializes the matrix as an identity matrix.
  4738. *
  4739. * @param {number} [n11] - 1-1 matrix element.
  4740. * @param {number} [n12] - 1-2 matrix element.
  4741. * @param {number} [n13] - 1-3 matrix element.
  4742. * @param {number} [n21] - 2-1 matrix element.
  4743. * @param {number} [n22] - 2-2 matrix element.
  4744. * @param {number} [n23] - 2-3 matrix element.
  4745. * @param {number} [n31] - 3-1 matrix element.
  4746. * @param {number} [n32] - 3-2 matrix element.
  4747. * @param {number} [n33] - 3-3 matrix element.
  4748. */
  4749. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4750. /**
  4751. * This flag can be used for type testing.
  4752. *
  4753. * @type {boolean}
  4754. * @readonly
  4755. * @default true
  4756. */
  4757. Matrix3.prototype.isMatrix3 = true;
  4758. /**
  4759. * A column-major list of matrix values.
  4760. *
  4761. * @type {Array<number>}
  4762. */
  4763. this.elements = [
  4764. 1, 0, 0,
  4765. 0, 1, 0,
  4766. 0, 0, 1
  4767. ];
  4768. if ( n11 !== undefined ) {
  4769. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4770. }
  4771. }
  4772. /**
  4773. * Sets the elements of the matrix.The arguments are supposed to be
  4774. * in row-major order.
  4775. *
  4776. * @param {number} [n11] - 1-1 matrix element.
  4777. * @param {number} [n12] - 1-2 matrix element.
  4778. * @param {number} [n13] - 1-3 matrix element.
  4779. * @param {number} [n21] - 2-1 matrix element.
  4780. * @param {number} [n22] - 2-2 matrix element.
  4781. * @param {number} [n23] - 2-3 matrix element.
  4782. * @param {number} [n31] - 3-1 matrix element.
  4783. * @param {number} [n32] - 3-2 matrix element.
  4784. * @param {number} [n33] - 3-3 matrix element.
  4785. * @return {Matrix3} A reference to this matrix.
  4786. */
  4787. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4788. const te = this.elements;
  4789. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4790. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4791. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4792. return this;
  4793. }
  4794. /**
  4795. * Sets this matrix to the 3x3 identity matrix.
  4796. *
  4797. * @return {Matrix3} A reference to this matrix.
  4798. */
  4799. identity() {
  4800. this.set(
  4801. 1, 0, 0,
  4802. 0, 1, 0,
  4803. 0, 0, 1
  4804. );
  4805. return this;
  4806. }
  4807. /**
  4808. * Copies the values of the given matrix to this instance.
  4809. *
  4810. * @param {Matrix3} m - The matrix to copy.
  4811. * @return {Matrix3} A reference to this matrix.
  4812. */
  4813. copy( m ) {
  4814. const te = this.elements;
  4815. const me = m.elements;
  4816. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4817. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4818. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4819. return this;
  4820. }
  4821. /**
  4822. * Extracts the basis of this matrix into the three axis vectors provided.
  4823. *
  4824. * @param {Vector3} xAxis - The basis's x axis.
  4825. * @param {Vector3} yAxis - The basis's y axis.
  4826. * @param {Vector3} zAxis - The basis's z axis.
  4827. * @return {Matrix3} A reference to this matrix.
  4828. */
  4829. extractBasis( xAxis, yAxis, zAxis ) {
  4830. xAxis.setFromMatrix3Column( this, 0 );
  4831. yAxis.setFromMatrix3Column( this, 1 );
  4832. zAxis.setFromMatrix3Column( this, 2 );
  4833. return this;
  4834. }
  4835. /**
  4836. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4837. *
  4838. * @param {Matrix4} m - The 4x4 matrix.
  4839. * @return {Matrix3} A reference to this matrix.
  4840. */
  4841. setFromMatrix4( m ) {
  4842. const me = m.elements;
  4843. this.set(
  4844. me[ 0 ], me[ 4 ], me[ 8 ],
  4845. me[ 1 ], me[ 5 ], me[ 9 ],
  4846. me[ 2 ], me[ 6 ], me[ 10 ]
  4847. );
  4848. return this;
  4849. }
  4850. /**
  4851. * Post-multiplies this matrix by the given 3x3 matrix.
  4852. *
  4853. * @param {Matrix3} m - The matrix to multiply with.
  4854. * @return {Matrix3} A reference to this matrix.
  4855. */
  4856. multiply( m ) {
  4857. return this.multiplyMatrices( this, m );
  4858. }
  4859. /**
  4860. * Pre-multiplies this matrix by the given 3x3 matrix.
  4861. *
  4862. * @param {Matrix3} m - The matrix to multiply with.
  4863. * @return {Matrix3} A reference to this matrix.
  4864. */
  4865. premultiply( m ) {
  4866. return this.multiplyMatrices( m, this );
  4867. }
  4868. /**
  4869. * Multiples the given 3x3 matrices and stores the result
  4870. * in this matrix.
  4871. *
  4872. * @param {Matrix3} a - The first matrix.
  4873. * @param {Matrix3} b - The second matrix.
  4874. * @return {Matrix3} A reference to this matrix.
  4875. */
  4876. multiplyMatrices( a, b ) {
  4877. const ae = a.elements;
  4878. const be = b.elements;
  4879. const te = this.elements;
  4880. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4881. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4882. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4883. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4884. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4885. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4886. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4887. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4888. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4889. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4890. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4891. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4892. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4893. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4894. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4895. return this;
  4896. }
  4897. /**
  4898. * Multiplies every component of the matrix by the given scalar.
  4899. *
  4900. * @param {number} s - The scalar.
  4901. * @return {Matrix3} A reference to this matrix.
  4902. */
  4903. multiplyScalar( s ) {
  4904. const te = this.elements;
  4905. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4906. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4907. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4908. return this;
  4909. }
  4910. /**
  4911. * Computes and returns the determinant of this matrix.
  4912. *
  4913. * @return {number} The determinant.
  4914. */
  4915. determinant() {
  4916. const te = this.elements;
  4917. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4918. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4919. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4920. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4921. }
  4922. /**
  4923. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4924. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4925. * a zero matrix instead.
  4926. *
  4927. * @return {Matrix3} A reference to this matrix.
  4928. */
  4929. invert() {
  4930. const te = this.elements,
  4931. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4932. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4933. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4934. t11 = n33 * n22 - n32 * n23,
  4935. t12 = n32 * n13 - n33 * n12,
  4936. t13 = n23 * n12 - n22 * n13,
  4937. det = n11 * t11 + n21 * t12 + n31 * t13;
  4938. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4939. const detInv = 1 / det;
  4940. te[ 0 ] = t11 * detInv;
  4941. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4942. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4943. te[ 3 ] = t12 * detInv;
  4944. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4945. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4946. te[ 6 ] = t13 * detInv;
  4947. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4948. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4949. return this;
  4950. }
  4951. /**
  4952. * Transposes this matrix in place.
  4953. *
  4954. * @return {Matrix3} A reference to this matrix.
  4955. */
  4956. transpose() {
  4957. let tmp;
  4958. const m = this.elements;
  4959. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4960. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4961. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4962. return this;
  4963. }
  4964. /**
  4965. * Computes the normal matrix which is the inverse transpose of the upper
  4966. * left 3x3 portion of the given 4x4 matrix.
  4967. *
  4968. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4969. * @return {Matrix3} A reference to this matrix.
  4970. */
  4971. getNormalMatrix( matrix4 ) {
  4972. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4973. }
  4974. /**
  4975. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4976. *
  4977. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4978. * @return {Matrix3} A reference to this matrix.
  4979. */
  4980. transposeIntoArray( r ) {
  4981. const m = this.elements;
  4982. r[ 0 ] = m[ 0 ];
  4983. r[ 1 ] = m[ 3 ];
  4984. r[ 2 ] = m[ 6 ];
  4985. r[ 3 ] = m[ 1 ];
  4986. r[ 4 ] = m[ 4 ];
  4987. r[ 5 ] = m[ 7 ];
  4988. r[ 6 ] = m[ 2 ];
  4989. r[ 7 ] = m[ 5 ];
  4990. r[ 8 ] = m[ 8 ];
  4991. return this;
  4992. }
  4993. /**
  4994. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4995. *
  4996. * @param {number} tx - Offset x.
  4997. * @param {number} ty - Offset y.
  4998. * @param {number} sx - Repeat x.
  4999. * @param {number} sy - Repeat y.
  5000. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  5001. * @param {number} cx - Center x of rotation.
  5002. * @param {number} cy - Center y of rotation
  5003. * @return {Matrix3} A reference to this matrix.
  5004. */
  5005. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  5006. const c = Math.cos( rotation );
  5007. const s = Math.sin( rotation );
  5008. this.set(
  5009. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  5010. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  5011. 0, 0, 1
  5012. );
  5013. return this;
  5014. }
  5015. /**
  5016. * Scales this matrix with the given scalar values.
  5017. *
  5018. * @param {number} sx - The amount to scale in the X axis.
  5019. * @param {number} sy - The amount to scale in the Y axis.
  5020. * @return {Matrix3} A reference to this matrix.
  5021. */
  5022. scale( sx, sy ) {
  5023. this.premultiply( _m3.makeScale( sx, sy ) );
  5024. return this;
  5025. }
  5026. /**
  5027. * Rotates this matrix by the given angle.
  5028. *
  5029. * @param {number} theta - The rotation in radians.
  5030. * @return {Matrix3} A reference to this matrix.
  5031. */
  5032. rotate( theta ) {
  5033. this.premultiply( _m3.makeRotation( - theta ) );
  5034. return this;
  5035. }
  5036. /**
  5037. * Translates this matrix by the given scalar values.
  5038. *
  5039. * @param {number} tx - The amount to translate in the X axis.
  5040. * @param {number} ty - The amount to translate in the Y axis.
  5041. * @return {Matrix3} A reference to this matrix.
  5042. */
  5043. translate( tx, ty ) {
  5044. this.premultiply( _m3.makeTranslation( tx, ty ) );
  5045. return this;
  5046. }
  5047. // for 2D Transforms
  5048. /**
  5049. * Sets this matrix as a 2D translation transform.
  5050. *
  5051. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  5052. * @param {number} y - The amount to translate in the Y axis.
  5053. * @return {Matrix3} A reference to this matrix.
  5054. */
  5055. makeTranslation( x, y ) {
  5056. if ( x.isVector2 ) {
  5057. this.set(
  5058. 1, 0, x.x,
  5059. 0, 1, x.y,
  5060. 0, 0, 1
  5061. );
  5062. } else {
  5063. this.set(
  5064. 1, 0, x,
  5065. 0, 1, y,
  5066. 0, 0, 1
  5067. );
  5068. }
  5069. return this;
  5070. }
  5071. /**
  5072. * Sets this matrix as a 2D rotational transformation.
  5073. *
  5074. * @param {number} theta - The rotation in radians.
  5075. * @return {Matrix3} A reference to this matrix.
  5076. */
  5077. makeRotation( theta ) {
  5078. // counterclockwise
  5079. const c = Math.cos( theta );
  5080. const s = Math.sin( theta );
  5081. this.set(
  5082. c, - s, 0,
  5083. s, c, 0,
  5084. 0, 0, 1
  5085. );
  5086. return this;
  5087. }
  5088. /**
  5089. * Sets this matrix as a 2D scale transform.
  5090. *
  5091. * @param {number} x - The amount to scale in the X axis.
  5092. * @param {number} y - The amount to scale in the Y axis.
  5093. * @return {Matrix3} A reference to this matrix.
  5094. */
  5095. makeScale( x, y ) {
  5096. this.set(
  5097. x, 0, 0,
  5098. 0, y, 0,
  5099. 0, 0, 1
  5100. );
  5101. return this;
  5102. }
  5103. /**
  5104. * Returns `true` if this matrix is equal with the given one.
  5105. *
  5106. * @param {Matrix3} matrix - The matrix to test for equality.
  5107. * @return {boolean} Whether this matrix is equal with the given one.
  5108. */
  5109. equals( matrix ) {
  5110. const te = this.elements;
  5111. const me = matrix.elements;
  5112. for ( let i = 0; i < 9; i ++ ) {
  5113. if ( te[ i ] !== me[ i ] ) return false;
  5114. }
  5115. return true;
  5116. }
  5117. /**
  5118. * Sets the elements of the matrix from the given array.
  5119. *
  5120. * @param {Array<number>} array - The matrix elements in column-major order.
  5121. * @param {number} [offset=0] - Index of the first element in the array.
  5122. * @return {Matrix3} A reference to this matrix.
  5123. */
  5124. fromArray( array, offset = 0 ) {
  5125. for ( let i = 0; i < 9; i ++ ) {
  5126. this.elements[ i ] = array[ i + offset ];
  5127. }
  5128. return this;
  5129. }
  5130. /**
  5131. * Writes the elements of this matrix to the given array. If no array is provided,
  5132. * the method returns a new instance.
  5133. *
  5134. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5135. * @param {number} [offset=0] - Index of the first element in the array.
  5136. * @return {Array<number>} The matrix elements in column-major order.
  5137. */
  5138. toArray( array = [], offset = 0 ) {
  5139. const te = this.elements;
  5140. array[ offset ] = te[ 0 ];
  5141. array[ offset + 1 ] = te[ 1 ];
  5142. array[ offset + 2 ] = te[ 2 ];
  5143. array[ offset + 3 ] = te[ 3 ];
  5144. array[ offset + 4 ] = te[ 4 ];
  5145. array[ offset + 5 ] = te[ 5 ];
  5146. array[ offset + 6 ] = te[ 6 ];
  5147. array[ offset + 7 ] = te[ 7 ];
  5148. array[ offset + 8 ] = te[ 8 ];
  5149. return array;
  5150. }
  5151. /**
  5152. * Returns a matrix with copied values from this instance.
  5153. *
  5154. * @return {Matrix3} A clone of this instance.
  5155. */
  5156. clone() {
  5157. return new this.constructor().fromArray( this.elements );
  5158. }
  5159. }
  5160. const _m3 = /*@__PURE__*/ new Matrix3();
  5161. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5162. 0.4123908, 0.3575843, 0.1804808,
  5163. 0.2126390, 0.7151687, 0.0721923,
  5164. 0.0193308, 0.1191948, 0.9505322
  5165. );
  5166. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5167. 3.2409699, -1.5373832, -0.4986108,
  5168. -0.9692436, 1.8759675, 0.0415551,
  5169. 0.0556301, -0.203977, 1.0569715
  5170. );
  5171. function createColorManagement() {
  5172. const ColorManagement = {
  5173. enabled: true,
  5174. workingColorSpace: LinearSRGBColorSpace,
  5175. /**
  5176. * Implementations of supported color spaces.
  5177. *
  5178. * Required:
  5179. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5180. * - whitePoint: reference white [ x y ]
  5181. * - transfer: transfer function (pre-defined)
  5182. * - toXYZ: Matrix3 RGB to XYZ transform
  5183. * - fromXYZ: Matrix3 XYZ to RGB transform
  5184. * - luminanceCoefficients: RGB luminance coefficients
  5185. *
  5186. * Optional:
  5187. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5188. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5189. *
  5190. * Reference:
  5191. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5192. */
  5193. spaces: {},
  5194. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5195. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5196. return color;
  5197. }
  5198. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5199. color.r = SRGBToLinear( color.r );
  5200. color.g = SRGBToLinear( color.g );
  5201. color.b = SRGBToLinear( color.b );
  5202. }
  5203. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5204. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5205. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5206. }
  5207. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5208. color.r = LinearToSRGB( color.r );
  5209. color.g = LinearToSRGB( color.g );
  5210. color.b = LinearToSRGB( color.b );
  5211. }
  5212. return color;
  5213. },
  5214. workingToColorSpace: function ( color, targetColorSpace ) {
  5215. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5216. },
  5217. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5218. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5219. },
  5220. getPrimaries: function ( colorSpace ) {
  5221. return this.spaces[ colorSpace ].primaries;
  5222. },
  5223. getTransfer: function ( colorSpace ) {
  5224. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5225. return this.spaces[ colorSpace ].transfer;
  5226. },
  5227. getToneMappingMode: function ( colorSpace ) {
  5228. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5229. },
  5230. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5231. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5232. },
  5233. define: function ( colorSpaces ) {
  5234. Object.assign( this.spaces, colorSpaces );
  5235. },
  5236. // Internal APIs
  5237. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5238. return targetMatrix
  5239. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5240. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5241. },
  5242. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5243. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5244. },
  5245. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5246. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5247. },
  5248. // Deprecated
  5249. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5250. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5251. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5252. },
  5253. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5254. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5255. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5256. },
  5257. };
  5258. /******************************************************************************
  5259. * sRGB definitions
  5260. */
  5261. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5262. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5263. const D65 = [ 0.3127, 0.3290 ];
  5264. ColorManagement.define( {
  5265. [ LinearSRGBColorSpace ]: {
  5266. primaries: REC709_PRIMARIES,
  5267. whitePoint: D65,
  5268. transfer: LinearTransfer,
  5269. toXYZ: LINEAR_REC709_TO_XYZ,
  5270. fromXYZ: XYZ_TO_LINEAR_REC709,
  5271. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5272. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5273. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5274. },
  5275. [ SRGBColorSpace ]: {
  5276. primaries: REC709_PRIMARIES,
  5277. whitePoint: D65,
  5278. transfer: SRGBTransfer,
  5279. toXYZ: LINEAR_REC709_TO_XYZ,
  5280. fromXYZ: XYZ_TO_LINEAR_REC709,
  5281. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5282. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5283. },
  5284. } );
  5285. return ColorManagement;
  5286. }
  5287. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5288. function SRGBToLinear( c ) {
  5289. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5290. }
  5291. function LinearToSRGB( c ) {
  5292. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5293. }
  5294. let _canvas;
  5295. /**
  5296. * A class containing utility functions for images.
  5297. *
  5298. * @hideconstructor
  5299. */
  5300. class ImageUtils {
  5301. /**
  5302. * Returns a data URI containing a representation of the given image.
  5303. *
  5304. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5305. * @param {string} [type='image/png'] - Indicates the image format.
  5306. * @return {string} The data URI.
  5307. */
  5308. static getDataURL( image, type = 'image/png' ) {
  5309. if ( /^data:/i.test( image.src ) ) {
  5310. return image.src;
  5311. }
  5312. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5313. return image.src;
  5314. }
  5315. let canvas;
  5316. if ( image instanceof HTMLCanvasElement ) {
  5317. canvas = image;
  5318. } else {
  5319. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5320. _canvas.width = image.width;
  5321. _canvas.height = image.height;
  5322. const context = _canvas.getContext( '2d' );
  5323. if ( image instanceof ImageData ) {
  5324. context.putImageData( image, 0, 0 );
  5325. } else {
  5326. context.drawImage( image, 0, 0, image.width, image.height );
  5327. }
  5328. canvas = _canvas;
  5329. }
  5330. return canvas.toDataURL( type );
  5331. }
  5332. /**
  5333. * Converts the given sRGB image data to linear color space.
  5334. *
  5335. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5336. * @return {HTMLCanvasElement|Object} The converted image.
  5337. */
  5338. static sRGBToLinear( image ) {
  5339. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5340. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5341. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5342. const canvas = createElementNS( 'canvas' );
  5343. canvas.width = image.width;
  5344. canvas.height = image.height;
  5345. const context = canvas.getContext( '2d' );
  5346. context.drawImage( image, 0, 0, image.width, image.height );
  5347. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5348. const data = imageData.data;
  5349. for ( let i = 0; i < data.length; i ++ ) {
  5350. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5351. }
  5352. context.putImageData( imageData, 0, 0 );
  5353. return canvas;
  5354. } else if ( image.data ) {
  5355. const data = image.data.slice( 0 );
  5356. for ( let i = 0; i < data.length; i ++ ) {
  5357. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5358. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5359. } else {
  5360. // assuming float
  5361. data[ i ] = SRGBToLinear( data[ i ] );
  5362. }
  5363. }
  5364. return {
  5365. data: data,
  5366. width: image.width,
  5367. height: image.height
  5368. };
  5369. } else {
  5370. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5371. return image;
  5372. }
  5373. }
  5374. }
  5375. let _sourceId = 0;
  5376. /**
  5377. * Represents the data source of a texture.
  5378. *
  5379. * The main purpose of this class is to decouple the data definition from the texture
  5380. * definition so the same data can be used with multiple texture instances.
  5381. */
  5382. class Source {
  5383. /**
  5384. * Constructs a new video texture.
  5385. *
  5386. * @param {any} [data=null] - The data definition of a texture.
  5387. */
  5388. constructor( data = null ) {
  5389. /**
  5390. * This flag can be used for type testing.
  5391. *
  5392. * @type {boolean}
  5393. * @readonly
  5394. * @default true
  5395. */
  5396. this.isSource = true;
  5397. /**
  5398. * The ID of the source.
  5399. *
  5400. * @name Source#id
  5401. * @type {number}
  5402. * @readonly
  5403. */
  5404. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5405. /**
  5406. * The UUID of the source.
  5407. *
  5408. * @type {string}
  5409. * @readonly
  5410. */
  5411. this.uuid = generateUUID();
  5412. /**
  5413. * The data definition of a texture.
  5414. *
  5415. * @type {any}
  5416. */
  5417. this.data = data;
  5418. /**
  5419. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5420. * provides more control on how texture data should be processed. When `dataReady` is set
  5421. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5422. * the data into the GPU memory.
  5423. *
  5424. * @type {boolean}
  5425. * @default true
  5426. */
  5427. this.dataReady = true;
  5428. /**
  5429. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5430. *
  5431. * @type {number}
  5432. * @readonly
  5433. * @default 0
  5434. */
  5435. this.version = 0;
  5436. }
  5437. /**
  5438. * Returns the dimensions of the source into the given target vector.
  5439. *
  5440. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5441. * @return {(Vector2|Vector3)} The dimensions of the source.
  5442. */
  5443. getSize( target ) {
  5444. const data = this.data;
  5445. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5446. target.set( data.videoWidth, data.videoHeight, 0 );
  5447. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5448. target.set( data.displayHeight, data.displayWidth, 0 );
  5449. } else if ( data !== null ) {
  5450. target.set( data.width, data.height, data.depth || 0 );
  5451. } else {
  5452. target.set( 0, 0, 0 );
  5453. }
  5454. return target;
  5455. }
  5456. /**
  5457. * When the property is set to `true`, the engine allocates the memory
  5458. * for the texture (if necessary) and triggers the actual texture upload
  5459. * to the GPU next time the source is used.
  5460. *
  5461. * @type {boolean}
  5462. * @default false
  5463. * @param {boolean} value
  5464. */
  5465. set needsUpdate( value ) {
  5466. if ( value === true ) this.version ++;
  5467. }
  5468. /**
  5469. * Serializes the source into JSON.
  5470. *
  5471. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5472. * @return {Object} A JSON object representing the serialized source.
  5473. * @see {@link ObjectLoader#parse}
  5474. */
  5475. toJSON( meta ) {
  5476. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5477. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5478. return meta.images[ this.uuid ];
  5479. }
  5480. const output = {
  5481. uuid: this.uuid,
  5482. url: ''
  5483. };
  5484. const data = this.data;
  5485. if ( data !== null ) {
  5486. let url;
  5487. if ( Array.isArray( data ) ) {
  5488. // cube texture
  5489. url = [];
  5490. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5491. if ( data[ i ].isDataTexture ) {
  5492. url.push( serializeImage( data[ i ].image ) );
  5493. } else {
  5494. url.push( serializeImage( data[ i ] ) );
  5495. }
  5496. }
  5497. } else {
  5498. // texture
  5499. url = serializeImage( data );
  5500. }
  5501. output.url = url;
  5502. }
  5503. if ( ! isRootObject ) {
  5504. meta.images[ this.uuid ] = output;
  5505. }
  5506. return output;
  5507. }
  5508. }
  5509. function serializeImage( image ) {
  5510. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5511. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5512. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5513. // default images
  5514. return ImageUtils.getDataURL( image );
  5515. } else {
  5516. if ( image.data ) {
  5517. // images of DataTexture
  5518. return {
  5519. data: Array.from( image.data ),
  5520. width: image.width,
  5521. height: image.height,
  5522. type: image.data.constructor.name
  5523. };
  5524. } else {
  5525. warn( 'Texture: Unable to serialize Texture.' );
  5526. return {};
  5527. }
  5528. }
  5529. }
  5530. let _textureId = 0;
  5531. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5532. /**
  5533. * Base class for all textures.
  5534. *
  5535. * Note: After the initial use of a texture, its dimensions, format, and type
  5536. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5537. *
  5538. * @augments EventDispatcher
  5539. */
  5540. class Texture extends EventDispatcher {
  5541. /**
  5542. * Constructs a new texture.
  5543. *
  5544. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5545. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5546. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5547. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5548. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5549. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5550. * @param {number} [format=RGBAFormat] - The texture format.
  5551. * @param {number} [type=UnsignedByteType] - The texture type.
  5552. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5553. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5554. */
  5555. 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 ) {
  5556. super();
  5557. /**
  5558. * This flag can be used for type testing.
  5559. *
  5560. * @type {boolean}
  5561. * @readonly
  5562. * @default true
  5563. */
  5564. this.isTexture = true;
  5565. /**
  5566. * The ID of the texture.
  5567. *
  5568. * @name Texture#id
  5569. * @type {number}
  5570. * @readonly
  5571. */
  5572. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5573. /**
  5574. * The UUID of the texture.
  5575. *
  5576. * @type {string}
  5577. * @readonly
  5578. */
  5579. this.uuid = generateUUID();
  5580. /**
  5581. * The name of the texture.
  5582. *
  5583. * @type {string}
  5584. */
  5585. this.name = '';
  5586. /**
  5587. * The data definition of a texture. A reference to the data source can be
  5588. * shared across textures. This is often useful in context of spritesheets
  5589. * where multiple textures render the same data but with different texture
  5590. * transformations.
  5591. *
  5592. * @type {Source}
  5593. */
  5594. this.source = new Source( image );
  5595. /**
  5596. * An array holding user-defined mipmaps.
  5597. *
  5598. * @type {Array<Object>}
  5599. */
  5600. this.mipmaps = [];
  5601. /**
  5602. * How the texture is applied to the object. The value `UVMapping`
  5603. * is the default, where texture or uv coordinates are used to apply the map.
  5604. *
  5605. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5606. * @default UVMapping
  5607. */
  5608. this.mapping = mapping;
  5609. /**
  5610. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5611. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5612. *
  5613. * @type {number}
  5614. * @default 0
  5615. */
  5616. this.channel = 0;
  5617. /**
  5618. * This defines how the texture is wrapped horizontally and corresponds to
  5619. * *U* in UV mapping.
  5620. *
  5621. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5622. * @default ClampToEdgeWrapping
  5623. */
  5624. this.wrapS = wrapS;
  5625. /**
  5626. * This defines how the texture is wrapped horizontally and corresponds to
  5627. * *V* in UV mapping.
  5628. *
  5629. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5630. * @default ClampToEdgeWrapping
  5631. */
  5632. this.wrapT = wrapT;
  5633. /**
  5634. * How the texture is sampled when a texel covers more than one pixel.
  5635. *
  5636. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5637. * @default LinearFilter
  5638. */
  5639. this.magFilter = magFilter;
  5640. /**
  5641. * How the texture is sampled when a texel covers less than one pixel.
  5642. *
  5643. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5644. * @default LinearMipmapLinearFilter
  5645. */
  5646. this.minFilter = minFilter;
  5647. /**
  5648. * The number of samples taken along the axis through the pixel that has the
  5649. * highest density of texels. By default, this value is `1`. A higher value
  5650. * gives a less blurry result than a basic mipmap, at the cost of more
  5651. * texture samples being used.
  5652. *
  5653. * @type {number}
  5654. * @default Texture.DEFAULT_ANISOTROPY
  5655. */
  5656. this.anisotropy = anisotropy;
  5657. /**
  5658. * The format of the texture.
  5659. *
  5660. * @type {number}
  5661. * @default RGBAFormat
  5662. */
  5663. this.format = format;
  5664. /**
  5665. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5666. * defines how the texture data is going to be stored on the GPU.
  5667. *
  5668. * This property allows to overwrite the default format.
  5669. *
  5670. * @type {?string}
  5671. * @default null
  5672. */
  5673. this.internalFormat = null;
  5674. /**
  5675. * The data type of the texture.
  5676. *
  5677. * @type {number}
  5678. * @default UnsignedByteType
  5679. */
  5680. this.type = type;
  5681. /**
  5682. * How much a single repetition of the texture is offset from the beginning,
  5683. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5684. *
  5685. * @type {Vector2}
  5686. * @default (0,0)
  5687. */
  5688. this.offset = new Vector2( 0, 0 );
  5689. /**
  5690. * How many times the texture is repeated across the surface, in each
  5691. * direction U and V. If repeat is set greater than `1` in either direction,
  5692. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5693. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5694. *
  5695. * @type {Vector2}
  5696. * @default (1,1)
  5697. */
  5698. this.repeat = new Vector2( 1, 1 );
  5699. /**
  5700. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5701. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5702. *
  5703. * @type {Vector2}
  5704. * @default (0,0)
  5705. */
  5706. this.center = new Vector2( 0, 0 );
  5707. /**
  5708. * How much the texture is rotated around the center point, in radians.
  5709. * Positive values are counter-clockwise.
  5710. *
  5711. * @type {number}
  5712. * @default 0
  5713. */
  5714. this.rotation = 0;
  5715. /**
  5716. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5717. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5718. * {@link Texture#rotation}, and {@link Texture#center}.
  5719. *
  5720. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5721. *
  5722. * @type {boolean}
  5723. * @default true
  5724. */
  5725. this.matrixAutoUpdate = true;
  5726. /**
  5727. * The uv-transformation matrix of the texture.
  5728. *
  5729. * @type {Matrix3}
  5730. */
  5731. this.matrix = new Matrix3();
  5732. /**
  5733. * Whether to generate mipmaps (if possible) for a texture.
  5734. *
  5735. * Set this to `false` if you are creating mipmaps manually.
  5736. *
  5737. * @type {boolean}
  5738. * @default true
  5739. */
  5740. this.generateMipmaps = true;
  5741. /**
  5742. * If set to `true`, the alpha channel, if present, is multiplied into the
  5743. * color channels when the texture is uploaded to the GPU.
  5744. *
  5745. * Note that this property has no effect when using `ImageBitmap`. You need to
  5746. * configure premultiply alpha on bitmap creation instead.
  5747. *
  5748. * @type {boolean}
  5749. * @default false
  5750. */
  5751. this.premultiplyAlpha = false;
  5752. /**
  5753. * If set to `true`, the texture is flipped along the vertical axis when
  5754. * uploaded to the GPU.
  5755. *
  5756. * Note that this property has no effect when using `ImageBitmap`. You need to
  5757. * configure the flip on bitmap creation instead.
  5758. *
  5759. * @type {boolean}
  5760. * @default true
  5761. */
  5762. this.flipY = true;
  5763. /**
  5764. * Specifies the alignment requirements for the start of each pixel row in memory.
  5765. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5766. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5767. *
  5768. * @type {number}
  5769. * @default 4
  5770. */
  5771. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5772. /**
  5773. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5774. *
  5775. * @type {string}
  5776. * @default NoColorSpace
  5777. */
  5778. this.colorSpace = colorSpace;
  5779. /**
  5780. * An object that can be used to store custom data about the texture. It
  5781. * should not hold references to functions as these will not be cloned.
  5782. *
  5783. * @type {Object}
  5784. */
  5785. this.userData = {};
  5786. /**
  5787. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5788. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5789. *
  5790. * @type {Array<Object>}
  5791. */
  5792. this.updateRanges = [];
  5793. /**
  5794. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5795. *
  5796. * @type {number}
  5797. * @readonly
  5798. * @default 0
  5799. */
  5800. this.version = 0;
  5801. /**
  5802. * A callback function, called when the texture is updated (e.g., when
  5803. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5804. *
  5805. * @type {?Function}
  5806. * @default null
  5807. */
  5808. this.onUpdate = null;
  5809. /**
  5810. * An optional back reference to the textures render target.
  5811. *
  5812. * @type {?(RenderTarget|WebGLRenderTarget)}
  5813. * @default null
  5814. */
  5815. this.renderTarget = null;
  5816. /**
  5817. * Indicates whether a texture belongs to a render target or not.
  5818. *
  5819. * @type {boolean}
  5820. * @readonly
  5821. * @default false
  5822. */
  5823. this.isRenderTargetTexture = false;
  5824. /**
  5825. * Indicates if a texture should be handled like a texture array.
  5826. *
  5827. * @type {boolean}
  5828. * @readonly
  5829. * @default false
  5830. */
  5831. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5832. /**
  5833. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5834. * (only relevant for render target textures).
  5835. *
  5836. * @type {number}
  5837. * @readonly
  5838. * @default 0
  5839. */
  5840. this.pmremVersion = 0;
  5841. }
  5842. /**
  5843. * The width of the texture in pixels.
  5844. */
  5845. get width() {
  5846. return this.source.getSize( _tempVec3 ).x;
  5847. }
  5848. /**
  5849. * The height of the texture in pixels.
  5850. */
  5851. get height() {
  5852. return this.source.getSize( _tempVec3 ).y;
  5853. }
  5854. /**
  5855. * The depth of the texture in pixels.
  5856. */
  5857. get depth() {
  5858. return this.source.getSize( _tempVec3 ).z;
  5859. }
  5860. /**
  5861. * The image object holding the texture data.
  5862. *
  5863. * @type {?Object}
  5864. */
  5865. get image() {
  5866. return this.source.data;
  5867. }
  5868. set image( value = null ) {
  5869. this.source.data = value;
  5870. }
  5871. /**
  5872. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5873. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5874. */
  5875. updateMatrix() {
  5876. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5877. }
  5878. /**
  5879. * Adds a range of data in the data texture to be updated on the GPU.
  5880. *
  5881. * @param {number} start - Position at which to start update.
  5882. * @param {number} count - The number of components to update.
  5883. */
  5884. addUpdateRange( start, count ) {
  5885. this.updateRanges.push( { start, count } );
  5886. }
  5887. /**
  5888. * Clears the update ranges.
  5889. */
  5890. clearUpdateRanges() {
  5891. this.updateRanges.length = 0;
  5892. }
  5893. /**
  5894. * Returns a new texture with copied values from this instance.
  5895. *
  5896. * @return {Texture} A clone of this instance.
  5897. */
  5898. clone() {
  5899. return new this.constructor().copy( this );
  5900. }
  5901. /**
  5902. * Copies the values of the given texture to this instance.
  5903. *
  5904. * @param {Texture} source - The texture to copy.
  5905. * @return {Texture} A reference to this instance.
  5906. */
  5907. copy( source ) {
  5908. this.name = source.name;
  5909. this.source = source.source;
  5910. this.mipmaps = source.mipmaps.slice( 0 );
  5911. this.mapping = source.mapping;
  5912. this.channel = source.channel;
  5913. this.wrapS = source.wrapS;
  5914. this.wrapT = source.wrapT;
  5915. this.magFilter = source.magFilter;
  5916. this.minFilter = source.minFilter;
  5917. this.anisotropy = source.anisotropy;
  5918. this.format = source.format;
  5919. this.internalFormat = source.internalFormat;
  5920. this.type = source.type;
  5921. this.offset.copy( source.offset );
  5922. this.repeat.copy( source.repeat );
  5923. this.center.copy( source.center );
  5924. this.rotation = source.rotation;
  5925. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5926. this.matrix.copy( source.matrix );
  5927. this.generateMipmaps = source.generateMipmaps;
  5928. this.premultiplyAlpha = source.premultiplyAlpha;
  5929. this.flipY = source.flipY;
  5930. this.unpackAlignment = source.unpackAlignment;
  5931. this.colorSpace = source.colorSpace;
  5932. this.renderTarget = source.renderTarget;
  5933. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5934. this.isArrayTexture = source.isArrayTexture;
  5935. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5936. this.needsUpdate = true;
  5937. return this;
  5938. }
  5939. /**
  5940. * Sets this texture's properties based on `values`.
  5941. * @param {Object} values - A container with texture parameters.
  5942. */
  5943. setValues( values ) {
  5944. for ( const key in values ) {
  5945. const newValue = values[ key ];
  5946. if ( newValue === undefined ) {
  5947. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5948. continue;
  5949. }
  5950. const currentValue = this[ key ];
  5951. if ( currentValue === undefined ) {
  5952. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5953. continue;
  5954. }
  5955. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5956. currentValue.copy( newValue );
  5957. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5958. currentValue.copy( newValue );
  5959. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5960. currentValue.copy( newValue );
  5961. } else {
  5962. this[ key ] = newValue;
  5963. }
  5964. }
  5965. }
  5966. /**
  5967. * Serializes the texture into JSON.
  5968. *
  5969. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5970. * @return {Object} A JSON object representing the serialized texture.
  5971. * @see {@link ObjectLoader#parse}
  5972. */
  5973. toJSON( meta ) {
  5974. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5975. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5976. return meta.textures[ this.uuid ];
  5977. }
  5978. const output = {
  5979. metadata: {
  5980. version: 4.7,
  5981. type: 'Texture',
  5982. generator: 'Texture.toJSON'
  5983. },
  5984. uuid: this.uuid,
  5985. name: this.name,
  5986. image: this.source.toJSON( meta ).uuid,
  5987. mapping: this.mapping,
  5988. channel: this.channel,
  5989. repeat: [ this.repeat.x, this.repeat.y ],
  5990. offset: [ this.offset.x, this.offset.y ],
  5991. center: [ this.center.x, this.center.y ],
  5992. rotation: this.rotation,
  5993. wrap: [ this.wrapS, this.wrapT ],
  5994. format: this.format,
  5995. internalFormat: this.internalFormat,
  5996. type: this.type,
  5997. colorSpace: this.colorSpace,
  5998. minFilter: this.minFilter,
  5999. magFilter: this.magFilter,
  6000. anisotropy: this.anisotropy,
  6001. flipY: this.flipY,
  6002. generateMipmaps: this.generateMipmaps,
  6003. premultiplyAlpha: this.premultiplyAlpha,
  6004. unpackAlignment: this.unpackAlignment
  6005. };
  6006. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  6007. if ( ! isRootObject ) {
  6008. meta.textures[ this.uuid ] = output;
  6009. }
  6010. return output;
  6011. }
  6012. /**
  6013. * Frees the GPU-related resources allocated by this instance. Call this
  6014. * method whenever this instance is no longer used in your app.
  6015. *
  6016. * @fires Texture#dispose
  6017. */
  6018. dispose() {
  6019. /**
  6020. * Fires when the texture has been disposed of.
  6021. *
  6022. * @event Texture#dispose
  6023. * @type {Object}
  6024. */
  6025. this.dispatchEvent( { type: 'dispose' } );
  6026. }
  6027. /**
  6028. * Transforms the given uv vector with the textures uv transformation matrix.
  6029. *
  6030. * @param {Vector2} uv - The uv vector.
  6031. * @return {Vector2} The transformed uv vector.
  6032. */
  6033. transformUv( uv ) {
  6034. if ( this.mapping !== UVMapping ) return uv;
  6035. uv.applyMatrix3( this.matrix );
  6036. if ( uv.x < 0 || uv.x > 1 ) {
  6037. switch ( this.wrapS ) {
  6038. case RepeatWrapping:
  6039. uv.x = uv.x - Math.floor( uv.x );
  6040. break;
  6041. case ClampToEdgeWrapping:
  6042. uv.x = uv.x < 0 ? 0 : 1;
  6043. break;
  6044. case MirroredRepeatWrapping:
  6045. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6046. uv.x = Math.ceil( uv.x ) - uv.x;
  6047. } else {
  6048. uv.x = uv.x - Math.floor( uv.x );
  6049. }
  6050. break;
  6051. }
  6052. }
  6053. if ( uv.y < 0 || uv.y > 1 ) {
  6054. switch ( this.wrapT ) {
  6055. case RepeatWrapping:
  6056. uv.y = uv.y - Math.floor( uv.y );
  6057. break;
  6058. case ClampToEdgeWrapping:
  6059. uv.y = uv.y < 0 ? 0 : 1;
  6060. break;
  6061. case MirroredRepeatWrapping:
  6062. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6063. uv.y = Math.ceil( uv.y ) - uv.y;
  6064. } else {
  6065. uv.y = uv.y - Math.floor( uv.y );
  6066. }
  6067. break;
  6068. }
  6069. }
  6070. if ( this.flipY ) {
  6071. uv.y = 1 - uv.y;
  6072. }
  6073. return uv;
  6074. }
  6075. /**
  6076. * Setting this property to `true` indicates the engine the texture
  6077. * must be updated in the next render. This triggers a texture upload
  6078. * to the GPU and ensures correct texture parameter configuration.
  6079. *
  6080. * @type {boolean}
  6081. * @default false
  6082. * @param {boolean} value
  6083. */
  6084. set needsUpdate( value ) {
  6085. if ( value === true ) {
  6086. this.version ++;
  6087. this.source.needsUpdate = true;
  6088. }
  6089. }
  6090. /**
  6091. * Setting this property to `true` indicates the engine the PMREM
  6092. * must be regenerated.
  6093. *
  6094. * @type {boolean}
  6095. * @default false
  6096. * @param {boolean} value
  6097. */
  6098. set needsPMREMUpdate( value ) {
  6099. if ( value === true ) {
  6100. this.pmremVersion ++;
  6101. }
  6102. }
  6103. }
  6104. /**
  6105. * The default image for all textures.
  6106. *
  6107. * @static
  6108. * @type {?Image}
  6109. * @default null
  6110. */
  6111. Texture.DEFAULT_IMAGE = null;
  6112. /**
  6113. * The default mapping for all textures.
  6114. *
  6115. * @static
  6116. * @type {number}
  6117. * @default UVMapping
  6118. */
  6119. Texture.DEFAULT_MAPPING = UVMapping;
  6120. /**
  6121. * The default anisotropy value for all textures.
  6122. *
  6123. * @static
  6124. * @type {number}
  6125. * @default 1
  6126. */
  6127. Texture.DEFAULT_ANISOTROPY = 1;
  6128. /**
  6129. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6130. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6131. *
  6132. * - A point in 4D space.
  6133. * - A direction and length in 4D space. In three.js the length will
  6134. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6135. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6136. * - Any arbitrary ordered quadruplet of numbers.
  6137. *
  6138. * There are other things a 4D vector can be used to represent, however these
  6139. * are the most common uses in *three.js*.
  6140. *
  6141. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6142. * the corresponding order.
  6143. * ```js
  6144. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6145. *
  6146. * //no arguments; will be initialised to (0, 0, 0, 1)
  6147. * const b = new THREE.Vector4( );
  6148. *
  6149. * const d = a.dot( b );
  6150. * ```
  6151. */
  6152. class Vector4 {
  6153. /**
  6154. * Constructs a new 4D vector.
  6155. *
  6156. * @param {number} [x=0] - The x value of this vector.
  6157. * @param {number} [y=0] - The y value of this vector.
  6158. * @param {number} [z=0] - The z value of this vector.
  6159. * @param {number} [w=1] - The w value of this vector.
  6160. */
  6161. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6162. /**
  6163. * This flag can be used for type testing.
  6164. *
  6165. * @type {boolean}
  6166. * @readonly
  6167. * @default true
  6168. */
  6169. Vector4.prototype.isVector4 = true;
  6170. /**
  6171. * The x value of this vector.
  6172. *
  6173. * @type {number}
  6174. */
  6175. this.x = x;
  6176. /**
  6177. * The y value of this vector.
  6178. *
  6179. * @type {number}
  6180. */
  6181. this.y = y;
  6182. /**
  6183. * The z value of this vector.
  6184. *
  6185. * @type {number}
  6186. */
  6187. this.z = z;
  6188. /**
  6189. * The w value of this vector.
  6190. *
  6191. * @type {number}
  6192. */
  6193. this.w = w;
  6194. }
  6195. /**
  6196. * Alias for {@link Vector4#z}.
  6197. *
  6198. * @type {number}
  6199. */
  6200. get width() {
  6201. return this.z;
  6202. }
  6203. set width( value ) {
  6204. this.z = value;
  6205. }
  6206. /**
  6207. * Alias for {@link Vector4#w}.
  6208. *
  6209. * @type {number}
  6210. */
  6211. get height() {
  6212. return this.w;
  6213. }
  6214. set height( value ) {
  6215. this.w = value;
  6216. }
  6217. /**
  6218. * Sets the vector components.
  6219. *
  6220. * @param {number} x - The value of the x component.
  6221. * @param {number} y - The value of the y component.
  6222. * @param {number} z - The value of the z component.
  6223. * @param {number} w - The value of the w component.
  6224. * @return {Vector4} A reference to this vector.
  6225. */
  6226. set( x, y, z, w ) {
  6227. this.x = x;
  6228. this.y = y;
  6229. this.z = z;
  6230. this.w = w;
  6231. return this;
  6232. }
  6233. /**
  6234. * Sets the vector components to the same value.
  6235. *
  6236. * @param {number} scalar - The value to set for all vector components.
  6237. * @return {Vector4} A reference to this vector.
  6238. */
  6239. setScalar( scalar ) {
  6240. this.x = scalar;
  6241. this.y = scalar;
  6242. this.z = scalar;
  6243. this.w = scalar;
  6244. return this;
  6245. }
  6246. /**
  6247. * Sets the vector's x component to the given value
  6248. *
  6249. * @param {number} x - The value to set.
  6250. * @return {Vector4} A reference to this vector.
  6251. */
  6252. setX( x ) {
  6253. this.x = x;
  6254. return this;
  6255. }
  6256. /**
  6257. * Sets the vector's y component to the given value
  6258. *
  6259. * @param {number} y - The value to set.
  6260. * @return {Vector4} A reference to this vector.
  6261. */
  6262. setY( y ) {
  6263. this.y = y;
  6264. return this;
  6265. }
  6266. /**
  6267. * Sets the vector's z component to the given value
  6268. *
  6269. * @param {number} z - The value to set.
  6270. * @return {Vector4} A reference to this vector.
  6271. */
  6272. setZ( z ) {
  6273. this.z = z;
  6274. return this;
  6275. }
  6276. /**
  6277. * Sets the vector's w component to the given value
  6278. *
  6279. * @param {number} w - The value to set.
  6280. * @return {Vector4} A reference to this vector.
  6281. */
  6282. setW( w ) {
  6283. this.w = w;
  6284. return this;
  6285. }
  6286. /**
  6287. * Allows to set a vector component with an index.
  6288. *
  6289. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6290. * `2` equals to z, `3` equals to w.
  6291. * @param {number} value - The value to set.
  6292. * @return {Vector4} A reference to this vector.
  6293. */
  6294. setComponent( index, value ) {
  6295. switch ( index ) {
  6296. case 0: this.x = value; break;
  6297. case 1: this.y = value; break;
  6298. case 2: this.z = value; break;
  6299. case 3: this.w = value; break;
  6300. default: throw new Error( 'index is out of range: ' + index );
  6301. }
  6302. return this;
  6303. }
  6304. /**
  6305. * Returns the value of the vector component which matches the given index.
  6306. *
  6307. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6308. * `2` equals to z, `3` equals to w.
  6309. * @return {number} A vector component value.
  6310. */
  6311. getComponent( index ) {
  6312. switch ( index ) {
  6313. case 0: return this.x;
  6314. case 1: return this.y;
  6315. case 2: return this.z;
  6316. case 3: return this.w;
  6317. default: throw new Error( 'index is out of range: ' + index );
  6318. }
  6319. }
  6320. /**
  6321. * Returns a new vector with copied values from this instance.
  6322. *
  6323. * @return {Vector4} A clone of this instance.
  6324. */
  6325. clone() {
  6326. return new this.constructor( this.x, this.y, this.z, this.w );
  6327. }
  6328. /**
  6329. * Copies the values of the given vector to this instance.
  6330. *
  6331. * @param {Vector3|Vector4} v - The vector to copy.
  6332. * @return {Vector4} A reference to this vector.
  6333. */
  6334. copy( v ) {
  6335. this.x = v.x;
  6336. this.y = v.y;
  6337. this.z = v.z;
  6338. this.w = ( v.w !== undefined ) ? v.w : 1;
  6339. return this;
  6340. }
  6341. /**
  6342. * Adds the given vector to this instance.
  6343. *
  6344. * @param {Vector4} v - The vector to add.
  6345. * @return {Vector4} A reference to this vector.
  6346. */
  6347. add( v ) {
  6348. this.x += v.x;
  6349. this.y += v.y;
  6350. this.z += v.z;
  6351. this.w += v.w;
  6352. return this;
  6353. }
  6354. /**
  6355. * Adds the given scalar value to all components of this instance.
  6356. *
  6357. * @param {number} s - The scalar to add.
  6358. * @return {Vector4} A reference to this vector.
  6359. */
  6360. addScalar( s ) {
  6361. this.x += s;
  6362. this.y += s;
  6363. this.z += s;
  6364. this.w += s;
  6365. return this;
  6366. }
  6367. /**
  6368. * Adds the given vectors and stores the result in this instance.
  6369. *
  6370. * @param {Vector4} a - The first vector.
  6371. * @param {Vector4} b - The second vector.
  6372. * @return {Vector4} A reference to this vector.
  6373. */
  6374. addVectors( a, b ) {
  6375. this.x = a.x + b.x;
  6376. this.y = a.y + b.y;
  6377. this.z = a.z + b.z;
  6378. this.w = a.w + b.w;
  6379. return this;
  6380. }
  6381. /**
  6382. * Adds the given vector scaled by the given factor to this instance.
  6383. *
  6384. * @param {Vector4} v - The vector.
  6385. * @param {number} s - The factor that scales `v`.
  6386. * @return {Vector4} A reference to this vector.
  6387. */
  6388. addScaledVector( v, s ) {
  6389. this.x += v.x * s;
  6390. this.y += v.y * s;
  6391. this.z += v.z * s;
  6392. this.w += v.w * s;
  6393. return this;
  6394. }
  6395. /**
  6396. * Subtracts the given vector from this instance.
  6397. *
  6398. * @param {Vector4} v - The vector to subtract.
  6399. * @return {Vector4} A reference to this vector.
  6400. */
  6401. sub( v ) {
  6402. this.x -= v.x;
  6403. this.y -= v.y;
  6404. this.z -= v.z;
  6405. this.w -= v.w;
  6406. return this;
  6407. }
  6408. /**
  6409. * Subtracts the given scalar value from all components of this instance.
  6410. *
  6411. * @param {number} s - The scalar to subtract.
  6412. * @return {Vector4} A reference to this vector.
  6413. */
  6414. subScalar( s ) {
  6415. this.x -= s;
  6416. this.y -= s;
  6417. this.z -= s;
  6418. this.w -= s;
  6419. return this;
  6420. }
  6421. /**
  6422. * Subtracts the given vectors and stores the result in this instance.
  6423. *
  6424. * @param {Vector4} a - The first vector.
  6425. * @param {Vector4} b - The second vector.
  6426. * @return {Vector4} A reference to this vector.
  6427. */
  6428. subVectors( a, b ) {
  6429. this.x = a.x - b.x;
  6430. this.y = a.y - b.y;
  6431. this.z = a.z - b.z;
  6432. this.w = a.w - b.w;
  6433. return this;
  6434. }
  6435. /**
  6436. * Multiplies the given vector with this instance.
  6437. *
  6438. * @param {Vector4} v - The vector to multiply.
  6439. * @return {Vector4} A reference to this vector.
  6440. */
  6441. multiply( v ) {
  6442. this.x *= v.x;
  6443. this.y *= v.y;
  6444. this.z *= v.z;
  6445. this.w *= v.w;
  6446. return this;
  6447. }
  6448. /**
  6449. * Multiplies the given scalar value with all components of this instance.
  6450. *
  6451. * @param {number} scalar - The scalar to multiply.
  6452. * @return {Vector4} A reference to this vector.
  6453. */
  6454. multiplyScalar( scalar ) {
  6455. this.x *= scalar;
  6456. this.y *= scalar;
  6457. this.z *= scalar;
  6458. this.w *= scalar;
  6459. return this;
  6460. }
  6461. /**
  6462. * Multiplies this vector with the given 4x4 matrix.
  6463. *
  6464. * @param {Matrix4} m - The 4x4 matrix.
  6465. * @return {Vector4} A reference to this vector.
  6466. */
  6467. applyMatrix4( m ) {
  6468. const x = this.x, y = this.y, z = this.z, w = this.w;
  6469. const e = m.elements;
  6470. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6471. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6472. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6473. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6474. return this;
  6475. }
  6476. /**
  6477. * Divides this instance by the given vector.
  6478. *
  6479. * @param {Vector4} v - The vector to divide.
  6480. * @return {Vector4} A reference to this vector.
  6481. */
  6482. divide( v ) {
  6483. this.x /= v.x;
  6484. this.y /= v.y;
  6485. this.z /= v.z;
  6486. this.w /= v.w;
  6487. return this;
  6488. }
  6489. /**
  6490. * Divides this vector by the given scalar.
  6491. *
  6492. * @param {number} scalar - The scalar to divide.
  6493. * @return {Vector4} A reference to this vector.
  6494. */
  6495. divideScalar( scalar ) {
  6496. return this.multiplyScalar( 1 / scalar );
  6497. }
  6498. /**
  6499. * Sets the x, y and z components of this
  6500. * vector to the quaternion's axis and w to the angle.
  6501. *
  6502. * @param {Quaternion} q - The Quaternion to set.
  6503. * @return {Vector4} A reference to this vector.
  6504. */
  6505. setAxisAngleFromQuaternion( q ) {
  6506. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6507. // q is assumed to be normalized
  6508. this.w = 2 * Math.acos( q.w );
  6509. const s = Math.sqrt( 1 - q.w * q.w );
  6510. if ( s < 0.0001 ) {
  6511. this.x = 1;
  6512. this.y = 0;
  6513. this.z = 0;
  6514. } else {
  6515. this.x = q.x / s;
  6516. this.y = q.y / s;
  6517. this.z = q.z / s;
  6518. }
  6519. return this;
  6520. }
  6521. /**
  6522. * Sets the x, y and z components of this
  6523. * vector to the axis of rotation and w to the angle.
  6524. *
  6525. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6526. * @return {Vector4} A reference to this vector.
  6527. */
  6528. setAxisAngleFromRotationMatrix( m ) {
  6529. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6530. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6531. let angle, x, y, z; // variables for result
  6532. const epsilon = 0.01, // margin to allow for rounding errors
  6533. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6534. te = m.elements,
  6535. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6536. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6537. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6538. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6539. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6540. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6541. // singularity found
  6542. // first check for identity matrix which must have +1 for all terms
  6543. // in leading diagonal and zero in other terms
  6544. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6545. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6546. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6547. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6548. // this singularity is identity matrix so angle = 0
  6549. this.set( 1, 0, 0, 0 );
  6550. return this; // zero angle, arbitrary axis
  6551. }
  6552. // otherwise this singularity is angle = 180
  6553. angle = Math.PI;
  6554. const xx = ( m11 + 1 ) / 2;
  6555. const yy = ( m22 + 1 ) / 2;
  6556. const zz = ( m33 + 1 ) / 2;
  6557. const xy = ( m12 + m21 ) / 4;
  6558. const xz = ( m13 + m31 ) / 4;
  6559. const yz = ( m23 + m32 ) / 4;
  6560. if ( ( xx > yy ) && ( xx > zz ) ) {
  6561. // m11 is the largest diagonal term
  6562. if ( xx < epsilon ) {
  6563. x = 0;
  6564. y = 0.707106781;
  6565. z = 0.707106781;
  6566. } else {
  6567. x = Math.sqrt( xx );
  6568. y = xy / x;
  6569. z = xz / x;
  6570. }
  6571. } else if ( yy > zz ) {
  6572. // m22 is the largest diagonal term
  6573. if ( yy < epsilon ) {
  6574. x = 0.707106781;
  6575. y = 0;
  6576. z = 0.707106781;
  6577. } else {
  6578. y = Math.sqrt( yy );
  6579. x = xy / y;
  6580. z = yz / y;
  6581. }
  6582. } else {
  6583. // m33 is the largest diagonal term so base result on this
  6584. if ( zz < epsilon ) {
  6585. x = 0.707106781;
  6586. y = 0.707106781;
  6587. z = 0;
  6588. } else {
  6589. z = Math.sqrt( zz );
  6590. x = xz / z;
  6591. y = yz / z;
  6592. }
  6593. }
  6594. this.set( x, y, z, angle );
  6595. return this; // return 180 deg rotation
  6596. }
  6597. // as we have reached here there are no singularities so we can handle normally
  6598. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6599. ( m13 - m31 ) * ( m13 - m31 ) +
  6600. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6601. if ( Math.abs( s ) < 0.001 ) s = 1;
  6602. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6603. // caught by singularity test above, but I've left it in just in case
  6604. this.x = ( m32 - m23 ) / s;
  6605. this.y = ( m13 - m31 ) / s;
  6606. this.z = ( m21 - m12 ) / s;
  6607. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6608. return this;
  6609. }
  6610. /**
  6611. * Sets the vector components to the position elements of the
  6612. * given transformation matrix.
  6613. *
  6614. * @param {Matrix4} m - The 4x4 matrix.
  6615. * @return {Vector4} A reference to this vector.
  6616. */
  6617. setFromMatrixPosition( m ) {
  6618. const e = m.elements;
  6619. this.x = e[ 12 ];
  6620. this.y = e[ 13 ];
  6621. this.z = e[ 14 ];
  6622. this.w = e[ 15 ];
  6623. return this;
  6624. }
  6625. /**
  6626. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6627. * value, replace that value with the corresponding min value.
  6628. *
  6629. * @param {Vector4} v - The vector.
  6630. * @return {Vector4} A reference to this vector.
  6631. */
  6632. min( v ) {
  6633. this.x = Math.min( this.x, v.x );
  6634. this.y = Math.min( this.y, v.y );
  6635. this.z = Math.min( this.z, v.z );
  6636. this.w = Math.min( this.w, v.w );
  6637. return this;
  6638. }
  6639. /**
  6640. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6641. * value, replace that value with the corresponding max value.
  6642. *
  6643. * @param {Vector4} v - The vector.
  6644. * @return {Vector4} A reference to this vector.
  6645. */
  6646. max( v ) {
  6647. this.x = Math.max( this.x, v.x );
  6648. this.y = Math.max( this.y, v.y );
  6649. this.z = Math.max( this.z, v.z );
  6650. this.w = Math.max( this.w, v.w );
  6651. return this;
  6652. }
  6653. /**
  6654. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6655. * value, it is replaced by the corresponding value.
  6656. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6657. * it is replaced by the corresponding value.
  6658. *
  6659. * @param {Vector4} min - The minimum x, y and z values.
  6660. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6661. * @return {Vector4} A reference to this vector.
  6662. */
  6663. clamp( min, max ) {
  6664. // assumes min < max, componentwise
  6665. this.x = clamp( this.x, min.x, max.x );
  6666. this.y = clamp( this.y, min.y, max.y );
  6667. this.z = clamp( this.z, min.z, max.z );
  6668. this.w = clamp( this.w, min.w, max.w );
  6669. return this;
  6670. }
  6671. /**
  6672. * If this vector's x, y, z or w values are greater than the max value, they are
  6673. * replaced by the max value.
  6674. * If this vector's x, y, z or w values are less than the min value, they are
  6675. * replaced by the min value.
  6676. *
  6677. * @param {number} minVal - The minimum value the components will be clamped to.
  6678. * @param {number} maxVal - The maximum value the components will be clamped to.
  6679. * @return {Vector4} A reference to this vector.
  6680. */
  6681. clampScalar( minVal, maxVal ) {
  6682. this.x = clamp( this.x, minVal, maxVal );
  6683. this.y = clamp( this.y, minVal, maxVal );
  6684. this.z = clamp( this.z, minVal, maxVal );
  6685. this.w = clamp( this.w, minVal, maxVal );
  6686. return this;
  6687. }
  6688. /**
  6689. * If this vector's length is greater than the max value, it is replaced by
  6690. * the max value.
  6691. * If this vector's length is less than the min value, it is replaced by the
  6692. * min value.
  6693. *
  6694. * @param {number} min - The minimum value the vector length will be clamped to.
  6695. * @param {number} max - The maximum value the vector length will be clamped to.
  6696. * @return {Vector4} A reference to this vector.
  6697. */
  6698. clampLength( min, max ) {
  6699. const length = this.length();
  6700. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6701. }
  6702. /**
  6703. * The components of this vector are rounded down to the nearest integer value.
  6704. *
  6705. * @return {Vector4} A reference to this vector.
  6706. */
  6707. floor() {
  6708. this.x = Math.floor( this.x );
  6709. this.y = Math.floor( this.y );
  6710. this.z = Math.floor( this.z );
  6711. this.w = Math.floor( this.w );
  6712. return this;
  6713. }
  6714. /**
  6715. * The components of this vector are rounded up to the nearest integer value.
  6716. *
  6717. * @return {Vector4} A reference to this vector.
  6718. */
  6719. ceil() {
  6720. this.x = Math.ceil( this.x );
  6721. this.y = Math.ceil( this.y );
  6722. this.z = Math.ceil( this.z );
  6723. this.w = Math.ceil( this.w );
  6724. return this;
  6725. }
  6726. /**
  6727. * The components of this vector are rounded to the nearest integer value
  6728. *
  6729. * @return {Vector4} A reference to this vector.
  6730. */
  6731. round() {
  6732. this.x = Math.round( this.x );
  6733. this.y = Math.round( this.y );
  6734. this.z = Math.round( this.z );
  6735. this.w = Math.round( this.w );
  6736. return this;
  6737. }
  6738. /**
  6739. * The components of this vector are rounded towards zero (up if negative,
  6740. * down if positive) to an integer value.
  6741. *
  6742. * @return {Vector4} A reference to this vector.
  6743. */
  6744. roundToZero() {
  6745. this.x = Math.trunc( this.x );
  6746. this.y = Math.trunc( this.y );
  6747. this.z = Math.trunc( this.z );
  6748. this.w = Math.trunc( this.w );
  6749. return this;
  6750. }
  6751. /**
  6752. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6753. *
  6754. * @return {Vector4} A reference to this vector.
  6755. */
  6756. negate() {
  6757. this.x = - this.x;
  6758. this.y = - this.y;
  6759. this.z = - this.z;
  6760. this.w = - this.w;
  6761. return this;
  6762. }
  6763. /**
  6764. * Calculates the dot product of the given vector with this instance.
  6765. *
  6766. * @param {Vector4} v - The vector to compute the dot product with.
  6767. * @return {number} The result of the dot product.
  6768. */
  6769. dot( v ) {
  6770. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6771. }
  6772. /**
  6773. * Computes the square of the Euclidean length (straight-line length) from
  6774. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6775. * compare the length squared instead as it is slightly more efficient to calculate.
  6776. *
  6777. * @return {number} The square length of this vector.
  6778. */
  6779. lengthSq() {
  6780. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6781. }
  6782. /**
  6783. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6784. *
  6785. * @return {number} The length of this vector.
  6786. */
  6787. length() {
  6788. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6789. }
  6790. /**
  6791. * Computes the Manhattan length of this vector.
  6792. *
  6793. * @return {number} The length of this vector.
  6794. */
  6795. manhattanLength() {
  6796. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6797. }
  6798. /**
  6799. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6800. * with the same direction as this one, but with a vector length of `1`.
  6801. *
  6802. * @return {Vector4} A reference to this vector.
  6803. */
  6804. normalize() {
  6805. return this.divideScalar( this.length() || 1 );
  6806. }
  6807. /**
  6808. * Sets this vector to a vector with the same direction as this one, but
  6809. * with the specified length.
  6810. *
  6811. * @param {number} length - The new length of this vector.
  6812. * @return {Vector4} A reference to this vector.
  6813. */
  6814. setLength( length ) {
  6815. return this.normalize().multiplyScalar( length );
  6816. }
  6817. /**
  6818. * Linearly interpolates between the given vector and this instance, where
  6819. * alpha is the percent distance along the line - alpha = 0 will be this
  6820. * vector, and alpha = 1 will be the given one.
  6821. *
  6822. * @param {Vector4} v - The vector to interpolate towards.
  6823. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6824. * @return {Vector4} A reference to this vector.
  6825. */
  6826. lerp( v, alpha ) {
  6827. this.x += ( v.x - this.x ) * alpha;
  6828. this.y += ( v.y - this.y ) * alpha;
  6829. this.z += ( v.z - this.z ) * alpha;
  6830. this.w += ( v.w - this.w ) * alpha;
  6831. return this;
  6832. }
  6833. /**
  6834. * Linearly interpolates between the given vectors, where alpha is the percent
  6835. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6836. * be the second one. The result is stored in this instance.
  6837. *
  6838. * @param {Vector4} v1 - The first vector.
  6839. * @param {Vector4} v2 - The second vector.
  6840. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6841. * @return {Vector4} A reference to this vector.
  6842. */
  6843. lerpVectors( v1, v2, alpha ) {
  6844. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6845. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6846. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6847. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6848. return this;
  6849. }
  6850. /**
  6851. * Returns `true` if this vector is equal with the given one.
  6852. *
  6853. * @param {Vector4} v - The vector to test for equality.
  6854. * @return {boolean} Whether this vector is equal with the given one.
  6855. */
  6856. equals( v ) {
  6857. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6858. }
  6859. /**
  6860. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6861. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6862. *
  6863. * @param {Array<number>} array - An array holding the vector component values.
  6864. * @param {number} [offset=0] - The offset into the array.
  6865. * @return {Vector4} A reference to this vector.
  6866. */
  6867. fromArray( array, offset = 0 ) {
  6868. this.x = array[ offset ];
  6869. this.y = array[ offset + 1 ];
  6870. this.z = array[ offset + 2 ];
  6871. this.w = array[ offset + 3 ];
  6872. return this;
  6873. }
  6874. /**
  6875. * Writes the components of this vector to the given array. If no array is provided,
  6876. * the method returns a new instance.
  6877. *
  6878. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6879. * @param {number} [offset=0] - Index of the first element in the array.
  6880. * @return {Array<number>} The vector components.
  6881. */
  6882. toArray( array = [], offset = 0 ) {
  6883. array[ offset ] = this.x;
  6884. array[ offset + 1 ] = this.y;
  6885. array[ offset + 2 ] = this.z;
  6886. array[ offset + 3 ] = this.w;
  6887. return array;
  6888. }
  6889. /**
  6890. * Sets the components of this vector from the given buffer attribute.
  6891. *
  6892. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6893. * @param {number} index - The index into the attribute.
  6894. * @return {Vector4} A reference to this vector.
  6895. */
  6896. fromBufferAttribute( attribute, index ) {
  6897. this.x = attribute.getX( index );
  6898. this.y = attribute.getY( index );
  6899. this.z = attribute.getZ( index );
  6900. this.w = attribute.getW( index );
  6901. return this;
  6902. }
  6903. /**
  6904. * Sets each component of this vector to a pseudo-random value between `0` and
  6905. * `1`, excluding `1`.
  6906. *
  6907. * @return {Vector4} A reference to this vector.
  6908. */
  6909. random() {
  6910. this.x = Math.random();
  6911. this.y = Math.random();
  6912. this.z = Math.random();
  6913. this.w = Math.random();
  6914. return this;
  6915. }
  6916. *[ Symbol.iterator ]() {
  6917. yield this.x;
  6918. yield this.y;
  6919. yield this.z;
  6920. yield this.w;
  6921. }
  6922. }
  6923. /**
  6924. * A render target is a buffer where the video card draws pixels for a scene
  6925. * that is being rendered in the background. It is used in different effects,
  6926. * such as applying postprocessing to a rendered image before displaying it
  6927. * on the screen.
  6928. *
  6929. * @augments EventDispatcher
  6930. */
  6931. class RenderTarget extends EventDispatcher {
  6932. /**
  6933. * Render target options.
  6934. *
  6935. * @typedef {Object} RenderTarget~Options
  6936. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6937. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6938. * @property {number} [minFilter=LinearFilter] - The min filter.
  6939. * @property {number} [format=RGBAFormat] - The texture format.
  6940. * @property {number} [type=UnsignedByteType] - The texture type.
  6941. * @property {?string} [internalFormat=null] - The texture's internal format.
  6942. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6943. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6944. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6945. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6946. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6947. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6948. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6949. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6950. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6951. * @property {number} [samples=0] - The MSAA samples count.
  6952. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6953. * @property {number} [depth=1] - The texture depth.
  6954. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6955. */
  6956. /**
  6957. * Constructs a new render target.
  6958. *
  6959. * @param {number} [width=1] - The width of the render target.
  6960. * @param {number} [height=1] - The height of the render target.
  6961. * @param {RenderTarget~Options} [options] - The configuration object.
  6962. */
  6963. constructor( width = 1, height = 1, options = {} ) {
  6964. super();
  6965. options = Object.assign( {
  6966. generateMipmaps: false,
  6967. internalFormat: null,
  6968. minFilter: LinearFilter,
  6969. depthBuffer: true,
  6970. stencilBuffer: false,
  6971. resolveDepthBuffer: true,
  6972. resolveStencilBuffer: true,
  6973. depthTexture: null,
  6974. samples: 0,
  6975. count: 1,
  6976. depth: 1,
  6977. multiview: false
  6978. }, options );
  6979. /**
  6980. * This flag can be used for type testing.
  6981. *
  6982. * @type {boolean}
  6983. * @readonly
  6984. * @default true
  6985. */
  6986. this.isRenderTarget = true;
  6987. /**
  6988. * The width of the render target.
  6989. *
  6990. * @type {number}
  6991. * @default 1
  6992. */
  6993. this.width = width;
  6994. /**
  6995. * The height of the render target.
  6996. *
  6997. * @type {number}
  6998. * @default 1
  6999. */
  7000. this.height = height;
  7001. /**
  7002. * The depth of the render target.
  7003. *
  7004. * @type {number}
  7005. * @default 1
  7006. */
  7007. this.depth = options.depth;
  7008. /**
  7009. * A rectangular area inside the render target's viewport. Fragments that are
  7010. * outside the area will be discarded.
  7011. *
  7012. * @type {Vector4}
  7013. * @default (0,0,width,height)
  7014. */
  7015. this.scissor = new Vector4( 0, 0, width, height );
  7016. /**
  7017. * Indicates whether the scissor test should be enabled when rendering into
  7018. * this render target or not.
  7019. *
  7020. * @type {boolean}
  7021. * @default false
  7022. */
  7023. this.scissorTest = false;
  7024. /**
  7025. * A rectangular area representing the render target's viewport.
  7026. *
  7027. * @type {Vector4}
  7028. * @default (0,0,width,height)
  7029. */
  7030. this.viewport = new Vector4( 0, 0, width, height );
  7031. const image = { width: width, height: height, depth: options.depth };
  7032. const texture = new Texture( image );
  7033. /**
  7034. * An array of textures. Each color attachment is represented as a separate texture.
  7035. * Has at least a single entry for the default color attachment.
  7036. *
  7037. * @type {Array<Texture>}
  7038. */
  7039. this.textures = [];
  7040. const count = options.count;
  7041. for ( let i = 0; i < count; i ++ ) {
  7042. this.textures[ i ] = texture.clone();
  7043. this.textures[ i ].isRenderTargetTexture = true;
  7044. this.textures[ i ].renderTarget = this;
  7045. }
  7046. this._setTextureOptions( options );
  7047. /**
  7048. * Whether to allocate a depth buffer or not.
  7049. *
  7050. * @type {boolean}
  7051. * @default true
  7052. */
  7053. this.depthBuffer = options.depthBuffer;
  7054. /**
  7055. * Whether to allocate a stencil buffer or not.
  7056. *
  7057. * @type {boolean}
  7058. * @default false
  7059. */
  7060. this.stencilBuffer = options.stencilBuffer;
  7061. /**
  7062. * Whether to resolve the depth buffer or not.
  7063. *
  7064. * @type {boolean}
  7065. * @default true
  7066. */
  7067. this.resolveDepthBuffer = options.resolveDepthBuffer;
  7068. /**
  7069. * Whether to resolve the stencil buffer or not.
  7070. *
  7071. * @type {boolean}
  7072. * @default true
  7073. */
  7074. this.resolveStencilBuffer = options.resolveStencilBuffer;
  7075. this._depthTexture = null;
  7076. this.depthTexture = options.depthTexture;
  7077. /**
  7078. * The number of MSAA samples.
  7079. *
  7080. * A value of `0` disables MSAA.
  7081. *
  7082. * @type {number}
  7083. * @default 0
  7084. */
  7085. this.samples = options.samples;
  7086. /**
  7087. * Whether to this target is used in multiview rendering.
  7088. *
  7089. * @type {boolean}
  7090. * @default false
  7091. */
  7092. this.multiview = options.multiview;
  7093. }
  7094. _setTextureOptions( options = {} ) {
  7095. const values = {
  7096. minFilter: LinearFilter,
  7097. generateMipmaps: false,
  7098. flipY: false,
  7099. internalFormat: null
  7100. };
  7101. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  7102. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  7103. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  7104. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  7105. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  7106. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  7107. if ( options.format !== undefined ) values.format = options.format;
  7108. if ( options.type !== undefined ) values.type = options.type;
  7109. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  7110. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  7111. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  7112. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  7113. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  7114. for ( let i = 0; i < this.textures.length; i ++ ) {
  7115. const texture = this.textures[ i ];
  7116. texture.setValues( values );
  7117. }
  7118. }
  7119. /**
  7120. * The texture representing the default color attachment.
  7121. *
  7122. * @type {Texture}
  7123. */
  7124. get texture() {
  7125. return this.textures[ 0 ];
  7126. }
  7127. set texture( value ) {
  7128. this.textures[ 0 ] = value;
  7129. }
  7130. set depthTexture( current ) {
  7131. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7132. if ( current !== null ) current.renderTarget = this;
  7133. this._depthTexture = current;
  7134. }
  7135. /**
  7136. * Instead of saving the depth in a renderbuffer, a texture
  7137. * can be used instead which is useful for further processing
  7138. * e.g. in context of post-processing.
  7139. *
  7140. * @type {?DepthTexture}
  7141. * @default null
  7142. */
  7143. get depthTexture() {
  7144. return this._depthTexture;
  7145. }
  7146. /**
  7147. * Sets the size of this render target.
  7148. *
  7149. * @param {number} width - The width.
  7150. * @param {number} height - The height.
  7151. * @param {number} [depth=1] - The depth.
  7152. */
  7153. setSize( width, height, depth = 1 ) {
  7154. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7155. this.width = width;
  7156. this.height = height;
  7157. this.depth = depth;
  7158. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7159. this.textures[ i ].image.width = width;
  7160. this.textures[ i ].image.height = height;
  7161. this.textures[ i ].image.depth = depth;
  7162. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7163. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7164. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7165. // both are evaluated on each call?
  7166. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7167. }
  7168. }
  7169. this.dispose();
  7170. }
  7171. this.viewport.set( 0, 0, width, height );
  7172. this.scissor.set( 0, 0, width, height );
  7173. }
  7174. /**
  7175. * Returns a new render target with copied values from this instance.
  7176. *
  7177. * @return {RenderTarget} A clone of this instance.
  7178. */
  7179. clone() {
  7180. return new this.constructor().copy( this );
  7181. }
  7182. /**
  7183. * Copies the settings of the given render target. This is a structural copy so
  7184. * no resources are shared between render targets after the copy. That includes
  7185. * all MRT textures and the depth texture.
  7186. *
  7187. * @param {RenderTarget} source - The render target to copy.
  7188. * @return {RenderTarget} A reference to this instance.
  7189. */
  7190. copy( source ) {
  7191. this.width = source.width;
  7192. this.height = source.height;
  7193. this.depth = source.depth;
  7194. this.scissor.copy( source.scissor );
  7195. this.scissorTest = source.scissorTest;
  7196. this.viewport.copy( source.viewport );
  7197. this.textures.length = 0;
  7198. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7199. this.textures[ i ] = source.textures[ i ].clone();
  7200. this.textures[ i ].isRenderTargetTexture = true;
  7201. this.textures[ i ].renderTarget = this;
  7202. // ensure image object is not shared, see #20328
  7203. const image = Object.assign( {}, source.textures[ i ].image );
  7204. this.textures[ i ].source = new Source( image );
  7205. }
  7206. this.depthBuffer = source.depthBuffer;
  7207. this.stencilBuffer = source.stencilBuffer;
  7208. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7209. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7210. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7211. this.samples = source.samples;
  7212. return this;
  7213. }
  7214. /**
  7215. * Frees the GPU-related resources allocated by this instance. Call this
  7216. * method whenever this instance is no longer used in your app.
  7217. *
  7218. * @fires RenderTarget#dispose
  7219. */
  7220. dispose() {
  7221. this.dispatchEvent( { type: 'dispose' } );
  7222. }
  7223. }
  7224. /**
  7225. * A render target used in context of {@link WebGLRenderer}.
  7226. *
  7227. * @augments RenderTarget
  7228. */
  7229. class WebGLRenderTarget extends RenderTarget {
  7230. /**
  7231. * Constructs a new 3D render target.
  7232. *
  7233. * @param {number} [width=1] - The width of the render target.
  7234. * @param {number} [height=1] - The height of the render target.
  7235. * @param {RenderTarget~Options} [options] - The configuration object.
  7236. */
  7237. constructor( width = 1, height = 1, options = {} ) {
  7238. super( width, height, options );
  7239. /**
  7240. * This flag can be used for type testing.
  7241. *
  7242. * @type {boolean}
  7243. * @readonly
  7244. * @default true
  7245. */
  7246. this.isWebGLRenderTarget = true;
  7247. }
  7248. }
  7249. /**
  7250. * Creates an array of textures directly from raw buffer data.
  7251. *
  7252. * @augments Texture
  7253. */
  7254. class DataArrayTexture extends Texture {
  7255. /**
  7256. * Constructs a new data array texture.
  7257. *
  7258. * @param {?TypedArray} [data=null] - The buffer data.
  7259. * @param {number} [width=1] - The width of the texture.
  7260. * @param {number} [height=1] - The height of the texture.
  7261. * @param {number} [depth=1] - The depth of the texture.
  7262. */
  7263. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7264. super( null );
  7265. /**
  7266. * This flag can be used for type testing.
  7267. *
  7268. * @type {boolean}
  7269. * @readonly
  7270. * @default true
  7271. */
  7272. this.isDataArrayTexture = true;
  7273. /**
  7274. * The image definition of a data texture.
  7275. *
  7276. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7277. */
  7278. this.image = { data, width, height, depth };
  7279. /**
  7280. * How the texture is sampled when a texel covers more than one pixel.
  7281. *
  7282. * Overwritten and set to `NearestFilter` by default.
  7283. *
  7284. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7285. * @default NearestFilter
  7286. */
  7287. this.magFilter = NearestFilter;
  7288. /**
  7289. * How the texture is sampled when a texel covers less than one pixel.
  7290. *
  7291. * Overwritten and set to `NearestFilter` by default.
  7292. *
  7293. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7294. * @default NearestFilter
  7295. */
  7296. this.minFilter = NearestFilter;
  7297. /**
  7298. * This defines how the texture is wrapped in the depth and corresponds to
  7299. * *W* in UVW mapping.
  7300. *
  7301. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7302. * @default ClampToEdgeWrapping
  7303. */
  7304. this.wrapR = ClampToEdgeWrapping;
  7305. /**
  7306. * Whether to generate mipmaps (if possible) for a texture.
  7307. *
  7308. * Overwritten and set to `false` by default.
  7309. *
  7310. * @type {boolean}
  7311. * @default false
  7312. */
  7313. this.generateMipmaps = false;
  7314. /**
  7315. * If set to `true`, the texture is flipped along the vertical axis when
  7316. * uploaded to the GPU.
  7317. *
  7318. * Overwritten and set to `false` by default.
  7319. *
  7320. * @type {boolean}
  7321. * @default false
  7322. */
  7323. this.flipY = false;
  7324. /**
  7325. * Specifies the alignment requirements for the start of each pixel row in memory.
  7326. *
  7327. * Overwritten and set to `1` by default.
  7328. *
  7329. * @type {boolean}
  7330. * @default 1
  7331. */
  7332. this.unpackAlignment = 1;
  7333. /**
  7334. * A set of all layers which need to be updated in the texture.
  7335. *
  7336. * @type {Set<number>}
  7337. */
  7338. this.layerUpdates = new Set();
  7339. }
  7340. /**
  7341. * Describes that a specific layer of the texture needs to be updated.
  7342. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7343. * entire data texture array is sent to the GPU. Marking specific
  7344. * layers will only transmit subsets of all mipmaps associated with a
  7345. * specific depth in the array which is often much more performant.
  7346. *
  7347. * @param {number} layerIndex - The layer index that should be updated.
  7348. */
  7349. addLayerUpdate( layerIndex ) {
  7350. this.layerUpdates.add( layerIndex );
  7351. }
  7352. /**
  7353. * Resets the layer updates registry.
  7354. */
  7355. clearLayerUpdates() {
  7356. this.layerUpdates.clear();
  7357. }
  7358. }
  7359. /**
  7360. * An array render target used in context of {@link WebGLRenderer}.
  7361. *
  7362. * @augments WebGLRenderTarget
  7363. */
  7364. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7365. /**
  7366. * Constructs a new array render target.
  7367. *
  7368. * @param {number} [width=1] - The width of the render target.
  7369. * @param {number} [height=1] - The height of the render target.
  7370. * @param {number} [depth=1] - The height of the render target.
  7371. * @param {RenderTarget~Options} [options] - The configuration object.
  7372. */
  7373. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7374. super( width, height, options );
  7375. /**
  7376. * This flag can be used for type testing.
  7377. *
  7378. * @type {boolean}
  7379. * @readonly
  7380. * @default true
  7381. */
  7382. this.isWebGLArrayRenderTarget = true;
  7383. this.depth = depth;
  7384. /**
  7385. * Overwritten with a different texture type.
  7386. *
  7387. * @type {DataArrayTexture}
  7388. */
  7389. this.texture = new DataArrayTexture( null, width, height, depth );
  7390. this._setTextureOptions( options );
  7391. this.texture.isRenderTargetTexture = true;
  7392. }
  7393. }
  7394. /**
  7395. * Creates a three-dimensional texture from raw data, with parameters to
  7396. * divide it into width, height, and depth.
  7397. *
  7398. * @augments Texture
  7399. */
  7400. class Data3DTexture extends Texture {
  7401. /**
  7402. * Constructs a new data array texture.
  7403. *
  7404. * @param {?TypedArray} [data=null] - The buffer data.
  7405. * @param {number} [width=1] - The width of the texture.
  7406. * @param {number} [height=1] - The height of the texture.
  7407. * @param {number} [depth=1] - The depth of the texture.
  7408. */
  7409. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7410. // We're going to add .setXXX() methods for setting properties later.
  7411. // Users can still set in Data3DTexture directly.
  7412. //
  7413. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7414. // texture.anisotropy = 16;
  7415. //
  7416. // See #14839
  7417. super( null );
  7418. /**
  7419. * This flag can be used for type testing.
  7420. *
  7421. * @type {boolean}
  7422. * @readonly
  7423. * @default true
  7424. */
  7425. this.isData3DTexture = true;
  7426. /**
  7427. * The image definition of a data texture.
  7428. *
  7429. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7430. */
  7431. this.image = { data, width, height, depth };
  7432. /**
  7433. * How the texture is sampled when a texel covers more than one pixel.
  7434. *
  7435. * Overwritten and set to `NearestFilter` by default.
  7436. *
  7437. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7438. * @default NearestFilter
  7439. */
  7440. this.magFilter = NearestFilter;
  7441. /**
  7442. * How the texture is sampled when a texel covers less than one pixel.
  7443. *
  7444. * Overwritten and set to `NearestFilter` by default.
  7445. *
  7446. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7447. * @default NearestFilter
  7448. */
  7449. this.minFilter = NearestFilter;
  7450. /**
  7451. * This defines how the texture is wrapped in the depth and corresponds to
  7452. * *W* in UVW mapping.
  7453. *
  7454. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7455. * @default ClampToEdgeWrapping
  7456. */
  7457. this.wrapR = ClampToEdgeWrapping;
  7458. /**
  7459. * Whether to generate mipmaps (if possible) for a texture.
  7460. *
  7461. * Overwritten and set to `false` by default.
  7462. *
  7463. * @type {boolean}
  7464. * @default false
  7465. */
  7466. this.generateMipmaps = false;
  7467. /**
  7468. * If set to `true`, the texture is flipped along the vertical axis when
  7469. * uploaded to the GPU.
  7470. *
  7471. * Overwritten and set to `false` by default.
  7472. *
  7473. * @type {boolean}
  7474. * @default false
  7475. */
  7476. this.flipY = false;
  7477. /**
  7478. * Specifies the alignment requirements for the start of each pixel row in memory.
  7479. *
  7480. * Overwritten and set to `1` by default.
  7481. *
  7482. * @type {boolean}
  7483. * @default 1
  7484. */
  7485. this.unpackAlignment = 1;
  7486. }
  7487. }
  7488. /**
  7489. * A 3D render target used in context of {@link WebGLRenderer}.
  7490. *
  7491. * @augments WebGLRenderTarget
  7492. */
  7493. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7494. /**
  7495. * Constructs a new 3D render target.
  7496. *
  7497. * @param {number} [width=1] - The width of the render target.
  7498. * @param {number} [height=1] - The height of the render target.
  7499. * @param {number} [depth=1] - The height of the render target.
  7500. * @param {RenderTarget~Options} [options] - The configuration object.
  7501. */
  7502. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7503. super( width, height, options );
  7504. /**
  7505. * This flag can be used for type testing.
  7506. *
  7507. * @type {boolean}
  7508. * @readonly
  7509. * @default true
  7510. */
  7511. this.isWebGL3DRenderTarget = true;
  7512. this.depth = depth;
  7513. /**
  7514. * Overwritten with a different texture type.
  7515. *
  7516. * @type {Data3DTexture}
  7517. */
  7518. this.texture = new Data3DTexture( null, width, height, depth );
  7519. this._setTextureOptions( options );
  7520. this.texture.isRenderTargetTexture = true;
  7521. }
  7522. }
  7523. /**
  7524. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7525. */
  7526. class Box3 {
  7527. /**
  7528. * Constructs a new bounding box.
  7529. *
  7530. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7531. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7532. */
  7533. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7534. /**
  7535. * This flag can be used for type testing.
  7536. *
  7537. * @type {boolean}
  7538. * @readonly
  7539. * @default true
  7540. */
  7541. this.isBox3 = true;
  7542. /**
  7543. * The lower boundary of the box.
  7544. *
  7545. * @type {Vector3}
  7546. */
  7547. this.min = min;
  7548. /**
  7549. * The upper boundary of the box.
  7550. *
  7551. * @type {Vector3}
  7552. */
  7553. this.max = max;
  7554. }
  7555. /**
  7556. * Sets the lower and upper boundaries of this box.
  7557. * Please note that this method only copies the values from the given objects.
  7558. *
  7559. * @param {Vector3} min - The lower boundary of the box.
  7560. * @param {Vector3} max - The upper boundary of the box.
  7561. * @return {Box3} A reference to this bounding box.
  7562. */
  7563. set( min, max ) {
  7564. this.min.copy( min );
  7565. this.max.copy( max );
  7566. return this;
  7567. }
  7568. /**
  7569. * Sets the upper and lower bounds of this box so it encloses the position data
  7570. * in the given array.
  7571. *
  7572. * @param {Array<number>} array - An array holding 3D position data.
  7573. * @return {Box3} A reference to this bounding box.
  7574. */
  7575. setFromArray( array ) {
  7576. this.makeEmpty();
  7577. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7578. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7579. }
  7580. return this;
  7581. }
  7582. /**
  7583. * Sets the upper and lower bounds of this box so it encloses the position data
  7584. * in the given buffer attribute.
  7585. *
  7586. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7587. * @return {Box3} A reference to this bounding box.
  7588. */
  7589. setFromBufferAttribute( attribute ) {
  7590. this.makeEmpty();
  7591. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7592. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7593. }
  7594. return this;
  7595. }
  7596. /**
  7597. * Sets the upper and lower bounds of this box so it encloses the position data
  7598. * in the given array.
  7599. *
  7600. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7601. * @return {Box3} A reference to this bounding box.
  7602. */
  7603. setFromPoints( points ) {
  7604. this.makeEmpty();
  7605. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7606. this.expandByPoint( points[ i ] );
  7607. }
  7608. return this;
  7609. }
  7610. /**
  7611. * Centers this box on the given center vector and sets this box's width, height and
  7612. * depth to the given size values.
  7613. *
  7614. * @param {Vector3} center - The center of the box.
  7615. * @param {Vector3} size - The x, y and z dimensions of the box.
  7616. * @return {Box3} A reference to this bounding box.
  7617. */
  7618. setFromCenterAndSize( center, size ) {
  7619. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7620. this.min.copy( center ).sub( halfSize );
  7621. this.max.copy( center ).add( halfSize );
  7622. return this;
  7623. }
  7624. /**
  7625. * Computes the world-axis-aligned bounding box for the given 3D object
  7626. * (including its children), accounting for the object's, and children's,
  7627. * world transforms. The function may result in a larger box than strictly necessary.
  7628. *
  7629. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7630. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7631. * world-axis-aligned bounding box at the expense of more computation.
  7632. * @return {Box3} A reference to this bounding box.
  7633. */
  7634. setFromObject( object, precise = false ) {
  7635. this.makeEmpty();
  7636. return this.expandByObject( object, precise );
  7637. }
  7638. /**
  7639. * Returns a new box with copied values from this instance.
  7640. *
  7641. * @return {Box3} A clone of this instance.
  7642. */
  7643. clone() {
  7644. return new this.constructor().copy( this );
  7645. }
  7646. /**
  7647. * Copies the values of the given box to this instance.
  7648. *
  7649. * @param {Box3} box - The box to copy.
  7650. * @return {Box3} A reference to this bounding box.
  7651. */
  7652. copy( box ) {
  7653. this.min.copy( box.min );
  7654. this.max.copy( box.max );
  7655. return this;
  7656. }
  7657. /**
  7658. * Makes this box empty which means in encloses a zero space in 3D.
  7659. *
  7660. * @return {Box3} A reference to this bounding box.
  7661. */
  7662. makeEmpty() {
  7663. this.min.x = this.min.y = this.min.z = + Infinity;
  7664. this.max.x = this.max.y = this.max.z = - Infinity;
  7665. return this;
  7666. }
  7667. /**
  7668. * Returns true if this box includes zero points within its bounds.
  7669. * Note that a box with equal lower and upper bounds still includes one
  7670. * point, the one both bounds share.
  7671. *
  7672. * @return {boolean} Whether this box is empty or not.
  7673. */
  7674. isEmpty() {
  7675. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7676. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7677. }
  7678. /**
  7679. * Returns the center point of this box.
  7680. *
  7681. * @param {Vector3} target - The target vector that is used to store the method's result.
  7682. * @return {Vector3} The center point.
  7683. */
  7684. getCenter( target ) {
  7685. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7686. }
  7687. /**
  7688. * Returns the dimensions of this box.
  7689. *
  7690. * @param {Vector3} target - The target vector that is used to store the method's result.
  7691. * @return {Vector3} The size.
  7692. */
  7693. getSize( target ) {
  7694. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7695. }
  7696. /**
  7697. * Expands the boundaries of this box to include the given point.
  7698. *
  7699. * @param {Vector3} point - The point that should be included by the bounding box.
  7700. * @return {Box3} A reference to this bounding box.
  7701. */
  7702. expandByPoint( point ) {
  7703. this.min.min( point );
  7704. this.max.max( point );
  7705. return this;
  7706. }
  7707. /**
  7708. * Expands this box equilaterally by the given vector. The width of this
  7709. * box will be expanded by the x component of the vector in both
  7710. * directions. The height of this box will be expanded by the y component of
  7711. * the vector in both directions. The depth of this box will be
  7712. * expanded by the z component of the vector in both directions.
  7713. *
  7714. * @param {Vector3} vector - The vector that should expand the bounding box.
  7715. * @return {Box3} A reference to this bounding box.
  7716. */
  7717. expandByVector( vector ) {
  7718. this.min.sub( vector );
  7719. this.max.add( vector );
  7720. return this;
  7721. }
  7722. /**
  7723. * Expands each dimension of the box by the given scalar. If negative, the
  7724. * dimensions of the box will be contracted.
  7725. *
  7726. * @param {number} scalar - The scalar value that should expand the bounding box.
  7727. * @return {Box3} A reference to this bounding box.
  7728. */
  7729. expandByScalar( scalar ) {
  7730. this.min.addScalar( - scalar );
  7731. this.max.addScalar( scalar );
  7732. return this;
  7733. }
  7734. /**
  7735. * Expands the boundaries of this box to include the given 3D object and
  7736. * its children, accounting for the object's, and children's, world
  7737. * transforms. The function may result in a larger box than strictly
  7738. * necessary (unless the precise parameter is set to true).
  7739. *
  7740. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7741. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7742. * as little as necessary at the expense of more computation.
  7743. * @return {Box3} A reference to this bounding box.
  7744. */
  7745. expandByObject( object, precise = false ) {
  7746. // Computes the world-axis-aligned bounding box of an object (including its children),
  7747. // accounting for both the object's, and children's, world transforms
  7748. object.updateWorldMatrix( false, false );
  7749. const geometry = object.geometry;
  7750. if ( geometry !== undefined ) {
  7751. const positionAttribute = geometry.getAttribute( 'position' );
  7752. // precise AABB computation based on vertex data requires at least a position attribute.
  7753. // instancing isn't supported so far and uses the normal (conservative) code path.
  7754. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7755. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7756. if ( object.isMesh === true ) {
  7757. object.getVertexPosition( i, _vector$b );
  7758. } else {
  7759. _vector$b.fromBufferAttribute( positionAttribute, i );
  7760. }
  7761. _vector$b.applyMatrix4( object.matrixWorld );
  7762. this.expandByPoint( _vector$b );
  7763. }
  7764. } else {
  7765. if ( object.boundingBox !== undefined ) {
  7766. // object-level bounding box
  7767. if ( object.boundingBox === null ) {
  7768. object.computeBoundingBox();
  7769. }
  7770. _box$4.copy( object.boundingBox );
  7771. } else {
  7772. // geometry-level bounding box
  7773. if ( geometry.boundingBox === null ) {
  7774. geometry.computeBoundingBox();
  7775. }
  7776. _box$4.copy( geometry.boundingBox );
  7777. }
  7778. _box$4.applyMatrix4( object.matrixWorld );
  7779. this.union( _box$4 );
  7780. }
  7781. }
  7782. const children = object.children;
  7783. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7784. this.expandByObject( children[ i ], precise );
  7785. }
  7786. return this;
  7787. }
  7788. /**
  7789. * Returns `true` if the given point lies within or on the boundaries of this box.
  7790. *
  7791. * @param {Vector3} point - The point to test.
  7792. * @return {boolean} Whether the bounding box contains the given point or not.
  7793. */
  7794. containsPoint( point ) {
  7795. return point.x >= this.min.x && point.x <= this.max.x &&
  7796. point.y >= this.min.y && point.y <= this.max.y &&
  7797. point.z >= this.min.z && point.z <= this.max.z;
  7798. }
  7799. /**
  7800. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7801. * If this box and the given one are identical, this function also returns `true`.
  7802. *
  7803. * @param {Box3} box - The bounding box to test.
  7804. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7805. */
  7806. containsBox( box ) {
  7807. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7808. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7809. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7810. }
  7811. /**
  7812. * Returns a point as a proportion of this box's width, height and depth.
  7813. *
  7814. * @param {Vector3} point - A point in 3D space.
  7815. * @param {Vector3} target - The target vector that is used to store the method's result.
  7816. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7817. */
  7818. getParameter( point, target ) {
  7819. // This can potentially have a divide by zero if the box
  7820. // has a size dimension of 0.
  7821. return target.set(
  7822. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7823. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7824. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7825. );
  7826. }
  7827. /**
  7828. * Returns `true` if the given bounding box intersects with this bounding box.
  7829. *
  7830. * @param {Box3} box - The bounding box to test.
  7831. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7832. */
  7833. intersectsBox( box ) {
  7834. // using 6 splitting planes to rule out intersections.
  7835. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7836. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7837. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7838. }
  7839. /**
  7840. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7841. *
  7842. * @param {Sphere} sphere - The bounding sphere to test.
  7843. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7844. */
  7845. intersectsSphere( sphere ) {
  7846. // Find the point on the AABB closest to the sphere center.
  7847. this.clampPoint( sphere.center, _vector$b );
  7848. // If that point is inside the sphere, the AABB and sphere intersect.
  7849. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7850. }
  7851. /**
  7852. * Returns `true` if the given plane intersects with this bounding box.
  7853. *
  7854. * @param {Plane} plane - The plane to test.
  7855. * @return {boolean} Whether the given plane intersects with this bounding box.
  7856. */
  7857. intersectsPlane( plane ) {
  7858. // We compute the minimum and maximum dot product values. If those values
  7859. // are on the same side (back or front) of the plane, then there is no intersection.
  7860. let min, max;
  7861. if ( plane.normal.x > 0 ) {
  7862. min = plane.normal.x * this.min.x;
  7863. max = plane.normal.x * this.max.x;
  7864. } else {
  7865. min = plane.normal.x * this.max.x;
  7866. max = plane.normal.x * this.min.x;
  7867. }
  7868. if ( plane.normal.y > 0 ) {
  7869. min += plane.normal.y * this.min.y;
  7870. max += plane.normal.y * this.max.y;
  7871. } else {
  7872. min += plane.normal.y * this.max.y;
  7873. max += plane.normal.y * this.min.y;
  7874. }
  7875. if ( plane.normal.z > 0 ) {
  7876. min += plane.normal.z * this.min.z;
  7877. max += plane.normal.z * this.max.z;
  7878. } else {
  7879. min += plane.normal.z * this.max.z;
  7880. max += plane.normal.z * this.min.z;
  7881. }
  7882. return ( min <= - plane.constant && max >= - plane.constant );
  7883. }
  7884. /**
  7885. * Returns `true` if the given triangle intersects with this bounding box.
  7886. *
  7887. * @param {Triangle} triangle - The triangle to test.
  7888. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7889. */
  7890. intersectsTriangle( triangle ) {
  7891. if ( this.isEmpty() ) {
  7892. return false;
  7893. }
  7894. // compute box center and extents
  7895. this.getCenter( _center );
  7896. _extents.subVectors( this.max, _center );
  7897. // translate triangle to aabb origin
  7898. _v0$3.subVectors( triangle.a, _center );
  7899. _v1$7.subVectors( triangle.b, _center );
  7900. _v2$4.subVectors( triangle.c, _center );
  7901. // compute edge vectors for triangle
  7902. _f0.subVectors( _v1$7, _v0$3 );
  7903. _f1.subVectors( _v2$4, _v1$7 );
  7904. _f2.subVectors( _v0$3, _v2$4 );
  7905. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7906. // 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
  7907. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7908. let axes = [
  7909. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7910. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7911. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7912. ];
  7913. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7914. return false;
  7915. }
  7916. // test 3 face normals from the aabb
  7917. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7918. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7919. return false;
  7920. }
  7921. // finally testing the face normal of the triangle
  7922. // use already existing triangle edge vectors here
  7923. _triangleNormal.crossVectors( _f0, _f1 );
  7924. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7925. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7926. }
  7927. /**
  7928. * Clamps the given point within the bounds of this box.
  7929. *
  7930. * @param {Vector3} point - The point to clamp.
  7931. * @param {Vector3} target - The target vector that is used to store the method's result.
  7932. * @return {Vector3} The clamped point.
  7933. */
  7934. clampPoint( point, target ) {
  7935. return target.copy( point ).clamp( this.min, this.max );
  7936. }
  7937. /**
  7938. * Returns the euclidean distance from any edge of this box to the specified point. If
  7939. * the given point lies inside of this box, the distance will be `0`.
  7940. *
  7941. * @param {Vector3} point - The point to compute the distance to.
  7942. * @return {number} The euclidean distance.
  7943. */
  7944. distanceToPoint( point ) {
  7945. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7946. }
  7947. /**
  7948. * Returns a bounding sphere that encloses this bounding box.
  7949. *
  7950. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7951. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7952. */
  7953. getBoundingSphere( target ) {
  7954. if ( this.isEmpty() ) {
  7955. target.makeEmpty();
  7956. } else {
  7957. this.getCenter( target.center );
  7958. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7959. }
  7960. return target;
  7961. }
  7962. /**
  7963. * Computes the intersection of this bounding box and the given one, setting the upper
  7964. * bound of this box to the lesser of the two boxes' upper bounds and the
  7965. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7966. * there's no overlap, makes this box empty.
  7967. *
  7968. * @param {Box3} box - The bounding box to intersect with.
  7969. * @return {Box3} A reference to this bounding box.
  7970. */
  7971. intersect( box ) {
  7972. this.min.max( box.min );
  7973. this.max.min( box.max );
  7974. // 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.
  7975. if ( this.isEmpty() ) this.makeEmpty();
  7976. return this;
  7977. }
  7978. /**
  7979. * Computes the union of this box and another and the given one, setting the upper
  7980. * bound of this box to the greater of the two boxes' upper bounds and the
  7981. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7982. *
  7983. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7984. * @return {Box3} A reference to this bounding box.
  7985. */
  7986. union( box ) {
  7987. this.min.min( box.min );
  7988. this.max.max( box.max );
  7989. return this;
  7990. }
  7991. /**
  7992. * Transforms this bounding box by the given 4x4 transformation matrix.
  7993. *
  7994. * @param {Matrix4} matrix - The transformation matrix.
  7995. * @return {Box3} A reference to this bounding box.
  7996. */
  7997. applyMatrix4( matrix ) {
  7998. // transform of empty box is an empty box.
  7999. if ( this.isEmpty() ) return this;
  8000. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  8001. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  8002. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  8003. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  8004. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  8005. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  8006. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  8007. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  8008. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  8009. this.setFromPoints( _points );
  8010. return this;
  8011. }
  8012. /**
  8013. * Adds the given offset to both the upper and lower bounds of this bounding box,
  8014. * effectively moving it in 3D space.
  8015. *
  8016. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  8017. * @return {Box3} A reference to this bounding box.
  8018. */
  8019. translate( offset ) {
  8020. this.min.add( offset );
  8021. this.max.add( offset );
  8022. return this;
  8023. }
  8024. /**
  8025. * Returns `true` if this bounding box is equal with the given one.
  8026. *
  8027. * @param {Box3} box - The box to test for equality.
  8028. * @return {boolean} Whether this bounding box is equal with the given one.
  8029. */
  8030. equals( box ) {
  8031. return box.min.equals( this.min ) && box.max.equals( this.max );
  8032. }
  8033. /**
  8034. * Returns a serialized structure of the bounding box.
  8035. *
  8036. * @return {Object} Serialized structure with fields representing the object state.
  8037. */
  8038. toJSON() {
  8039. return {
  8040. min: this.min.toArray(),
  8041. max: this.max.toArray()
  8042. };
  8043. }
  8044. /**
  8045. * Returns a serialized structure of the bounding box.
  8046. *
  8047. * @param {Object} json - The serialized json to set the box from.
  8048. * @return {Box3} A reference to this bounding box.
  8049. */
  8050. fromJSON( json ) {
  8051. this.min.fromArray( json.min );
  8052. this.max.fromArray( json.max );
  8053. return this;
  8054. }
  8055. }
  8056. const _points = [
  8057. /*@__PURE__*/ new Vector3(),
  8058. /*@__PURE__*/ new Vector3(),
  8059. /*@__PURE__*/ new Vector3(),
  8060. /*@__PURE__*/ new Vector3(),
  8061. /*@__PURE__*/ new Vector3(),
  8062. /*@__PURE__*/ new Vector3(),
  8063. /*@__PURE__*/ new Vector3(),
  8064. /*@__PURE__*/ new Vector3()
  8065. ];
  8066. const _vector$b = /*@__PURE__*/ new Vector3();
  8067. const _box$4 = /*@__PURE__*/ new Box3();
  8068. // triangle centered vertices
  8069. const _v0$3 = /*@__PURE__*/ new Vector3();
  8070. const _v1$7 = /*@__PURE__*/ new Vector3();
  8071. const _v2$4 = /*@__PURE__*/ new Vector3();
  8072. // triangle edge vectors
  8073. const _f0 = /*@__PURE__*/ new Vector3();
  8074. const _f1 = /*@__PURE__*/ new Vector3();
  8075. const _f2 = /*@__PURE__*/ new Vector3();
  8076. const _center = /*@__PURE__*/ new Vector3();
  8077. const _extents = /*@__PURE__*/ new Vector3();
  8078. const _triangleNormal = /*@__PURE__*/ new Vector3();
  8079. const _testAxis = /*@__PURE__*/ new Vector3();
  8080. function satForAxes( axes, v0, v1, v2, extents ) {
  8081. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  8082. _testAxis.fromArray( axes, i );
  8083. // project the aabb onto the separating axis
  8084. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  8085. // project all 3 vertices of the triangle onto the separating axis
  8086. const p0 = v0.dot( _testAxis );
  8087. const p1 = v1.dot( _testAxis );
  8088. const p2 = v2.dot( _testAxis );
  8089. // actual test, basically see if either of the most extreme of the triangle points intersects r
  8090. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  8091. // points of the projected triangle are outside the projected half-length of the aabb
  8092. // the axis is separating and we can exit
  8093. return false;
  8094. }
  8095. }
  8096. return true;
  8097. }
  8098. const _box$3 = /*@__PURE__*/ new Box3();
  8099. const _v1$6 = /*@__PURE__*/ new Vector3();
  8100. const _v2$3 = /*@__PURE__*/ new Vector3();
  8101. /**
  8102. * An analytical 3D sphere defined by a center and radius. This class is mainly
  8103. * used as a Bounding Sphere for 3D objects.
  8104. */
  8105. class Sphere {
  8106. /**
  8107. * Constructs a new sphere.
  8108. *
  8109. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  8110. * @param {number} [radius=-1] - The radius of the sphere.
  8111. */
  8112. constructor( center = new Vector3(), radius = -1 ) {
  8113. /**
  8114. * This flag can be used for type testing.
  8115. *
  8116. * @type {boolean}
  8117. * @readonly
  8118. * @default true
  8119. */
  8120. this.isSphere = true;
  8121. /**
  8122. * The center of the sphere
  8123. *
  8124. * @type {Vector3}
  8125. */
  8126. this.center = center;
  8127. /**
  8128. * The radius of the sphere.
  8129. *
  8130. * @type {number}
  8131. */
  8132. this.radius = radius;
  8133. }
  8134. /**
  8135. * Sets the sphere's components by copying the given values.
  8136. *
  8137. * @param {Vector3} center - The center.
  8138. * @param {number} radius - The radius.
  8139. * @return {Sphere} A reference to this sphere.
  8140. */
  8141. set( center, radius ) {
  8142. this.center.copy( center );
  8143. this.radius = radius;
  8144. return this;
  8145. }
  8146. /**
  8147. * Computes the minimum bounding sphere for list of points.
  8148. * If the optional center point is given, it is used as the sphere's
  8149. * center. Otherwise, the center of the axis-aligned bounding box
  8150. * encompassing the points is calculated.
  8151. *
  8152. * @param {Array<Vector3>} points - A list of points in 3D space.
  8153. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8154. * @return {Sphere} A reference to this sphere.
  8155. */
  8156. setFromPoints( points, optionalCenter ) {
  8157. const center = this.center;
  8158. if ( optionalCenter !== undefined ) {
  8159. center.copy( optionalCenter );
  8160. } else {
  8161. _box$3.setFromPoints( points ).getCenter( center );
  8162. }
  8163. let maxRadiusSq = 0;
  8164. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8165. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8166. }
  8167. this.radius = Math.sqrt( maxRadiusSq );
  8168. return this;
  8169. }
  8170. /**
  8171. * Copies the values of the given sphere to this instance.
  8172. *
  8173. * @param {Sphere} sphere - The sphere to copy.
  8174. * @return {Sphere} A reference to this sphere.
  8175. */
  8176. copy( sphere ) {
  8177. this.center.copy( sphere.center );
  8178. this.radius = sphere.radius;
  8179. return this;
  8180. }
  8181. /**
  8182. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8183. *
  8184. * Spheres with a radius of `0` contain only their center point and are not
  8185. * considered to be empty.
  8186. *
  8187. * @return {boolean} Whether this sphere is empty or not.
  8188. */
  8189. isEmpty() {
  8190. return ( this.radius < 0 );
  8191. }
  8192. /**
  8193. * Makes this sphere empty which means in encloses a zero space in 3D.
  8194. *
  8195. * @return {Sphere} A reference to this sphere.
  8196. */
  8197. makeEmpty() {
  8198. this.center.set( 0, 0, 0 );
  8199. this.radius = -1;
  8200. return this;
  8201. }
  8202. /**
  8203. * Returns `true` if this sphere contains the given point inclusive of
  8204. * the surface of the sphere.
  8205. *
  8206. * @param {Vector3} point - The point to check.
  8207. * @return {boolean} Whether this sphere contains the given point or not.
  8208. */
  8209. containsPoint( point ) {
  8210. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8211. }
  8212. /**
  8213. * Returns the closest distance from the boundary of the sphere to the
  8214. * given point. If the sphere contains the point, the distance will
  8215. * be negative.
  8216. *
  8217. * @param {Vector3} point - The point to compute the distance to.
  8218. * @return {number} The distance to the point.
  8219. */
  8220. distanceToPoint( point ) {
  8221. return ( point.distanceTo( this.center ) - this.radius );
  8222. }
  8223. /**
  8224. * Returns `true` if this sphere intersects with the given one.
  8225. *
  8226. * @param {Sphere} sphere - The sphere to test.
  8227. * @return {boolean} Whether this sphere intersects with the given one or not.
  8228. */
  8229. intersectsSphere( sphere ) {
  8230. const radiusSum = this.radius + sphere.radius;
  8231. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8232. }
  8233. /**
  8234. * Returns `true` if this sphere intersects with the given box.
  8235. *
  8236. * @param {Box3} box - The box to test.
  8237. * @return {boolean} Whether this sphere intersects with the given box or not.
  8238. */
  8239. intersectsBox( box ) {
  8240. return box.intersectsSphere( this );
  8241. }
  8242. /**
  8243. * Returns `true` if this sphere intersects with the given plane.
  8244. *
  8245. * @param {Plane} plane - The plane to test.
  8246. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8247. */
  8248. intersectsPlane( plane ) {
  8249. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8250. }
  8251. /**
  8252. * Clamps a point within the sphere. If the point is outside the sphere, it
  8253. * will clamp it to the closest point on the edge of the sphere. Points
  8254. * already inside the sphere will not be affected.
  8255. *
  8256. * @param {Vector3} point - The plane to clamp.
  8257. * @param {Vector3} target - The target vector that is used to store the method's result.
  8258. * @return {Vector3} The clamped point.
  8259. */
  8260. clampPoint( point, target ) {
  8261. const deltaLengthSq = this.center.distanceToSquared( point );
  8262. target.copy( point );
  8263. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8264. target.sub( this.center ).normalize();
  8265. target.multiplyScalar( this.radius ).add( this.center );
  8266. }
  8267. return target;
  8268. }
  8269. /**
  8270. * Returns a bounding box that encloses this sphere.
  8271. *
  8272. * @param {Box3} target - The target box that is used to store the method's result.
  8273. * @return {Box3} The bounding box that encloses this sphere.
  8274. */
  8275. getBoundingBox( target ) {
  8276. if ( this.isEmpty() ) {
  8277. // Empty sphere produces empty bounding box
  8278. target.makeEmpty();
  8279. return target;
  8280. }
  8281. target.set( this.center, this.center );
  8282. target.expandByScalar( this.radius );
  8283. return target;
  8284. }
  8285. /**
  8286. * Transforms this sphere with the given 4x4 transformation matrix.
  8287. *
  8288. * @param {Matrix4} matrix - The transformation matrix.
  8289. * @return {Sphere} A reference to this sphere.
  8290. */
  8291. applyMatrix4( matrix ) {
  8292. this.center.applyMatrix4( matrix );
  8293. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8294. return this;
  8295. }
  8296. /**
  8297. * Translates the sphere's center by the given offset.
  8298. *
  8299. * @param {Vector3} offset - The offset.
  8300. * @return {Sphere} A reference to this sphere.
  8301. */
  8302. translate( offset ) {
  8303. this.center.add( offset );
  8304. return this;
  8305. }
  8306. /**
  8307. * Expands the boundaries of this sphere to include the given point.
  8308. *
  8309. * @param {Vector3} point - The point to include.
  8310. * @return {Sphere} A reference to this sphere.
  8311. */
  8312. expandByPoint( point ) {
  8313. if ( this.isEmpty() ) {
  8314. this.center.copy( point );
  8315. this.radius = 0;
  8316. return this;
  8317. }
  8318. _v1$6.subVectors( point, this.center );
  8319. const lengthSq = _v1$6.lengthSq();
  8320. if ( lengthSq > ( this.radius * this.radius ) ) {
  8321. // calculate the minimal sphere
  8322. const length = Math.sqrt( lengthSq );
  8323. const delta = ( length - this.radius ) * 0.5;
  8324. this.center.addScaledVector( _v1$6, delta / length );
  8325. this.radius += delta;
  8326. }
  8327. return this;
  8328. }
  8329. /**
  8330. * Expands this sphere to enclose both the original sphere and the given sphere.
  8331. *
  8332. * @param {Sphere} sphere - The sphere to include.
  8333. * @return {Sphere} A reference to this sphere.
  8334. */
  8335. union( sphere ) {
  8336. if ( sphere.isEmpty() ) {
  8337. return this;
  8338. }
  8339. if ( this.isEmpty() ) {
  8340. this.copy( sphere );
  8341. return this;
  8342. }
  8343. if ( this.center.equals( sphere.center ) === true ) {
  8344. this.radius = Math.max( this.radius, sphere.radius );
  8345. } else {
  8346. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8347. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8348. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8349. }
  8350. return this;
  8351. }
  8352. /**
  8353. * Returns `true` if this sphere is equal with the given one.
  8354. *
  8355. * @param {Sphere} sphere - The sphere to test for equality.
  8356. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8357. */
  8358. equals( sphere ) {
  8359. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8360. }
  8361. /**
  8362. * Returns a new sphere with copied values from this instance.
  8363. *
  8364. * @return {Sphere} A clone of this instance.
  8365. */
  8366. clone() {
  8367. return new this.constructor().copy( this );
  8368. }
  8369. /**
  8370. * Returns a serialized structure of the bounding sphere.
  8371. *
  8372. * @return {Object} Serialized structure with fields representing the object state.
  8373. */
  8374. toJSON() {
  8375. return {
  8376. radius: this.radius,
  8377. center: this.center.toArray()
  8378. };
  8379. }
  8380. /**
  8381. * Returns a serialized structure of the bounding sphere.
  8382. *
  8383. * @param {Object} json - The serialized json to set the sphere from.
  8384. * @return {Sphere} A reference to this bounding sphere.
  8385. */
  8386. fromJSON( json ) {
  8387. this.radius = json.radius;
  8388. this.center.fromArray( json.center );
  8389. return this;
  8390. }
  8391. }
  8392. const _vector$a = /*@__PURE__*/ new Vector3();
  8393. const _segCenter = /*@__PURE__*/ new Vector3();
  8394. const _segDir = /*@__PURE__*/ new Vector3();
  8395. const _diff = /*@__PURE__*/ new Vector3();
  8396. const _edge1 = /*@__PURE__*/ new Vector3();
  8397. const _edge2 = /*@__PURE__*/ new Vector3();
  8398. const _normal$1 = /*@__PURE__*/ new Vector3();
  8399. /**
  8400. * A ray that emits from an origin in a certain direction. The class is used by
  8401. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8402. * mouse picking (working out what objects in the 3D space the mouse is over)
  8403. * amongst other things.
  8404. */
  8405. class Ray {
  8406. /**
  8407. * Constructs a new ray.
  8408. *
  8409. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8410. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8411. */
  8412. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8413. /**
  8414. * The origin of the ray.
  8415. *
  8416. * @type {Vector3}
  8417. */
  8418. this.origin = origin;
  8419. /**
  8420. * The (normalized) direction of the ray.
  8421. *
  8422. * @type {Vector3}
  8423. */
  8424. this.direction = direction;
  8425. }
  8426. /**
  8427. * Sets the ray's components by copying the given values.
  8428. *
  8429. * @param {Vector3} origin - The origin.
  8430. * @param {Vector3} direction - The direction.
  8431. * @return {Ray} A reference to this ray.
  8432. */
  8433. set( origin, direction ) {
  8434. this.origin.copy( origin );
  8435. this.direction.copy( direction );
  8436. return this;
  8437. }
  8438. /**
  8439. * Copies the values of the given ray to this instance.
  8440. *
  8441. * @param {Ray} ray - The ray to copy.
  8442. * @return {Ray} A reference to this ray.
  8443. */
  8444. copy( ray ) {
  8445. this.origin.copy( ray.origin );
  8446. this.direction.copy( ray.direction );
  8447. return this;
  8448. }
  8449. /**
  8450. * Returns a vector that is located at a given distance along this ray.
  8451. *
  8452. * @param {number} t - The distance along the ray to retrieve a position for.
  8453. * @param {Vector3} target - The target vector that is used to store the method's result.
  8454. * @return {Vector3} A position on the ray.
  8455. */
  8456. at( t, target ) {
  8457. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8458. }
  8459. /**
  8460. * Adjusts the direction of the ray to point at the given vector in world space.
  8461. *
  8462. * @param {Vector3} v - The target position.
  8463. * @return {Ray} A reference to this ray.
  8464. */
  8465. lookAt( v ) {
  8466. this.direction.copy( v ).sub( this.origin ).normalize();
  8467. return this;
  8468. }
  8469. /**
  8470. * Shift the origin of this ray along its direction by the given distance.
  8471. *
  8472. * @param {number} t - The distance along the ray to interpolate.
  8473. * @return {Ray} A reference to this ray.
  8474. */
  8475. recast( t ) {
  8476. this.origin.copy( this.at( t, _vector$a ) );
  8477. return this;
  8478. }
  8479. /**
  8480. * Returns the point along this ray that is closest to the given point.
  8481. *
  8482. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8483. * @param {Vector3} target - The target vector that is used to store the method's result.
  8484. * @return {Vector3} The closest point on this ray.
  8485. */
  8486. closestPointToPoint( point, target ) {
  8487. target.subVectors( point, this.origin );
  8488. const directionDistance = target.dot( this.direction );
  8489. if ( directionDistance < 0 ) {
  8490. return target.copy( this.origin );
  8491. }
  8492. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8493. }
  8494. /**
  8495. * Returns the distance of the closest approach between this ray and the given point.
  8496. *
  8497. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8498. * @return {number} The distance.
  8499. */
  8500. distanceToPoint( point ) {
  8501. return Math.sqrt( this.distanceSqToPoint( point ) );
  8502. }
  8503. /**
  8504. * Returns the squared distance of the closest approach between this ray and the given point.
  8505. *
  8506. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8507. * @return {number} The squared distance.
  8508. */
  8509. distanceSqToPoint( point ) {
  8510. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8511. // point behind the ray
  8512. if ( directionDistance < 0 ) {
  8513. return this.origin.distanceToSquared( point );
  8514. }
  8515. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8516. return _vector$a.distanceToSquared( point );
  8517. }
  8518. /**
  8519. * Returns the squared distance between this ray and the given line segment.
  8520. *
  8521. * @param {Vector3} v0 - The start point of the line segment.
  8522. * @param {Vector3} v1 - The end point of the line segment.
  8523. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8524. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8525. * @return {number} The squared distance.
  8526. */
  8527. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8528. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8529. // It returns the min distance between the ray and the segment
  8530. // defined by v0 and v1
  8531. // It can also set two optional targets :
  8532. // - The closest point on the ray
  8533. // - The closest point on the segment
  8534. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8535. _segDir.copy( v1 ).sub( v0 ).normalize();
  8536. _diff.copy( this.origin ).sub( _segCenter );
  8537. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8538. const a01 = - this.direction.dot( _segDir );
  8539. const b0 = _diff.dot( this.direction );
  8540. const b1 = - _diff.dot( _segDir );
  8541. const c = _diff.lengthSq();
  8542. const det = Math.abs( 1 - a01 * a01 );
  8543. let s0, s1, sqrDist, extDet;
  8544. if ( det > 0 ) {
  8545. // The ray and segment are not parallel.
  8546. s0 = a01 * b1 - b0;
  8547. s1 = a01 * b0 - b1;
  8548. extDet = segExtent * det;
  8549. if ( s0 >= 0 ) {
  8550. if ( s1 >= - extDet ) {
  8551. if ( s1 <= extDet ) {
  8552. // region 0
  8553. // Minimum at interior points of ray and segment.
  8554. const invDet = 1 / det;
  8555. s0 *= invDet;
  8556. s1 *= invDet;
  8557. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8558. } else {
  8559. // region 1
  8560. s1 = segExtent;
  8561. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8562. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8563. }
  8564. } else {
  8565. // region 5
  8566. s1 = - segExtent;
  8567. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8568. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8569. }
  8570. } else {
  8571. if ( s1 <= - extDet ) {
  8572. // region 4
  8573. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8574. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8575. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8576. } else if ( s1 <= extDet ) {
  8577. // region 3
  8578. s0 = 0;
  8579. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8580. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8581. } else {
  8582. // region 2
  8583. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8584. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8585. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8586. }
  8587. }
  8588. } else {
  8589. // Ray and segment are parallel.
  8590. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8591. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8592. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8593. }
  8594. if ( optionalPointOnRay ) {
  8595. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8596. }
  8597. if ( optionalPointOnSegment ) {
  8598. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8599. }
  8600. return sqrDist;
  8601. }
  8602. /**
  8603. * Intersects this ray with the given sphere, returning the intersection
  8604. * point or `null` if there is no intersection.
  8605. *
  8606. * @param {Sphere} sphere - The sphere to intersect.
  8607. * @param {Vector3} target - The target vector that is used to store the method's result.
  8608. * @return {?Vector3} The intersection point.
  8609. */
  8610. intersectSphere( sphere, target ) {
  8611. _vector$a.subVectors( sphere.center, this.origin );
  8612. const tca = _vector$a.dot( this.direction );
  8613. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8614. const radius2 = sphere.radius * sphere.radius;
  8615. if ( d2 > radius2 ) return null;
  8616. const thc = Math.sqrt( radius2 - d2 );
  8617. // t0 = first intersect point - entrance on front of sphere
  8618. const t0 = tca - thc;
  8619. // t1 = second intersect point - exit point on back of sphere
  8620. const t1 = tca + thc;
  8621. // test to see if t1 is behind the ray - if so, return null
  8622. if ( t1 < 0 ) return null;
  8623. // test to see if t0 is behind the ray:
  8624. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8625. // in order to always return an intersect point that is in front of the ray.
  8626. if ( t0 < 0 ) return this.at( t1, target );
  8627. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8628. return this.at( t0, target );
  8629. }
  8630. /**
  8631. * Returns `true` if this ray intersects with the given sphere.
  8632. *
  8633. * @param {Sphere} sphere - The sphere to intersect.
  8634. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8635. */
  8636. intersectsSphere( sphere ) {
  8637. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8638. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8639. }
  8640. /**
  8641. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8642. * does not intersect with the plane.
  8643. *
  8644. * @param {Plane} plane - The plane to compute the distance to.
  8645. * @return {?number} Whether this ray intersects with the given sphere or not.
  8646. */
  8647. distanceToPlane( plane ) {
  8648. const denominator = plane.normal.dot( this.direction );
  8649. if ( denominator === 0 ) {
  8650. // line is coplanar, return origin
  8651. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8652. return 0;
  8653. }
  8654. // Null is preferable to undefined since undefined means.... it is undefined
  8655. return null;
  8656. }
  8657. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8658. // Return if the ray never intersects the plane
  8659. return t >= 0 ? t : null;
  8660. }
  8661. /**
  8662. * Intersects this ray with the given plane, returning the intersection
  8663. * point or `null` if there is no intersection.
  8664. *
  8665. * @param {Plane} plane - The plane to intersect.
  8666. * @param {Vector3} target - The target vector that is used to store the method's result.
  8667. * @return {?Vector3} The intersection point.
  8668. */
  8669. intersectPlane( plane, target ) {
  8670. const t = this.distanceToPlane( plane );
  8671. if ( t === null ) {
  8672. return null;
  8673. }
  8674. return this.at( t, target );
  8675. }
  8676. /**
  8677. * Returns `true` if this ray intersects with the given plane.
  8678. *
  8679. * @param {Plane} plane - The plane to intersect.
  8680. * @return {boolean} Whether this ray intersects with the given plane or not.
  8681. */
  8682. intersectsPlane( plane ) {
  8683. // check if the ray lies on the plane first
  8684. const distToPoint = plane.distanceToPoint( this.origin );
  8685. if ( distToPoint === 0 ) {
  8686. return true;
  8687. }
  8688. const denominator = plane.normal.dot( this.direction );
  8689. if ( denominator * distToPoint < 0 ) {
  8690. return true;
  8691. }
  8692. // ray origin is behind the plane (and is pointing behind it)
  8693. return false;
  8694. }
  8695. /**
  8696. * Intersects this ray with the given bounding box, returning the intersection
  8697. * point or `null` if there is no intersection.
  8698. *
  8699. * @param {Box3} box - The box to intersect.
  8700. * @param {Vector3} target - The target vector that is used to store the method's result.
  8701. * @return {?Vector3} The intersection point.
  8702. */
  8703. intersectBox( box, target ) {
  8704. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8705. const invdirx = 1 / this.direction.x,
  8706. invdiry = 1 / this.direction.y,
  8707. invdirz = 1 / this.direction.z;
  8708. const origin = this.origin;
  8709. if ( invdirx >= 0 ) {
  8710. tmin = ( box.min.x - origin.x ) * invdirx;
  8711. tmax = ( box.max.x - origin.x ) * invdirx;
  8712. } else {
  8713. tmin = ( box.max.x - origin.x ) * invdirx;
  8714. tmax = ( box.min.x - origin.x ) * invdirx;
  8715. }
  8716. if ( invdiry >= 0 ) {
  8717. tymin = ( box.min.y - origin.y ) * invdiry;
  8718. tymax = ( box.max.y - origin.y ) * invdiry;
  8719. } else {
  8720. tymin = ( box.max.y - origin.y ) * invdiry;
  8721. tymax = ( box.min.y - origin.y ) * invdiry;
  8722. }
  8723. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8724. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8725. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8726. if ( invdirz >= 0 ) {
  8727. tzmin = ( box.min.z - origin.z ) * invdirz;
  8728. tzmax = ( box.max.z - origin.z ) * invdirz;
  8729. } else {
  8730. tzmin = ( box.max.z - origin.z ) * invdirz;
  8731. tzmax = ( box.min.z - origin.z ) * invdirz;
  8732. }
  8733. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8734. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8735. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8736. //return point closest to the ray (positive side)
  8737. if ( tmax < 0 ) return null;
  8738. return this.at( tmin >= 0 ? tmin : tmax, target );
  8739. }
  8740. /**
  8741. * Returns `true` if this ray intersects with the given box.
  8742. *
  8743. * @param {Box3} box - The box to intersect.
  8744. * @return {boolean} Whether this ray intersects with the given box or not.
  8745. */
  8746. intersectsBox( box ) {
  8747. return this.intersectBox( box, _vector$a ) !== null;
  8748. }
  8749. /**
  8750. * Intersects this ray with the given triangle, returning the intersection
  8751. * point or `null` if there is no intersection.
  8752. *
  8753. * @param {Vector3} a - The first vertex of the triangle.
  8754. * @param {Vector3} b - The second vertex of the triangle.
  8755. * @param {Vector3} c - The third vertex of the triangle.
  8756. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8757. * @param {Vector3} target - The target vector that is used to store the method's result.
  8758. * @return {?Vector3} The intersection point.
  8759. */
  8760. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8761. // Compute the offset origin, edges, and normal.
  8762. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8763. _edge1.subVectors( b, a );
  8764. _edge2.subVectors( c, a );
  8765. _normal$1.crossVectors( _edge1, _edge2 );
  8766. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8767. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8768. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8769. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8770. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8771. let DdN = this.direction.dot( _normal$1 );
  8772. let sign;
  8773. if ( DdN > 0 ) {
  8774. if ( backfaceCulling ) return null;
  8775. sign = 1;
  8776. } else if ( DdN < 0 ) {
  8777. sign = -1;
  8778. DdN = - DdN;
  8779. } else {
  8780. return null;
  8781. }
  8782. _diff.subVectors( this.origin, a );
  8783. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8784. // b1 < 0, no intersection
  8785. if ( DdQxE2 < 0 ) {
  8786. return null;
  8787. }
  8788. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8789. // b2 < 0, no intersection
  8790. if ( DdE1xQ < 0 ) {
  8791. return null;
  8792. }
  8793. // b1+b2 > 1, no intersection
  8794. if ( DdQxE2 + DdE1xQ > DdN ) {
  8795. return null;
  8796. }
  8797. // Line intersects triangle, check if ray does.
  8798. const QdN = - sign * _diff.dot( _normal$1 );
  8799. // t < 0, no intersection
  8800. if ( QdN < 0 ) {
  8801. return null;
  8802. }
  8803. // Ray intersects triangle.
  8804. return this.at( QdN / DdN, target );
  8805. }
  8806. /**
  8807. * Transforms this ray with the given 4x4 transformation matrix.
  8808. *
  8809. * @param {Matrix4} matrix4 - The transformation matrix.
  8810. * @return {Ray} A reference to this ray.
  8811. */
  8812. applyMatrix4( matrix4 ) {
  8813. this.origin.applyMatrix4( matrix4 );
  8814. this.direction.transformDirection( matrix4 );
  8815. return this;
  8816. }
  8817. /**
  8818. * Returns `true` if this ray is equal with the given one.
  8819. *
  8820. * @param {Ray} ray - The ray to test for equality.
  8821. * @return {boolean} Whether this ray is equal with the given one.
  8822. */
  8823. equals( ray ) {
  8824. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8825. }
  8826. /**
  8827. * Returns a new ray with copied values from this instance.
  8828. *
  8829. * @return {Ray} A clone of this instance.
  8830. */
  8831. clone() {
  8832. return new this.constructor().copy( this );
  8833. }
  8834. }
  8835. /**
  8836. * Represents a 4x4 matrix.
  8837. *
  8838. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8839. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8840. *
  8841. * This allows a 3D vector representing a point in 3D space to undergo
  8842. * transformations such as translation, rotation, shear, scale, reflection,
  8843. * orthogonal or perspective projection and so on, by being multiplied by the
  8844. * matrix. This is known as `applying` the matrix to the vector.
  8845. *
  8846. * A Note on Row-Major and Column-Major Ordering:
  8847. *
  8848. * The constructor and {@link Matrix3#set} method take arguments in
  8849. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8850. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8851. * This means that calling:
  8852. * ```js
  8853. * const m = new THREE.Matrix4();
  8854. * m.set( 11, 12, 13, 14,
  8855. * 21, 22, 23, 24,
  8856. * 31, 32, 33, 34,
  8857. * 41, 42, 43, 44 );
  8858. * ```
  8859. * will result in the elements array containing:
  8860. * ```js
  8861. * m.elements = [ 11, 21, 31, 41,
  8862. * 12, 22, 32, 42,
  8863. * 13, 23, 33, 43,
  8864. * 14, 24, 34, 44 ];
  8865. * ```
  8866. * and internally all calculations are performed using column-major ordering.
  8867. * However, as the actual ordering makes no difference mathematically and
  8868. * most people are used to thinking about matrices in row-major order, the
  8869. * three.js documentation shows matrices in row-major order. Just bear in
  8870. * mind that if you are reading the source code, you'll have to take the
  8871. * transpose of any matrices outlined here to make sense of the calculations.
  8872. */
  8873. class Matrix4 {
  8874. /**
  8875. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8876. * in row-major order. If no arguments are provided, the constructor
  8877. * initializes the matrix as an identity matrix.
  8878. *
  8879. * @param {number} [n11] - 1-1 matrix element.
  8880. * @param {number} [n12] - 1-2 matrix element.
  8881. * @param {number} [n13] - 1-3 matrix element.
  8882. * @param {number} [n14] - 1-4 matrix element.
  8883. * @param {number} [n21] - 2-1 matrix element.
  8884. * @param {number} [n22] - 2-2 matrix element.
  8885. * @param {number} [n23] - 2-3 matrix element.
  8886. * @param {number} [n24] - 2-4 matrix element.
  8887. * @param {number} [n31] - 3-1 matrix element.
  8888. * @param {number} [n32] - 3-2 matrix element.
  8889. * @param {number} [n33] - 3-3 matrix element.
  8890. * @param {number} [n34] - 3-4 matrix element.
  8891. * @param {number} [n41] - 4-1 matrix element.
  8892. * @param {number} [n42] - 4-2 matrix element.
  8893. * @param {number} [n43] - 4-3 matrix element.
  8894. * @param {number} [n44] - 4-4 matrix element.
  8895. */
  8896. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8897. /**
  8898. * This flag can be used for type testing.
  8899. *
  8900. * @type {boolean}
  8901. * @readonly
  8902. * @default true
  8903. */
  8904. Matrix4.prototype.isMatrix4 = true;
  8905. /**
  8906. * A column-major list of matrix values.
  8907. *
  8908. * @type {Array<number>}
  8909. */
  8910. this.elements = [
  8911. 1, 0, 0, 0,
  8912. 0, 1, 0, 0,
  8913. 0, 0, 1, 0,
  8914. 0, 0, 0, 1
  8915. ];
  8916. if ( n11 !== undefined ) {
  8917. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8918. }
  8919. }
  8920. /**
  8921. * Sets the elements of the matrix.The arguments are supposed to be
  8922. * in row-major order.
  8923. *
  8924. * @param {number} [n11] - 1-1 matrix element.
  8925. * @param {number} [n12] - 1-2 matrix element.
  8926. * @param {number} [n13] - 1-3 matrix element.
  8927. * @param {number} [n14] - 1-4 matrix element.
  8928. * @param {number} [n21] - 2-1 matrix element.
  8929. * @param {number} [n22] - 2-2 matrix element.
  8930. * @param {number} [n23] - 2-3 matrix element.
  8931. * @param {number} [n24] - 2-4 matrix element.
  8932. * @param {number} [n31] - 3-1 matrix element.
  8933. * @param {number} [n32] - 3-2 matrix element.
  8934. * @param {number} [n33] - 3-3 matrix element.
  8935. * @param {number} [n34] - 3-4 matrix element.
  8936. * @param {number} [n41] - 4-1 matrix element.
  8937. * @param {number} [n42] - 4-2 matrix element.
  8938. * @param {number} [n43] - 4-3 matrix element.
  8939. * @param {number} [n44] - 4-4 matrix element.
  8940. * @return {Matrix4} A reference to this matrix.
  8941. */
  8942. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8943. const te = this.elements;
  8944. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8945. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8946. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8947. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8948. return this;
  8949. }
  8950. /**
  8951. * Sets this matrix to the 4x4 identity matrix.
  8952. *
  8953. * @return {Matrix4} A reference to this matrix.
  8954. */
  8955. identity() {
  8956. this.set(
  8957. 1, 0, 0, 0,
  8958. 0, 1, 0, 0,
  8959. 0, 0, 1, 0,
  8960. 0, 0, 0, 1
  8961. );
  8962. return this;
  8963. }
  8964. /**
  8965. * Returns a matrix with copied values from this instance.
  8966. *
  8967. * @return {Matrix4} A clone of this instance.
  8968. */
  8969. clone() {
  8970. return new Matrix4().fromArray( this.elements );
  8971. }
  8972. /**
  8973. * Copies the values of the given matrix to this instance.
  8974. *
  8975. * @param {Matrix4} m - The matrix to copy.
  8976. * @return {Matrix4} A reference to this matrix.
  8977. */
  8978. copy( m ) {
  8979. const te = this.elements;
  8980. const me = m.elements;
  8981. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8982. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8983. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8984. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8985. return this;
  8986. }
  8987. /**
  8988. * Copies the translation component of the given matrix
  8989. * into this matrix's translation component.
  8990. *
  8991. * @param {Matrix4} m - The matrix to copy the translation component.
  8992. * @return {Matrix4} A reference to this matrix.
  8993. */
  8994. copyPosition( m ) {
  8995. const te = this.elements, me = m.elements;
  8996. te[ 12 ] = me[ 12 ];
  8997. te[ 13 ] = me[ 13 ];
  8998. te[ 14 ] = me[ 14 ];
  8999. return this;
  9000. }
  9001. /**
  9002. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  9003. *
  9004. * @param {Matrix3} m - The 3x3 matrix.
  9005. * @return {Matrix4} A reference to this matrix.
  9006. */
  9007. setFromMatrix3( m ) {
  9008. const me = m.elements;
  9009. this.set(
  9010. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  9011. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  9012. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  9013. 0, 0, 0, 1
  9014. );
  9015. return this;
  9016. }
  9017. /**
  9018. * Extracts the basis of this matrix into the three axis vectors provided.
  9019. *
  9020. * @param {Vector3} xAxis - The basis's x axis.
  9021. * @param {Vector3} yAxis - The basis's y axis.
  9022. * @param {Vector3} zAxis - The basis's z axis.
  9023. * @return {Matrix4} A reference to this matrix.
  9024. */
  9025. extractBasis( xAxis, yAxis, zAxis ) {
  9026. if ( this.determinant() === 0 ) {
  9027. xAxis.set( 1, 0, 0 );
  9028. yAxis.set( 0, 1, 0 );
  9029. zAxis.set( 0, 0, 1 );
  9030. return this;
  9031. }
  9032. xAxis.setFromMatrixColumn( this, 0 );
  9033. yAxis.setFromMatrixColumn( this, 1 );
  9034. zAxis.setFromMatrixColumn( this, 2 );
  9035. return this;
  9036. }
  9037. /**
  9038. * Sets the given basis vectors to this matrix.
  9039. *
  9040. * @param {Vector3} xAxis - The basis's x axis.
  9041. * @param {Vector3} yAxis - The basis's y axis.
  9042. * @param {Vector3} zAxis - The basis's z axis.
  9043. * @return {Matrix4} A reference to this matrix.
  9044. */
  9045. makeBasis( xAxis, yAxis, zAxis ) {
  9046. this.set(
  9047. xAxis.x, yAxis.x, zAxis.x, 0,
  9048. xAxis.y, yAxis.y, zAxis.y, 0,
  9049. xAxis.z, yAxis.z, zAxis.z, 0,
  9050. 0, 0, 0, 1
  9051. );
  9052. return this;
  9053. }
  9054. /**
  9055. * Extracts the rotation component of the given matrix
  9056. * into this matrix's rotation component.
  9057. *
  9058. * Note: This method does not support reflection matrices.
  9059. *
  9060. * @param {Matrix4} m - The matrix.
  9061. * @return {Matrix4} A reference to this matrix.
  9062. */
  9063. extractRotation( m ) {
  9064. if ( m.determinant() === 0 ) {
  9065. return this.identity();
  9066. }
  9067. const te = this.elements;
  9068. const me = m.elements;
  9069. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  9070. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  9071. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  9072. te[ 0 ] = me[ 0 ] * scaleX;
  9073. te[ 1 ] = me[ 1 ] * scaleX;
  9074. te[ 2 ] = me[ 2 ] * scaleX;
  9075. te[ 3 ] = 0;
  9076. te[ 4 ] = me[ 4 ] * scaleY;
  9077. te[ 5 ] = me[ 5 ] * scaleY;
  9078. te[ 6 ] = me[ 6 ] * scaleY;
  9079. te[ 7 ] = 0;
  9080. te[ 8 ] = me[ 8 ] * scaleZ;
  9081. te[ 9 ] = me[ 9 ] * scaleZ;
  9082. te[ 10 ] = me[ 10 ] * scaleZ;
  9083. te[ 11 ] = 0;
  9084. te[ 12 ] = 0;
  9085. te[ 13 ] = 0;
  9086. te[ 14 ] = 0;
  9087. te[ 15 ] = 1;
  9088. return this;
  9089. }
  9090. /**
  9091. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  9092. * the rotation specified by the given Euler angles. The rest of
  9093. * the matrix is set to the identity. Depending on the {@link Euler#order},
  9094. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  9095. * for a complete list.
  9096. *
  9097. * @param {Euler} euler - The Euler angles.
  9098. * @return {Matrix4} A reference to this matrix.
  9099. */
  9100. makeRotationFromEuler( euler ) {
  9101. const te = this.elements;
  9102. const x = euler.x, y = euler.y, z = euler.z;
  9103. const a = Math.cos( x ), b = Math.sin( x );
  9104. const c = Math.cos( y ), d = Math.sin( y );
  9105. const e = Math.cos( z ), f = Math.sin( z );
  9106. if ( euler.order === 'XYZ' ) {
  9107. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9108. te[ 0 ] = c * e;
  9109. te[ 4 ] = - c * f;
  9110. te[ 8 ] = d;
  9111. te[ 1 ] = af + be * d;
  9112. te[ 5 ] = ae - bf * d;
  9113. te[ 9 ] = - b * c;
  9114. te[ 2 ] = bf - ae * d;
  9115. te[ 6 ] = be + af * d;
  9116. te[ 10 ] = a * c;
  9117. } else if ( euler.order === 'YXZ' ) {
  9118. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9119. te[ 0 ] = ce + df * b;
  9120. te[ 4 ] = de * b - cf;
  9121. te[ 8 ] = a * d;
  9122. te[ 1 ] = a * f;
  9123. te[ 5 ] = a * e;
  9124. te[ 9 ] = - b;
  9125. te[ 2 ] = cf * b - de;
  9126. te[ 6 ] = df + ce * b;
  9127. te[ 10 ] = a * c;
  9128. } else if ( euler.order === 'ZXY' ) {
  9129. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  9130. te[ 0 ] = ce - df * b;
  9131. te[ 4 ] = - a * f;
  9132. te[ 8 ] = de + cf * b;
  9133. te[ 1 ] = cf + de * b;
  9134. te[ 5 ] = a * e;
  9135. te[ 9 ] = df - ce * b;
  9136. te[ 2 ] = - a * d;
  9137. te[ 6 ] = b;
  9138. te[ 10 ] = a * c;
  9139. } else if ( euler.order === 'ZYX' ) {
  9140. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9141. te[ 0 ] = c * e;
  9142. te[ 4 ] = be * d - af;
  9143. te[ 8 ] = ae * d + bf;
  9144. te[ 1 ] = c * f;
  9145. te[ 5 ] = bf * d + ae;
  9146. te[ 9 ] = af * d - be;
  9147. te[ 2 ] = - d;
  9148. te[ 6 ] = b * c;
  9149. te[ 10 ] = a * c;
  9150. } else if ( euler.order === 'YZX' ) {
  9151. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9152. te[ 0 ] = c * e;
  9153. te[ 4 ] = bd - ac * f;
  9154. te[ 8 ] = bc * f + ad;
  9155. te[ 1 ] = f;
  9156. te[ 5 ] = a * e;
  9157. te[ 9 ] = - b * e;
  9158. te[ 2 ] = - d * e;
  9159. te[ 6 ] = ad * f + bc;
  9160. te[ 10 ] = ac - bd * f;
  9161. } else if ( euler.order === 'XZY' ) {
  9162. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9163. te[ 0 ] = c * e;
  9164. te[ 4 ] = - f;
  9165. te[ 8 ] = d * e;
  9166. te[ 1 ] = ac * f + bd;
  9167. te[ 5 ] = a * e;
  9168. te[ 9 ] = ad * f - bc;
  9169. te[ 2 ] = bc * f - ad;
  9170. te[ 6 ] = b * e;
  9171. te[ 10 ] = bd * f + ac;
  9172. }
  9173. // bottom row
  9174. te[ 3 ] = 0;
  9175. te[ 7 ] = 0;
  9176. te[ 11 ] = 0;
  9177. // last column
  9178. te[ 12 ] = 0;
  9179. te[ 13 ] = 0;
  9180. te[ 14 ] = 0;
  9181. te[ 15 ] = 1;
  9182. return this;
  9183. }
  9184. /**
  9185. * Sets the rotation component of this matrix to the rotation specified by
  9186. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9187. * The rest of the matrix is set to the identity.
  9188. *
  9189. * @param {Quaternion} q - The Quaternion.
  9190. * @return {Matrix4} A reference to this matrix.
  9191. */
  9192. makeRotationFromQuaternion( q ) {
  9193. return this.compose( _zero, q, _one );
  9194. }
  9195. /**
  9196. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9197. * `target`, and oriented by the up-direction.
  9198. *
  9199. * @param {Vector3} eye - The eye vector.
  9200. * @param {Vector3} target - The target vector.
  9201. * @param {Vector3} up - The up vector.
  9202. * @return {Matrix4} A reference to this matrix.
  9203. */
  9204. lookAt( eye, target, up ) {
  9205. const te = this.elements;
  9206. _z.subVectors( eye, target );
  9207. if ( _z.lengthSq() === 0 ) {
  9208. // eye and target are in the same position
  9209. _z.z = 1;
  9210. }
  9211. _z.normalize();
  9212. _x.crossVectors( up, _z );
  9213. if ( _x.lengthSq() === 0 ) {
  9214. // up and z are parallel
  9215. if ( Math.abs( up.z ) === 1 ) {
  9216. _z.x += 0.0001;
  9217. } else {
  9218. _z.z += 0.0001;
  9219. }
  9220. _z.normalize();
  9221. _x.crossVectors( up, _z );
  9222. }
  9223. _x.normalize();
  9224. _y.crossVectors( _z, _x );
  9225. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9226. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9227. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9228. return this;
  9229. }
  9230. /**
  9231. * Post-multiplies this matrix by the given 4x4 matrix.
  9232. *
  9233. * @param {Matrix4} m - The matrix to multiply with.
  9234. * @return {Matrix4} A reference to this matrix.
  9235. */
  9236. multiply( m ) {
  9237. return this.multiplyMatrices( this, m );
  9238. }
  9239. /**
  9240. * Pre-multiplies this matrix by the given 4x4 matrix.
  9241. *
  9242. * @param {Matrix4} m - The matrix to multiply with.
  9243. * @return {Matrix4} A reference to this matrix.
  9244. */
  9245. premultiply( m ) {
  9246. return this.multiplyMatrices( m, this );
  9247. }
  9248. /**
  9249. * Multiples the given 4x4 matrices and stores the result
  9250. * in this matrix.
  9251. *
  9252. * @param {Matrix4} a - The first matrix.
  9253. * @param {Matrix4} b - The second matrix.
  9254. * @return {Matrix4} A reference to this matrix.
  9255. */
  9256. multiplyMatrices( a, b ) {
  9257. const ae = a.elements;
  9258. const be = b.elements;
  9259. const te = this.elements;
  9260. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9261. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9262. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9263. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9264. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9265. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9266. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9267. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9268. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9269. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9270. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9271. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9272. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9273. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9274. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9275. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9276. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9277. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9278. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9279. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9280. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9281. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9282. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9283. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9284. return this;
  9285. }
  9286. /**
  9287. * Multiplies every component of the matrix by the given scalar.
  9288. *
  9289. * @param {number} s - The scalar.
  9290. * @return {Matrix4} A reference to this matrix.
  9291. */
  9292. multiplyScalar( s ) {
  9293. const te = this.elements;
  9294. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9295. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9296. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9297. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9298. return this;
  9299. }
  9300. /**
  9301. * Computes and returns the determinant of this matrix.
  9302. *
  9303. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9304. *
  9305. * @return {number} The determinant.
  9306. */
  9307. determinant() {
  9308. const te = this.elements;
  9309. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9310. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9311. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9312. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9313. const t11 = n23 * n34 - n24 * n33;
  9314. const t12 = n22 * n34 - n24 * n32;
  9315. const t13 = n22 * n33 - n23 * n32;
  9316. const t21 = n21 * n34 - n24 * n31;
  9317. const t22 = n21 * n33 - n23 * n31;
  9318. const t23 = n21 * n32 - n22 * n31;
  9319. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9320. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9321. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9322. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9323. }
  9324. /**
  9325. * Transposes this matrix in place.
  9326. *
  9327. * @return {Matrix4} A reference to this matrix.
  9328. */
  9329. transpose() {
  9330. const te = this.elements;
  9331. let tmp;
  9332. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9333. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9334. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9335. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9336. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9337. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9338. return this;
  9339. }
  9340. /**
  9341. * Sets the position component for this matrix from the given vector,
  9342. * without affecting the rest of the matrix.
  9343. *
  9344. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9345. * @param {number} y - The y component of the vector.
  9346. * @param {number} z - The z component of the vector.
  9347. * @return {Matrix4} A reference to this matrix.
  9348. */
  9349. setPosition( x, y, z ) {
  9350. const te = this.elements;
  9351. if ( x.isVector3 ) {
  9352. te[ 12 ] = x.x;
  9353. te[ 13 ] = x.y;
  9354. te[ 14 ] = x.z;
  9355. } else {
  9356. te[ 12 ] = x;
  9357. te[ 13 ] = y;
  9358. te[ 14 ] = z;
  9359. }
  9360. return this;
  9361. }
  9362. /**
  9363. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9364. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9365. * a zero matrix instead.
  9366. *
  9367. * @return {Matrix4} A reference to this matrix.
  9368. */
  9369. invert() {
  9370. // based on https://github.com/toji/gl-matrix
  9371. const te = this.elements,
  9372. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9373. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9374. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9375. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9376. t1 = n11 * n22 - n21 * n12,
  9377. t2 = n11 * n32 - n31 * n12,
  9378. t3 = n11 * n42 - n41 * n12,
  9379. t4 = n21 * n32 - n31 * n22,
  9380. t5 = n21 * n42 - n41 * n22,
  9381. t6 = n31 * n42 - n41 * n32,
  9382. t7 = n13 * n24 - n23 * n14,
  9383. t8 = n13 * n34 - n33 * n14,
  9384. t9 = n13 * n44 - n43 * n14,
  9385. t10 = n23 * n34 - n33 * n24,
  9386. t11 = n23 * n44 - n43 * n24,
  9387. t12 = n33 * n44 - n43 * n34;
  9388. const det = t1 * t12 - t2 * t11 + t3 * t10 + t4 * t9 - t5 * t8 + t6 * t7;
  9389. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9390. const detInv = 1 / det;
  9391. te[ 0 ] = ( n22 * t12 - n32 * t11 + n42 * t10 ) * detInv;
  9392. te[ 1 ] = ( n31 * t11 - n21 * t12 - n41 * t10 ) * detInv;
  9393. te[ 2 ] = ( n24 * t6 - n34 * t5 + n44 * t4 ) * detInv;
  9394. te[ 3 ] = ( n33 * t5 - n23 * t6 - n43 * t4 ) * detInv;
  9395. te[ 4 ] = ( n32 * t9 - n12 * t12 - n42 * t8 ) * detInv;
  9396. te[ 5 ] = ( n11 * t12 - n31 * t9 + n41 * t8 ) * detInv;
  9397. te[ 6 ] = ( n34 * t3 - n14 * t6 - n44 * t2 ) * detInv;
  9398. te[ 7 ] = ( n13 * t6 - n33 * t3 + n43 * t2 ) * detInv;
  9399. te[ 8 ] = ( n12 * t11 - n22 * t9 + n42 * t7 ) * detInv;
  9400. te[ 9 ] = ( n21 * t9 - n11 * t11 - n41 * t7 ) * detInv;
  9401. te[ 10 ] = ( n14 * t5 - n24 * t3 + n44 * t1 ) * detInv;
  9402. te[ 11 ] = ( n23 * t3 - n13 * t5 - n43 * t1 ) * detInv;
  9403. te[ 12 ] = ( n22 * t8 - n12 * t10 - n32 * t7 ) * detInv;
  9404. te[ 13 ] = ( n11 * t10 - n21 * t8 + n31 * t7 ) * detInv;
  9405. te[ 14 ] = ( n24 * t2 - n14 * t4 - n34 * t1 ) * detInv;
  9406. te[ 15 ] = ( n13 * t4 - n23 * t2 + n33 * t1 ) * detInv;
  9407. return this;
  9408. }
  9409. /**
  9410. * Multiplies the columns of this matrix by the given vector.
  9411. *
  9412. * @param {Vector3} v - The scale vector.
  9413. * @return {Matrix4} A reference to this matrix.
  9414. */
  9415. scale( v ) {
  9416. const te = this.elements;
  9417. const x = v.x, y = v.y, z = v.z;
  9418. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9419. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9420. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9421. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9422. return this;
  9423. }
  9424. /**
  9425. * Gets the maximum scale value of the three axes.
  9426. *
  9427. * @return {number} The maximum scale.
  9428. */
  9429. getMaxScaleOnAxis() {
  9430. const te = this.elements;
  9431. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9432. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9433. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9434. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9435. }
  9436. /**
  9437. * Sets this matrix as a translation transform from the given vector.
  9438. *
  9439. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9440. * @param {number} y - The amount to translate in the Y axis.
  9441. * @param {number} z - The amount to translate in the z axis.
  9442. * @return {Matrix4} A reference to this matrix.
  9443. */
  9444. makeTranslation( x, y, z ) {
  9445. if ( x.isVector3 ) {
  9446. this.set(
  9447. 1, 0, 0, x.x,
  9448. 0, 1, 0, x.y,
  9449. 0, 0, 1, x.z,
  9450. 0, 0, 0, 1
  9451. );
  9452. } else {
  9453. this.set(
  9454. 1, 0, 0, x,
  9455. 0, 1, 0, y,
  9456. 0, 0, 1, z,
  9457. 0, 0, 0, 1
  9458. );
  9459. }
  9460. return this;
  9461. }
  9462. /**
  9463. * Sets this matrix as a rotational transformation around the X axis by
  9464. * the given angle.
  9465. *
  9466. * @param {number} theta - The rotation in radians.
  9467. * @return {Matrix4} A reference to this matrix.
  9468. */
  9469. makeRotationX( theta ) {
  9470. const c = Math.cos( theta ), s = Math.sin( theta );
  9471. this.set(
  9472. 1, 0, 0, 0,
  9473. 0, c, - s, 0,
  9474. 0, s, c, 0,
  9475. 0, 0, 0, 1
  9476. );
  9477. return this;
  9478. }
  9479. /**
  9480. * Sets this matrix as a rotational transformation around the Y axis by
  9481. * the given angle.
  9482. *
  9483. * @param {number} theta - The rotation in radians.
  9484. * @return {Matrix4} A reference to this matrix.
  9485. */
  9486. makeRotationY( theta ) {
  9487. const c = Math.cos( theta ), s = Math.sin( theta );
  9488. this.set(
  9489. c, 0, s, 0,
  9490. 0, 1, 0, 0,
  9491. - s, 0, c, 0,
  9492. 0, 0, 0, 1
  9493. );
  9494. return this;
  9495. }
  9496. /**
  9497. * Sets this matrix as a rotational transformation around the Z axis by
  9498. * the given angle.
  9499. *
  9500. * @param {number} theta - The rotation in radians.
  9501. * @return {Matrix4} A reference to this matrix.
  9502. */
  9503. makeRotationZ( theta ) {
  9504. const c = Math.cos( theta ), s = Math.sin( theta );
  9505. this.set(
  9506. c, - s, 0, 0,
  9507. s, c, 0, 0,
  9508. 0, 0, 1, 0,
  9509. 0, 0, 0, 1
  9510. );
  9511. return this;
  9512. }
  9513. /**
  9514. * Sets this matrix as a rotational transformation around the given axis by
  9515. * the given angle.
  9516. *
  9517. * This is a somewhat controversial but mathematically sound alternative to
  9518. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9519. *
  9520. * @param {Vector3} axis - The normalized rotation axis.
  9521. * @param {number} angle - The rotation in radians.
  9522. * @return {Matrix4} A reference to this matrix.
  9523. */
  9524. makeRotationAxis( axis, angle ) {
  9525. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9526. const c = Math.cos( angle );
  9527. const s = Math.sin( angle );
  9528. const t = 1 - c;
  9529. const x = axis.x, y = axis.y, z = axis.z;
  9530. const tx = t * x, ty = t * y;
  9531. this.set(
  9532. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9533. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9534. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9535. 0, 0, 0, 1
  9536. );
  9537. return this;
  9538. }
  9539. /**
  9540. * Sets this matrix as a scale transformation.
  9541. *
  9542. * @param {number} x - The amount to scale in the X axis.
  9543. * @param {number} y - The amount to scale in the Y axis.
  9544. * @param {number} z - The amount to scale in the Z axis.
  9545. * @return {Matrix4} A reference to this matrix.
  9546. */
  9547. makeScale( x, y, z ) {
  9548. this.set(
  9549. x, 0, 0, 0,
  9550. 0, y, 0, 0,
  9551. 0, 0, z, 0,
  9552. 0, 0, 0, 1
  9553. );
  9554. return this;
  9555. }
  9556. /**
  9557. * Sets this matrix as a shear transformation.
  9558. *
  9559. * @param {number} xy - The amount to shear X by Y.
  9560. * @param {number} xz - The amount to shear X by Z.
  9561. * @param {number} yx - The amount to shear Y by X.
  9562. * @param {number} yz - The amount to shear Y by Z.
  9563. * @param {number} zx - The amount to shear Z by X.
  9564. * @param {number} zy - The amount to shear Z by Y.
  9565. * @return {Matrix4} A reference to this matrix.
  9566. */
  9567. makeShear( xy, xz, yx, yz, zx, zy ) {
  9568. this.set(
  9569. 1, yx, zx, 0,
  9570. xy, 1, zy, 0,
  9571. xz, yz, 1, 0,
  9572. 0, 0, 0, 1
  9573. );
  9574. return this;
  9575. }
  9576. /**
  9577. * Sets this matrix to the transformation composed of the given position,
  9578. * rotation (Quaternion) and scale.
  9579. *
  9580. * @param {Vector3} position - The position vector.
  9581. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9582. * @param {Vector3} scale - The scale vector.
  9583. * @return {Matrix4} A reference to this matrix.
  9584. */
  9585. compose( position, quaternion, scale ) {
  9586. const te = this.elements;
  9587. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9588. const x2 = x + x, y2 = y + y, z2 = z + z;
  9589. const xx = x * x2, xy = x * y2, xz = x * z2;
  9590. const yy = y * y2, yz = y * z2, zz = z * z2;
  9591. const wx = w * x2, wy = w * y2, wz = w * z2;
  9592. const sx = scale.x, sy = scale.y, sz = scale.z;
  9593. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9594. te[ 1 ] = ( xy + wz ) * sx;
  9595. te[ 2 ] = ( xz - wy ) * sx;
  9596. te[ 3 ] = 0;
  9597. te[ 4 ] = ( xy - wz ) * sy;
  9598. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9599. te[ 6 ] = ( yz + wx ) * sy;
  9600. te[ 7 ] = 0;
  9601. te[ 8 ] = ( xz + wy ) * sz;
  9602. te[ 9 ] = ( yz - wx ) * sz;
  9603. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9604. te[ 11 ] = 0;
  9605. te[ 12 ] = position.x;
  9606. te[ 13 ] = position.y;
  9607. te[ 14 ] = position.z;
  9608. te[ 15 ] = 1;
  9609. return this;
  9610. }
  9611. /**
  9612. * Decomposes this matrix into its position, rotation and scale components
  9613. * and provides the result in the given objects.
  9614. *
  9615. * Note: Not all matrices are decomposable in this way. For example, if an
  9616. * object has a non-uniformly scaled parent, then the object's world matrix
  9617. * may not be decomposable, and this method may not be appropriate.
  9618. *
  9619. * @param {Vector3} position - The position vector.
  9620. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9621. * @param {Vector3} scale - The scale vector.
  9622. * @return {Matrix4} A reference to this matrix.
  9623. */
  9624. decompose( position, quaternion, scale ) {
  9625. const te = this.elements;
  9626. position.x = te[ 12 ];
  9627. position.y = te[ 13 ];
  9628. position.z = te[ 14 ];
  9629. const det = this.determinant();
  9630. if ( det === 0 ) {
  9631. scale.set( 1, 1, 1 );
  9632. quaternion.identity();
  9633. return this;
  9634. }
  9635. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9636. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9637. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9638. // if determinant is negative, we need to invert one scale
  9639. if ( det < 0 ) sx = - sx;
  9640. // scale the rotation part
  9641. _m1$4.copy( this );
  9642. const invSX = 1 / sx;
  9643. const invSY = 1 / sy;
  9644. const invSZ = 1 / sz;
  9645. _m1$4.elements[ 0 ] *= invSX;
  9646. _m1$4.elements[ 1 ] *= invSX;
  9647. _m1$4.elements[ 2 ] *= invSX;
  9648. _m1$4.elements[ 4 ] *= invSY;
  9649. _m1$4.elements[ 5 ] *= invSY;
  9650. _m1$4.elements[ 6 ] *= invSY;
  9651. _m1$4.elements[ 8 ] *= invSZ;
  9652. _m1$4.elements[ 9 ] *= invSZ;
  9653. _m1$4.elements[ 10 ] *= invSZ;
  9654. quaternion.setFromRotationMatrix( _m1$4 );
  9655. scale.x = sx;
  9656. scale.y = sy;
  9657. scale.z = sz;
  9658. return this;
  9659. }
  9660. /**
  9661. * Creates a perspective projection matrix. This is used internally by
  9662. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9663. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9664. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9665. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9666. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9667. * @param {number} near - The distance from the camera to the near plane.
  9668. * @param {number} far - The distance from the camera to the far plane.
  9669. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9670. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9671. * @return {Matrix4} A reference to this matrix.
  9672. */
  9673. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9674. const te = this.elements;
  9675. const x = 2 * near / ( right - left );
  9676. const y = 2 * near / ( top - bottom );
  9677. const a = ( right + left ) / ( right - left );
  9678. const b = ( top + bottom ) / ( top - bottom );
  9679. let c, d;
  9680. if ( reversedDepth ) {
  9681. c = near / ( far - near );
  9682. d = ( far * near ) / ( far - near );
  9683. } else {
  9684. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9685. c = - ( far + near ) / ( far - near );
  9686. d = ( -2 * far * near ) / ( far - near );
  9687. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9688. c = - far / ( far - near );
  9689. d = ( - far * near ) / ( far - near );
  9690. } else {
  9691. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9692. }
  9693. }
  9694. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9695. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9696. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9697. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9698. return this;
  9699. }
  9700. /**
  9701. * Creates a orthographic projection matrix. This is used internally by
  9702. * {@link OrthographicCamera#updateProjectionMatrix}.
  9703. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9704. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9705. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9706. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9707. * @param {number} near - The distance from the camera to the near plane.
  9708. * @param {number} far - The distance from the camera to the far plane.
  9709. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9710. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9711. * @return {Matrix4} A reference to this matrix.
  9712. */
  9713. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9714. const te = this.elements;
  9715. const x = 2 / ( right - left );
  9716. const y = 2 / ( top - bottom );
  9717. const a = - ( right + left ) / ( right - left );
  9718. const b = - ( top + bottom ) / ( top - bottom );
  9719. let c, d;
  9720. if ( reversedDepth ) {
  9721. c = 1 / ( far - near );
  9722. d = far / ( far - near );
  9723. } else {
  9724. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9725. c = -2 / ( far - near );
  9726. d = - ( far + near ) / ( far - near );
  9727. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9728. c = -1 / ( far - near );
  9729. d = - near / ( far - near );
  9730. } else {
  9731. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9732. }
  9733. }
  9734. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9735. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9736. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9737. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9738. return this;
  9739. }
  9740. /**
  9741. * Returns `true` if this matrix is equal with the given one.
  9742. *
  9743. * @param {Matrix4} matrix - The matrix to test for equality.
  9744. * @return {boolean} Whether this matrix is equal with the given one.
  9745. */
  9746. equals( matrix ) {
  9747. const te = this.elements;
  9748. const me = matrix.elements;
  9749. for ( let i = 0; i < 16; i ++ ) {
  9750. if ( te[ i ] !== me[ i ] ) return false;
  9751. }
  9752. return true;
  9753. }
  9754. /**
  9755. * Sets the elements of the matrix from the given array.
  9756. *
  9757. * @param {Array<number>} array - The matrix elements in column-major order.
  9758. * @param {number} [offset=0] - Index of the first element in the array.
  9759. * @return {Matrix4} A reference to this matrix.
  9760. */
  9761. fromArray( array, offset = 0 ) {
  9762. for ( let i = 0; i < 16; i ++ ) {
  9763. this.elements[ i ] = array[ i + offset ];
  9764. }
  9765. return this;
  9766. }
  9767. /**
  9768. * Writes the elements of this matrix to the given array. If no array is provided,
  9769. * the method returns a new instance.
  9770. *
  9771. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9772. * @param {number} [offset=0] - Index of the first element in the array.
  9773. * @return {Array<number>} The matrix elements in column-major order.
  9774. */
  9775. toArray( array = [], offset = 0 ) {
  9776. const te = this.elements;
  9777. array[ offset ] = te[ 0 ];
  9778. array[ offset + 1 ] = te[ 1 ];
  9779. array[ offset + 2 ] = te[ 2 ];
  9780. array[ offset + 3 ] = te[ 3 ];
  9781. array[ offset + 4 ] = te[ 4 ];
  9782. array[ offset + 5 ] = te[ 5 ];
  9783. array[ offset + 6 ] = te[ 6 ];
  9784. array[ offset + 7 ] = te[ 7 ];
  9785. array[ offset + 8 ] = te[ 8 ];
  9786. array[ offset + 9 ] = te[ 9 ];
  9787. array[ offset + 10 ] = te[ 10 ];
  9788. array[ offset + 11 ] = te[ 11 ];
  9789. array[ offset + 12 ] = te[ 12 ];
  9790. array[ offset + 13 ] = te[ 13 ];
  9791. array[ offset + 14 ] = te[ 14 ];
  9792. array[ offset + 15 ] = te[ 15 ];
  9793. return array;
  9794. }
  9795. }
  9796. const _v1$5 = /*@__PURE__*/ new Vector3();
  9797. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9798. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9799. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9800. const _x = /*@__PURE__*/ new Vector3();
  9801. const _y = /*@__PURE__*/ new Vector3();
  9802. const _z = /*@__PURE__*/ new Vector3();
  9803. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9804. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9805. /**
  9806. * A class representing Euler angles.
  9807. *
  9808. * Euler angles describe a rotational transformation by rotating an object on
  9809. * its various axes in specified amounts per axis, and a specified axis
  9810. * order.
  9811. *
  9812. * Iterating through an instance will yield its components (x, y, z,
  9813. * order) in the corresponding order.
  9814. *
  9815. * ```js
  9816. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9817. * const b = new THREE.Vector3( 1, 0, 1 );
  9818. * b.applyEuler(a);
  9819. * ```
  9820. */
  9821. class Euler {
  9822. /**
  9823. * Constructs a new euler instance.
  9824. *
  9825. * @param {number} [x=0] - The angle of the x axis in radians.
  9826. * @param {number} [y=0] - The angle of the y axis in radians.
  9827. * @param {number} [z=0] - The angle of the z axis in radians.
  9828. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9829. */
  9830. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9831. /**
  9832. * This flag can be used for type testing.
  9833. *
  9834. * @type {boolean}
  9835. * @readonly
  9836. * @default true
  9837. */
  9838. this.isEuler = true;
  9839. this._x = x;
  9840. this._y = y;
  9841. this._z = z;
  9842. this._order = order;
  9843. }
  9844. /**
  9845. * The angle of the x axis in radians.
  9846. *
  9847. * @type {number}
  9848. * @default 0
  9849. */
  9850. get x() {
  9851. return this._x;
  9852. }
  9853. set x( value ) {
  9854. this._x = value;
  9855. this._onChangeCallback();
  9856. }
  9857. /**
  9858. * The angle of the y axis in radians.
  9859. *
  9860. * @type {number}
  9861. * @default 0
  9862. */
  9863. get y() {
  9864. return this._y;
  9865. }
  9866. set y( value ) {
  9867. this._y = value;
  9868. this._onChangeCallback();
  9869. }
  9870. /**
  9871. * The angle of the z axis in radians.
  9872. *
  9873. * @type {number}
  9874. * @default 0
  9875. */
  9876. get z() {
  9877. return this._z;
  9878. }
  9879. set z( value ) {
  9880. this._z = value;
  9881. this._onChangeCallback();
  9882. }
  9883. /**
  9884. * A string representing the order that the rotations are applied.
  9885. *
  9886. * @type {string}
  9887. * @default 'XYZ'
  9888. */
  9889. get order() {
  9890. return this._order;
  9891. }
  9892. set order( value ) {
  9893. this._order = value;
  9894. this._onChangeCallback();
  9895. }
  9896. /**
  9897. * Sets the Euler components.
  9898. *
  9899. * @param {number} x - The angle of the x axis in radians.
  9900. * @param {number} y - The angle of the y axis in radians.
  9901. * @param {number} z - The angle of the z axis in radians.
  9902. * @param {string} [order] - A string representing the order that the rotations are applied.
  9903. * @return {Euler} A reference to this Euler instance.
  9904. */
  9905. set( x, y, z, order = this._order ) {
  9906. this._x = x;
  9907. this._y = y;
  9908. this._z = z;
  9909. this._order = order;
  9910. this._onChangeCallback();
  9911. return this;
  9912. }
  9913. /**
  9914. * Returns a new Euler instance with copied values from this instance.
  9915. *
  9916. * @return {Euler} A clone of this instance.
  9917. */
  9918. clone() {
  9919. return new this.constructor( this._x, this._y, this._z, this._order );
  9920. }
  9921. /**
  9922. * Copies the values of the given Euler instance to this instance.
  9923. *
  9924. * @param {Euler} euler - The Euler instance to copy.
  9925. * @return {Euler} A reference to this Euler instance.
  9926. */
  9927. copy( euler ) {
  9928. this._x = euler._x;
  9929. this._y = euler._y;
  9930. this._z = euler._z;
  9931. this._order = euler._order;
  9932. this._onChangeCallback();
  9933. return this;
  9934. }
  9935. /**
  9936. * Sets the angles of this Euler instance from a pure rotation matrix.
  9937. *
  9938. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9939. * @param {string} [order] - A string representing the order that the rotations are applied.
  9940. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9941. * @return {Euler} A reference to this Euler instance.
  9942. */
  9943. setFromRotationMatrix( m, order = this._order, update = true ) {
  9944. const te = m.elements;
  9945. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9946. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9947. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9948. switch ( order ) {
  9949. case 'XYZ':
  9950. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9951. if ( Math.abs( m13 ) < 0.9999999 ) {
  9952. this._x = Math.atan2( - m23, m33 );
  9953. this._z = Math.atan2( - m12, m11 );
  9954. } else {
  9955. this._x = Math.atan2( m32, m22 );
  9956. this._z = 0;
  9957. }
  9958. break;
  9959. case 'YXZ':
  9960. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9961. if ( Math.abs( m23 ) < 0.9999999 ) {
  9962. this._y = Math.atan2( m13, m33 );
  9963. this._z = Math.atan2( m21, m22 );
  9964. } else {
  9965. this._y = Math.atan2( - m31, m11 );
  9966. this._z = 0;
  9967. }
  9968. break;
  9969. case 'ZXY':
  9970. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9971. if ( Math.abs( m32 ) < 0.9999999 ) {
  9972. this._y = Math.atan2( - m31, m33 );
  9973. this._z = Math.atan2( - m12, m22 );
  9974. } else {
  9975. this._y = 0;
  9976. this._z = Math.atan2( m21, m11 );
  9977. }
  9978. break;
  9979. case 'ZYX':
  9980. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9981. if ( Math.abs( m31 ) < 0.9999999 ) {
  9982. this._x = Math.atan2( m32, m33 );
  9983. this._z = Math.atan2( m21, m11 );
  9984. } else {
  9985. this._x = 0;
  9986. this._z = Math.atan2( - m12, m22 );
  9987. }
  9988. break;
  9989. case 'YZX':
  9990. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9991. if ( Math.abs( m21 ) < 0.9999999 ) {
  9992. this._x = Math.atan2( - m23, m22 );
  9993. this._y = Math.atan2( - m31, m11 );
  9994. } else {
  9995. this._x = 0;
  9996. this._y = Math.atan2( m13, m33 );
  9997. }
  9998. break;
  9999. case 'XZY':
  10000. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  10001. if ( Math.abs( m12 ) < 0.9999999 ) {
  10002. this._x = Math.atan2( m32, m22 );
  10003. this._y = Math.atan2( m13, m11 );
  10004. } else {
  10005. this._x = Math.atan2( - m23, m33 );
  10006. this._y = 0;
  10007. }
  10008. break;
  10009. default:
  10010. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  10011. }
  10012. this._order = order;
  10013. if ( update === true ) this._onChangeCallback();
  10014. return this;
  10015. }
  10016. /**
  10017. * Sets the angles of this Euler instance from a normalized quaternion.
  10018. *
  10019. * @param {Quaternion} q - A normalized Quaternion.
  10020. * @param {string} [order] - A string representing the order that the rotations are applied.
  10021. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  10022. * @return {Euler} A reference to this Euler instance.
  10023. */
  10024. setFromQuaternion( q, order, update ) {
  10025. _matrix$2.makeRotationFromQuaternion( q );
  10026. return this.setFromRotationMatrix( _matrix$2, order, update );
  10027. }
  10028. /**
  10029. * Sets the angles of this Euler instance from the given vector.
  10030. *
  10031. * @param {Vector3} v - The vector.
  10032. * @param {string} [order] - A string representing the order that the rotations are applied.
  10033. * @return {Euler} A reference to this Euler instance.
  10034. */
  10035. setFromVector3( v, order = this._order ) {
  10036. return this.set( v.x, v.y, v.z, order );
  10037. }
  10038. /**
  10039. * Resets the euler angle with a new order by creating a quaternion from this
  10040. * euler angle and then setting this euler angle with the quaternion and the
  10041. * new order.
  10042. *
  10043. * Warning: This discards revolution information.
  10044. *
  10045. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  10046. * @return {Euler} A reference to this Euler instance.
  10047. */
  10048. reorder( newOrder ) {
  10049. _quaternion$3.setFromEuler( this );
  10050. return this.setFromQuaternion( _quaternion$3, newOrder );
  10051. }
  10052. /**
  10053. * Returns `true` if this Euler instance is equal with the given one.
  10054. *
  10055. * @param {Euler} euler - The Euler instance to test for equality.
  10056. * @return {boolean} Whether this Euler instance is equal with the given one.
  10057. */
  10058. equals( euler ) {
  10059. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10060. }
  10061. /**
  10062. * Sets this Euler instance's components to values from the given array. The first three
  10063. * entries of the array are assign to the x,y and z components. An optional fourth entry
  10064. * defines the Euler order.
  10065. *
  10066. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  10067. * @return {Euler} A reference to this Euler instance.
  10068. */
  10069. fromArray( array ) {
  10070. this._x = array[ 0 ];
  10071. this._y = array[ 1 ];
  10072. this._z = array[ 2 ];
  10073. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10074. this._onChangeCallback();
  10075. return this;
  10076. }
  10077. /**
  10078. * Writes the components of this Euler instance to the given array. If no array is provided,
  10079. * the method returns a new instance.
  10080. *
  10081. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  10082. * @param {number} [offset=0] - Index of the first element in the array.
  10083. * @return {Array<number,number,number,string>} The Euler components.
  10084. */
  10085. toArray( array = [], offset = 0 ) {
  10086. array[ offset ] = this._x;
  10087. array[ offset + 1 ] = this._y;
  10088. array[ offset + 2 ] = this._z;
  10089. array[ offset + 3 ] = this._order;
  10090. return array;
  10091. }
  10092. _onChange( callback ) {
  10093. this._onChangeCallback = callback;
  10094. return this;
  10095. }
  10096. _onChangeCallback() {}
  10097. *[ Symbol.iterator ]() {
  10098. yield this._x;
  10099. yield this._y;
  10100. yield this._z;
  10101. yield this._order;
  10102. }
  10103. }
  10104. /**
  10105. * The default Euler angle order.
  10106. *
  10107. * @static
  10108. * @type {string}
  10109. * @default 'XYZ'
  10110. */
  10111. Euler.DEFAULT_ORDER = 'XYZ';
  10112. /**
  10113. * A layers object assigns an 3D object to 1 or more of 32
  10114. * layers numbered `0` to `31` - internally the layers are stored as a
  10115. * bit mask], and by default all 3D objects are a member of layer `0`.
  10116. *
  10117. * This can be used to control visibility - an object must share a layer with
  10118. * a camera to be visible when that camera's view is
  10119. * rendered.
  10120. *
  10121. * All classes that inherit from {@link Object3D} have an `layers` property which
  10122. * is an instance of this class.
  10123. */
  10124. class Layers {
  10125. /**
  10126. * Constructs a new layers instance, with membership
  10127. * initially set to layer `0`.
  10128. */
  10129. constructor() {
  10130. /**
  10131. * A bit mask storing which of the 32 layers this layers object is currently
  10132. * a member of.
  10133. *
  10134. * @type {number}
  10135. */
  10136. this.mask = 1 | 0;
  10137. }
  10138. /**
  10139. * Sets membership to the given layer, and remove membership all other layers.
  10140. *
  10141. * @param {number} layer - The layer to set.
  10142. */
  10143. set( layer ) {
  10144. this.mask = ( 1 << layer | 0 ) >>> 0;
  10145. }
  10146. /**
  10147. * Adds membership of the given layer.
  10148. *
  10149. * @param {number} layer - The layer to enable.
  10150. */
  10151. enable( layer ) {
  10152. this.mask |= 1 << layer | 0;
  10153. }
  10154. /**
  10155. * Adds membership to all layers.
  10156. */
  10157. enableAll() {
  10158. this.mask = 0xffffffff | 0;
  10159. }
  10160. /**
  10161. * Toggles the membership of the given layer.
  10162. *
  10163. * @param {number} layer - The layer to toggle.
  10164. */
  10165. toggle( layer ) {
  10166. this.mask ^= 1 << layer | 0;
  10167. }
  10168. /**
  10169. * Removes membership of the given layer.
  10170. *
  10171. * @param {number} layer - The layer to enable.
  10172. */
  10173. disable( layer ) {
  10174. this.mask &= ~ ( 1 << layer | 0 );
  10175. }
  10176. /**
  10177. * Removes the membership from all layers.
  10178. */
  10179. disableAll() {
  10180. this.mask = 0;
  10181. }
  10182. /**
  10183. * Returns `true` if this and the given layers object have at least one
  10184. * layer in common.
  10185. *
  10186. * @param {Layers} layers - The layers to test.
  10187. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10188. */
  10189. test( layers ) {
  10190. return ( this.mask & layers.mask ) !== 0;
  10191. }
  10192. /**
  10193. * Returns `true` if the given layer is enabled.
  10194. *
  10195. * @param {number} layer - The layer to test.
  10196. * @return {boolean } Whether the given layer is enabled or not.
  10197. */
  10198. isEnabled( layer ) {
  10199. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10200. }
  10201. }
  10202. let _object3DId = 0;
  10203. const _v1$4 = /*@__PURE__*/ new Vector3();
  10204. const _q1 = /*@__PURE__*/ new Quaternion();
  10205. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10206. const _target = /*@__PURE__*/ new Vector3();
  10207. const _position$3 = /*@__PURE__*/ new Vector3();
  10208. const _scale$2 = /*@__PURE__*/ new Vector3();
  10209. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10210. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10211. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10212. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10213. /**
  10214. * Fires when the object has been added to its parent object.
  10215. *
  10216. * @event Object3D#added
  10217. * @type {Object}
  10218. */
  10219. const _addedEvent = { type: 'added' };
  10220. /**
  10221. * Fires when the object has been removed from its parent object.
  10222. *
  10223. * @event Object3D#removed
  10224. * @type {Object}
  10225. */
  10226. const _removedEvent = { type: 'removed' };
  10227. /**
  10228. * Fires when a new child object has been added.
  10229. *
  10230. * @event Object3D#childadded
  10231. * @type {Object}
  10232. */
  10233. const _childaddedEvent = { type: 'childadded', child: null };
  10234. /**
  10235. * Fires when a child object has been removed.
  10236. *
  10237. * @event Object3D#childremoved
  10238. * @type {Object}
  10239. */
  10240. const _childremovedEvent = { type: 'childremoved', child: null };
  10241. /**
  10242. * This is the base class for most objects in three.js and provides a set of
  10243. * properties and methods for manipulating objects in 3D space.
  10244. *
  10245. * @augments EventDispatcher
  10246. */
  10247. class Object3D extends EventDispatcher {
  10248. /**
  10249. * Constructs a new 3D object.
  10250. */
  10251. constructor() {
  10252. super();
  10253. /**
  10254. * This flag can be used for type testing.
  10255. *
  10256. * @type {boolean}
  10257. * @readonly
  10258. * @default true
  10259. */
  10260. this.isObject3D = true;
  10261. /**
  10262. * The ID of the 3D object.
  10263. *
  10264. * @name Object3D#id
  10265. * @type {number}
  10266. * @readonly
  10267. */
  10268. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10269. /**
  10270. * The UUID of the 3D object.
  10271. *
  10272. * @type {string}
  10273. * @readonly
  10274. */
  10275. this.uuid = generateUUID();
  10276. /**
  10277. * The name of the 3D object.
  10278. *
  10279. * @type {string}
  10280. */
  10281. this.name = '';
  10282. /**
  10283. * The type property is used for detecting the object type
  10284. * in context of serialization/deserialization.
  10285. *
  10286. * @type {string}
  10287. * @readonly
  10288. */
  10289. this.type = 'Object3D';
  10290. /**
  10291. * A reference to the parent object.
  10292. *
  10293. * @type {?Object3D}
  10294. * @default null
  10295. */
  10296. this.parent = null;
  10297. /**
  10298. * An array holding the child 3D objects of this instance.
  10299. *
  10300. * @type {Array<Object3D>}
  10301. */
  10302. this.children = [];
  10303. /**
  10304. * Defines the `up` direction of the 3D object which influences
  10305. * the orientation via methods like {@link Object3D#lookAt}.
  10306. *
  10307. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10308. *
  10309. * @type {Vector3}
  10310. */
  10311. this.up = Object3D.DEFAULT_UP.clone();
  10312. const position = new Vector3();
  10313. const rotation = new Euler();
  10314. const quaternion = new Quaternion();
  10315. const scale = new Vector3( 1, 1, 1 );
  10316. function onRotationChange() {
  10317. quaternion.setFromEuler( rotation, false );
  10318. }
  10319. function onQuaternionChange() {
  10320. rotation.setFromQuaternion( quaternion, undefined, false );
  10321. }
  10322. rotation._onChange( onRotationChange );
  10323. quaternion._onChange( onQuaternionChange );
  10324. Object.defineProperties( this, {
  10325. /**
  10326. * Represents the object's local position.
  10327. *
  10328. * @name Object3D#position
  10329. * @type {Vector3}
  10330. * @default (0,0,0)
  10331. */
  10332. position: {
  10333. configurable: true,
  10334. enumerable: true,
  10335. value: position
  10336. },
  10337. /**
  10338. * Represents the object's local rotation as Euler angles, in radians.
  10339. *
  10340. * @name Object3D#rotation
  10341. * @type {Euler}
  10342. * @default (0,0,0)
  10343. */
  10344. rotation: {
  10345. configurable: true,
  10346. enumerable: true,
  10347. value: rotation
  10348. },
  10349. /**
  10350. * Represents the object's local rotation as Quaternions.
  10351. *
  10352. * @name Object3D#quaternion
  10353. * @type {Quaternion}
  10354. */
  10355. quaternion: {
  10356. configurable: true,
  10357. enumerable: true,
  10358. value: quaternion
  10359. },
  10360. /**
  10361. * Represents the object's local scale.
  10362. *
  10363. * @name Object3D#scale
  10364. * @type {Vector3}
  10365. * @default (1,1,1)
  10366. */
  10367. scale: {
  10368. configurable: true,
  10369. enumerable: true,
  10370. value: scale
  10371. },
  10372. /**
  10373. * Represents the object's model-view matrix.
  10374. *
  10375. * @name Object3D#modelViewMatrix
  10376. * @type {Matrix4}
  10377. */
  10378. modelViewMatrix: {
  10379. value: new Matrix4()
  10380. },
  10381. /**
  10382. * Represents the object's normal matrix.
  10383. *
  10384. * @name Object3D#normalMatrix
  10385. * @type {Matrix3}
  10386. */
  10387. normalMatrix: {
  10388. value: new Matrix3()
  10389. }
  10390. } );
  10391. /**
  10392. * Represents the object's transformation matrix in local space.
  10393. *
  10394. * @type {Matrix4}
  10395. */
  10396. this.matrix = new Matrix4();
  10397. /**
  10398. * Represents the object's transformation matrix in world space.
  10399. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10400. *
  10401. * @type {Matrix4}
  10402. */
  10403. this.matrixWorld = new Matrix4();
  10404. /**
  10405. * When set to `true`, the engine automatically computes the local matrix from position,
  10406. * rotation and scale every frame.
  10407. *
  10408. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10409. *
  10410. * @type {boolean}
  10411. * @default true
  10412. */
  10413. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10414. /**
  10415. * When set to `true`, the engine automatically computes the world matrix from the current local
  10416. * matrix and the object's transformation hierarchy.
  10417. *
  10418. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10419. *
  10420. * @type {boolean}
  10421. * @default true
  10422. */
  10423. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10424. /**
  10425. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10426. * to `false`.
  10427. *
  10428. * @type {boolean}
  10429. * @default false
  10430. */
  10431. this.matrixWorldNeedsUpdate = false;
  10432. /**
  10433. * The layer membership of the 3D object. The 3D object is only visible if it has
  10434. * at least one layer in common with the camera in use. This property can also be
  10435. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10436. *
  10437. * @type {Layers}
  10438. */
  10439. this.layers = new Layers();
  10440. /**
  10441. * When set to `true`, the 3D object gets rendered.
  10442. *
  10443. * @type {boolean}
  10444. * @default true
  10445. */
  10446. this.visible = true;
  10447. /**
  10448. * When set to `true`, the 3D object gets rendered into shadow maps.
  10449. *
  10450. * @type {boolean}
  10451. * @default false
  10452. */
  10453. this.castShadow = false;
  10454. /**
  10455. * When set to `true`, the 3D object is affected by shadows in the scene.
  10456. *
  10457. * @type {boolean}
  10458. * @default false
  10459. */
  10460. this.receiveShadow = false;
  10461. /**
  10462. * When set to `true`, the 3D object is honored by view frustum culling.
  10463. *
  10464. * @type {boolean}
  10465. * @default true
  10466. */
  10467. this.frustumCulled = true;
  10468. /**
  10469. * This value allows the default rendering order of scene graph objects to be
  10470. * overridden although opaque and transparent objects remain sorted independently.
  10471. * When this property is set for an instance of {@link Group},all descendants
  10472. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10473. * render order.
  10474. *
  10475. * @type {number}
  10476. * @default 0
  10477. */
  10478. this.renderOrder = 0;
  10479. /**
  10480. * An array holding the animation clips of the 3D object.
  10481. *
  10482. * @type {Array<AnimationClip>}
  10483. */
  10484. this.animations = [];
  10485. /**
  10486. * Custom depth material to be used when rendering to the depth map. Can only be used
  10487. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10488. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10489. * material for proper shadows.
  10490. *
  10491. * Only relevant in context of {@link WebGLRenderer}.
  10492. *
  10493. * @type {(Material|undefined)}
  10494. * @default undefined
  10495. */
  10496. this.customDepthMaterial = undefined;
  10497. /**
  10498. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10499. *
  10500. * Only relevant in context of {@link WebGLRenderer}.
  10501. *
  10502. * @type {(Material|undefined)}
  10503. * @default undefined
  10504. */
  10505. this.customDistanceMaterial = undefined;
  10506. /**
  10507. * Whether the 3D object is supposed to be static or not. If set to `true`, it means
  10508. * the 3D object is not going to be changed after the initial renderer. This includes
  10509. * geometry and material settings. A static 3D object can be processed by the renderer
  10510. * slightly faster since certain state checks can be bypassed.
  10511. *
  10512. * Only relevant in context of {@link WebGPURenderer}.
  10513. *
  10514. * @type {boolean}
  10515. * @default false
  10516. */
  10517. this.static = false;
  10518. /**
  10519. * An object that can be used to store custom data about the 3D object. It
  10520. * should not hold references to functions as these will not be cloned.
  10521. *
  10522. * @type {Object}
  10523. */
  10524. this.userData = {};
  10525. /**
  10526. * The pivot point for rotation and scale transformations.
  10527. * When set, rotation and scale are applied around this point
  10528. * instead of the object's origin.
  10529. *
  10530. * @type {?Vector3}
  10531. * @default null
  10532. */
  10533. this.pivot = null;
  10534. }
  10535. /**
  10536. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10537. *
  10538. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10539. * @param {Object3D} object - The 3D object.
  10540. * @param {Camera} camera - The camera that is used to render the scene.
  10541. * @param {Camera} shadowCamera - The shadow camera.
  10542. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10543. * @param {Material} depthMaterial - The depth material.
  10544. * @param {Object} group - The geometry group data.
  10545. */
  10546. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10547. /**
  10548. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10549. *
  10550. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10551. * @param {Object3D} object - The 3D object.
  10552. * @param {Camera} camera - The camera that is used to render the scene.
  10553. * @param {Camera} shadowCamera - The shadow camera.
  10554. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10555. * @param {Material} depthMaterial - The depth material.
  10556. * @param {Object} group - The geometry group data.
  10557. */
  10558. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10559. /**
  10560. * A callback that is executed immediately before a 3D object is rendered.
  10561. *
  10562. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10563. * @param {Object3D} object - The 3D object.
  10564. * @param {Camera} camera - The camera that is used to render the scene.
  10565. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10566. * @param {Material} material - The 3D object's material.
  10567. * @param {Object} group - The geometry group data.
  10568. */
  10569. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10570. /**
  10571. * A callback that is executed immediately after a 3D object is rendered.
  10572. *
  10573. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10574. * @param {Object3D} object - The 3D object.
  10575. * @param {Camera} camera - The camera that is used to render the scene.
  10576. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10577. * @param {Material} material - The 3D object's material.
  10578. * @param {Object} group - The geometry group data.
  10579. */
  10580. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10581. /**
  10582. * Applies the given transformation matrix to the object and updates the object's position,
  10583. * rotation and scale.
  10584. *
  10585. * @param {Matrix4} matrix - The transformation matrix.
  10586. */
  10587. applyMatrix4( matrix ) {
  10588. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10589. this.matrix.premultiply( matrix );
  10590. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10591. }
  10592. /**
  10593. * Applies a rotation represented by given the quaternion to the 3D object.
  10594. *
  10595. * @param {Quaternion} q - The quaternion.
  10596. * @return {Object3D} A reference to this instance.
  10597. */
  10598. applyQuaternion( q ) {
  10599. this.quaternion.premultiply( q );
  10600. return this;
  10601. }
  10602. /**
  10603. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10604. *
  10605. * @param {Vector3} axis - The (normalized) axis vector.
  10606. * @param {number} angle - The angle in radians.
  10607. */
  10608. setRotationFromAxisAngle( axis, angle ) {
  10609. // assumes axis is normalized
  10610. this.quaternion.setFromAxisAngle( axis, angle );
  10611. }
  10612. /**
  10613. * Sets the given rotation represented as Euler angles to the 3D object.
  10614. *
  10615. * @param {Euler} euler - The Euler angles.
  10616. */
  10617. setRotationFromEuler( euler ) {
  10618. this.quaternion.setFromEuler( euler, true );
  10619. }
  10620. /**
  10621. * Sets the given rotation represented as rotation matrix to the 3D object.
  10622. *
  10623. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10624. * a pure rotation matrix (i.e, unscaled).
  10625. */
  10626. setRotationFromMatrix( m ) {
  10627. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10628. this.quaternion.setFromRotationMatrix( m );
  10629. }
  10630. /**
  10631. * Sets the given rotation represented as a Quaternion to the 3D object.
  10632. *
  10633. * @param {Quaternion} q - The Quaternion
  10634. */
  10635. setRotationFromQuaternion( q ) {
  10636. // assumes q is normalized
  10637. this.quaternion.copy( q );
  10638. }
  10639. /**
  10640. * Rotates the 3D object along an axis in local space.
  10641. *
  10642. * @param {Vector3} axis - The (normalized) axis vector.
  10643. * @param {number} angle - The angle in radians.
  10644. * @return {Object3D} A reference to this instance.
  10645. */
  10646. rotateOnAxis( axis, angle ) {
  10647. // rotate object on axis in object space
  10648. // axis is assumed to be normalized
  10649. _q1.setFromAxisAngle( axis, angle );
  10650. this.quaternion.multiply( _q1 );
  10651. return this;
  10652. }
  10653. /**
  10654. * Rotates the 3D object along an axis in world space.
  10655. *
  10656. * @param {Vector3} axis - The (normalized) axis vector.
  10657. * @param {number} angle - The angle in radians.
  10658. * @return {Object3D} A reference to this instance.
  10659. */
  10660. rotateOnWorldAxis( axis, angle ) {
  10661. // rotate object on axis in world space
  10662. // axis is assumed to be normalized
  10663. // method assumes no rotated parent
  10664. _q1.setFromAxisAngle( axis, angle );
  10665. this.quaternion.premultiply( _q1 );
  10666. return this;
  10667. }
  10668. /**
  10669. * Rotates the 3D object around its X axis in local space.
  10670. *
  10671. * @param {number} angle - The angle in radians.
  10672. * @return {Object3D} A reference to this instance.
  10673. */
  10674. rotateX( angle ) {
  10675. return this.rotateOnAxis( _xAxis, angle );
  10676. }
  10677. /**
  10678. * Rotates the 3D object around its Y axis in local space.
  10679. *
  10680. * @param {number} angle - The angle in radians.
  10681. * @return {Object3D} A reference to this instance.
  10682. */
  10683. rotateY( angle ) {
  10684. return this.rotateOnAxis( _yAxis, angle );
  10685. }
  10686. /**
  10687. * Rotates the 3D object around its Z axis in local space.
  10688. *
  10689. * @param {number} angle - The angle in radians.
  10690. * @return {Object3D} A reference to this instance.
  10691. */
  10692. rotateZ( angle ) {
  10693. return this.rotateOnAxis( _zAxis, angle );
  10694. }
  10695. /**
  10696. * Translate the 3D object by a distance along the given axis in local space.
  10697. *
  10698. * @param {Vector3} axis - The (normalized) axis vector.
  10699. * @param {number} distance - The distance in world units.
  10700. * @return {Object3D} A reference to this instance.
  10701. */
  10702. translateOnAxis( axis, distance ) {
  10703. // translate object by distance along axis in object space
  10704. // axis is assumed to be normalized
  10705. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10706. this.position.add( _v1$4.multiplyScalar( distance ) );
  10707. return this;
  10708. }
  10709. /**
  10710. * Translate the 3D object by a distance along its X-axis in local space.
  10711. *
  10712. * @param {number} distance - The distance in world units.
  10713. * @return {Object3D} A reference to this instance.
  10714. */
  10715. translateX( distance ) {
  10716. return this.translateOnAxis( _xAxis, distance );
  10717. }
  10718. /**
  10719. * Translate the 3D object by a distance along its Y-axis in local space.
  10720. *
  10721. * @param {number} distance - The distance in world units.
  10722. * @return {Object3D} A reference to this instance.
  10723. */
  10724. translateY( distance ) {
  10725. return this.translateOnAxis( _yAxis, distance );
  10726. }
  10727. /**
  10728. * Translate the 3D object by a distance along its Z-axis in local space.
  10729. *
  10730. * @param {number} distance - The distance in world units.
  10731. * @return {Object3D} A reference to this instance.
  10732. */
  10733. translateZ( distance ) {
  10734. return this.translateOnAxis( _zAxis, distance );
  10735. }
  10736. /**
  10737. * Converts the given vector from this 3D object's local space to world space.
  10738. *
  10739. * @param {Vector3} vector - The vector to convert.
  10740. * @return {Vector3} The converted vector.
  10741. */
  10742. localToWorld( vector ) {
  10743. this.updateWorldMatrix( true, false );
  10744. return vector.applyMatrix4( this.matrixWorld );
  10745. }
  10746. /**
  10747. * Converts the given vector from this 3D object's world space to local space.
  10748. *
  10749. * @param {Vector3} vector - The vector to convert.
  10750. * @return {Vector3} The converted vector.
  10751. */
  10752. worldToLocal( vector ) {
  10753. this.updateWorldMatrix( true, false );
  10754. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10755. }
  10756. /**
  10757. * Rotates the object to face a point in world space.
  10758. *
  10759. * This method does not support objects having non-uniformly-scaled parent(s).
  10760. *
  10761. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10762. * @param {number} [y] - The y coordinate in world space.
  10763. * @param {number} [z] - The z coordinate in world space.
  10764. */
  10765. lookAt( x, y, z ) {
  10766. // This method does not support objects having non-uniformly-scaled parent(s)
  10767. if ( x.isVector3 ) {
  10768. _target.copy( x );
  10769. } else {
  10770. _target.set( x, y, z );
  10771. }
  10772. const parent = this.parent;
  10773. this.updateWorldMatrix( true, false );
  10774. _position$3.setFromMatrixPosition( this.matrixWorld );
  10775. if ( this.isCamera || this.isLight ) {
  10776. _m1$3.lookAt( _position$3, _target, this.up );
  10777. } else {
  10778. _m1$3.lookAt( _target, _position$3, this.up );
  10779. }
  10780. this.quaternion.setFromRotationMatrix( _m1$3 );
  10781. if ( parent ) {
  10782. _m1$3.extractRotation( parent.matrixWorld );
  10783. _q1.setFromRotationMatrix( _m1$3 );
  10784. this.quaternion.premultiply( _q1.invert() );
  10785. }
  10786. }
  10787. /**
  10788. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10789. * objects may be added. Any current parent on an object passed in here will be
  10790. * removed, since an object can have at most one parent.
  10791. *
  10792. * @fires Object3D#added
  10793. * @fires Object3D#childadded
  10794. * @param {Object3D} object - The 3D object to add.
  10795. * @return {Object3D} A reference to this instance.
  10796. */
  10797. add( object ) {
  10798. if ( arguments.length > 1 ) {
  10799. for ( let i = 0; i < arguments.length; i ++ ) {
  10800. this.add( arguments[ i ] );
  10801. }
  10802. return this;
  10803. }
  10804. if ( object === this ) {
  10805. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10806. return this;
  10807. }
  10808. if ( object && object.isObject3D ) {
  10809. object.removeFromParent();
  10810. object.parent = this;
  10811. this.children.push( object );
  10812. object.dispatchEvent( _addedEvent );
  10813. _childaddedEvent.child = object;
  10814. this.dispatchEvent( _childaddedEvent );
  10815. _childaddedEvent.child = null;
  10816. } else {
  10817. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10818. }
  10819. return this;
  10820. }
  10821. /**
  10822. * Removes the given 3D object as child from this 3D object.
  10823. * An arbitrary number of objects may be removed.
  10824. *
  10825. * @fires Object3D#removed
  10826. * @fires Object3D#childremoved
  10827. * @param {Object3D} object - The 3D object to remove.
  10828. * @return {Object3D} A reference to this instance.
  10829. */
  10830. remove( object ) {
  10831. if ( arguments.length > 1 ) {
  10832. for ( let i = 0; i < arguments.length; i ++ ) {
  10833. this.remove( arguments[ i ] );
  10834. }
  10835. return this;
  10836. }
  10837. const index = this.children.indexOf( object );
  10838. if ( index !== -1 ) {
  10839. object.parent = null;
  10840. this.children.splice( index, 1 );
  10841. object.dispatchEvent( _removedEvent );
  10842. _childremovedEvent.child = object;
  10843. this.dispatchEvent( _childremovedEvent );
  10844. _childremovedEvent.child = null;
  10845. }
  10846. return this;
  10847. }
  10848. /**
  10849. * Removes this 3D object from its current parent.
  10850. *
  10851. * @fires Object3D#removed
  10852. * @fires Object3D#childremoved
  10853. * @return {Object3D} A reference to this instance.
  10854. */
  10855. removeFromParent() {
  10856. const parent = this.parent;
  10857. if ( parent !== null ) {
  10858. parent.remove( this );
  10859. }
  10860. return this;
  10861. }
  10862. /**
  10863. * Removes all child objects.
  10864. *
  10865. * @fires Object3D#removed
  10866. * @fires Object3D#childremoved
  10867. * @return {Object3D} A reference to this instance.
  10868. */
  10869. clear() {
  10870. return this.remove( ... this.children );
  10871. }
  10872. /**
  10873. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10874. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10875. *
  10876. * @fires Object3D#added
  10877. * @fires Object3D#childadded
  10878. * @param {Object3D} object - The 3D object to attach.
  10879. * @return {Object3D} A reference to this instance.
  10880. */
  10881. attach( object ) {
  10882. // adds object as a child of this, while maintaining the object's world transform
  10883. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10884. this.updateWorldMatrix( true, false );
  10885. _m1$3.copy( this.matrixWorld ).invert();
  10886. if ( object.parent !== null ) {
  10887. object.parent.updateWorldMatrix( true, false );
  10888. _m1$3.multiply( object.parent.matrixWorld );
  10889. }
  10890. object.applyMatrix4( _m1$3 );
  10891. object.removeFromParent();
  10892. object.parent = this;
  10893. this.children.push( object );
  10894. object.updateWorldMatrix( false, true );
  10895. object.dispatchEvent( _addedEvent );
  10896. _childaddedEvent.child = object;
  10897. this.dispatchEvent( _childaddedEvent );
  10898. _childaddedEvent.child = null;
  10899. return this;
  10900. }
  10901. /**
  10902. * Searches through the 3D object and its children, starting with the 3D object
  10903. * itself, and returns the first with a matching ID.
  10904. *
  10905. * @param {number} id - The id.
  10906. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10907. */
  10908. getObjectById( id ) {
  10909. return this.getObjectByProperty( 'id', id );
  10910. }
  10911. /**
  10912. * Searches through the 3D object and its children, starting with the 3D object
  10913. * itself, and returns the first with a matching name.
  10914. *
  10915. * @param {string} name - The name.
  10916. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10917. */
  10918. getObjectByName( name ) {
  10919. return this.getObjectByProperty( 'name', name );
  10920. }
  10921. /**
  10922. * Searches through the 3D object and its children, starting with the 3D object
  10923. * itself, and returns the first with a matching property value.
  10924. *
  10925. * @param {string} name - The name of the property.
  10926. * @param {any} value - The value.
  10927. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10928. */
  10929. getObjectByProperty( name, value ) {
  10930. if ( this[ name ] === value ) return this;
  10931. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10932. const child = this.children[ i ];
  10933. const object = child.getObjectByProperty( name, value );
  10934. if ( object !== undefined ) {
  10935. return object;
  10936. }
  10937. }
  10938. return undefined;
  10939. }
  10940. /**
  10941. * Searches through the 3D object and its children, starting with the 3D object
  10942. * itself, and returns all 3D objects with a matching property value.
  10943. *
  10944. * @param {string} name - The name of the property.
  10945. * @param {any} value - The value.
  10946. * @param {Array<Object3D>} result - The method stores the result in this array.
  10947. * @return {Array<Object3D>} The found 3D objects.
  10948. */
  10949. getObjectsByProperty( name, value, result = [] ) {
  10950. if ( this[ name ] === value ) result.push( this );
  10951. const children = this.children;
  10952. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10953. children[ i ].getObjectsByProperty( name, value, result );
  10954. }
  10955. return result;
  10956. }
  10957. /**
  10958. * Returns a vector representing the position of the 3D object in world space.
  10959. *
  10960. * @param {Vector3} target - The target vector the result is stored to.
  10961. * @return {Vector3} The 3D object's position in world space.
  10962. */
  10963. getWorldPosition( target ) {
  10964. this.updateWorldMatrix( true, false );
  10965. return target.setFromMatrixPosition( this.matrixWorld );
  10966. }
  10967. /**
  10968. * Returns a Quaternion representing the position of the 3D object in world space.
  10969. *
  10970. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10971. * @return {Quaternion} The 3D object's rotation in world space.
  10972. */
  10973. getWorldQuaternion( target ) {
  10974. this.updateWorldMatrix( true, false );
  10975. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10976. return target;
  10977. }
  10978. /**
  10979. * Returns a vector representing the scale of the 3D object in world space.
  10980. *
  10981. * @param {Vector3} target - The target vector the result is stored to.
  10982. * @return {Vector3} The 3D object's scale in world space.
  10983. */
  10984. getWorldScale( target ) {
  10985. this.updateWorldMatrix( true, false );
  10986. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10987. return target;
  10988. }
  10989. /**
  10990. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10991. *
  10992. * @param {Vector3} target - The target vector the result is stored to.
  10993. * @return {Vector3} The 3D object's direction in world space.
  10994. */
  10995. getWorldDirection( target ) {
  10996. this.updateWorldMatrix( true, false );
  10997. const e = this.matrixWorld.elements;
  10998. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10999. }
  11000. /**
  11001. * Abstract method to get intersections between a casted ray and this
  11002. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  11003. * implement this method in order to use raycasting.
  11004. *
  11005. * @abstract
  11006. * @param {Raycaster} raycaster - The raycaster.
  11007. * @param {Array<Object>} intersects - An array holding the result of the method.
  11008. */
  11009. raycast( /* raycaster, intersects */ ) {}
  11010. /**
  11011. * Executes the callback on this 3D object and all descendants.
  11012. *
  11013. * Note: Modifying the scene graph inside the callback is discouraged.
  11014. *
  11015. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11016. */
  11017. traverse( callback ) {
  11018. callback( this );
  11019. const children = this.children;
  11020. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11021. children[ i ].traverse( callback );
  11022. }
  11023. }
  11024. /**
  11025. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  11026. * Descendants of invisible 3D objects are not traversed.
  11027. *
  11028. * Note: Modifying the scene graph inside the callback is discouraged.
  11029. *
  11030. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11031. */
  11032. traverseVisible( callback ) {
  11033. if ( this.visible === false ) return;
  11034. callback( this );
  11035. const children = this.children;
  11036. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11037. children[ i ].traverseVisible( callback );
  11038. }
  11039. }
  11040. /**
  11041. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  11042. *
  11043. * Note: Modifying the scene graph inside the callback is discouraged.
  11044. *
  11045. * @param {Function} callback - A callback function that allows to process the current 3D object.
  11046. */
  11047. traverseAncestors( callback ) {
  11048. const parent = this.parent;
  11049. if ( parent !== null ) {
  11050. callback( parent );
  11051. parent.traverseAncestors( callback );
  11052. }
  11053. }
  11054. /**
  11055. * Updates the transformation matrix in local space by computing it from the current
  11056. * position, rotation and scale values.
  11057. */
  11058. updateMatrix() {
  11059. this.matrix.compose( this.position, this.quaternion, this.scale );
  11060. const pivot = this.pivot;
  11061. if ( pivot !== null ) {
  11062. const px = pivot.x, py = pivot.y, pz = pivot.z;
  11063. const te = this.matrix.elements;
  11064. te[ 12 ] += px - te[ 0 ] * px - te[ 4 ] * py - te[ 8 ] * pz;
  11065. te[ 13 ] += py - te[ 1 ] * px - te[ 5 ] * py - te[ 9 ] * pz;
  11066. te[ 14 ] += pz - te[ 2 ] * px - te[ 6 ] * py - te[ 10 ] * pz;
  11067. }
  11068. this.matrixWorldNeedsUpdate = true;
  11069. }
  11070. /**
  11071. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  11072. *
  11073. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  11074. * local space. The computation of the local and world matrix can be controlled with the
  11075. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  11076. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  11077. *
  11078. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  11079. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  11080. */
  11081. updateMatrixWorld( force ) {
  11082. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11083. if ( this.matrixWorldNeedsUpdate || force ) {
  11084. if ( this.matrixWorldAutoUpdate === true ) {
  11085. if ( this.parent === null ) {
  11086. this.matrixWorld.copy( this.matrix );
  11087. } else {
  11088. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11089. }
  11090. }
  11091. this.matrixWorldNeedsUpdate = false;
  11092. force = true;
  11093. }
  11094. // make sure descendants are updated if required
  11095. const children = this.children;
  11096. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11097. const child = children[ i ];
  11098. child.updateMatrixWorld( force );
  11099. }
  11100. }
  11101. /**
  11102. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  11103. * update of ancestor and descendant nodes.
  11104. *
  11105. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  11106. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  11107. */
  11108. updateWorldMatrix( updateParents, updateChildren ) {
  11109. const parent = this.parent;
  11110. if ( updateParents === true && parent !== null ) {
  11111. parent.updateWorldMatrix( true, false );
  11112. }
  11113. if ( this.matrixAutoUpdate ) this.updateMatrix();
  11114. if ( this.matrixWorldAutoUpdate === true ) {
  11115. if ( this.parent === null ) {
  11116. this.matrixWorld.copy( this.matrix );
  11117. } else {
  11118. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  11119. }
  11120. }
  11121. // make sure descendants are updated
  11122. if ( updateChildren === true ) {
  11123. const children = this.children;
  11124. for ( let i = 0, l = children.length; i < l; i ++ ) {
  11125. const child = children[ i ];
  11126. child.updateWorldMatrix( false, true );
  11127. }
  11128. }
  11129. }
  11130. /**
  11131. * Serializes the 3D object into JSON.
  11132. *
  11133. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  11134. * @return {Object} A JSON object representing the serialized 3D object.
  11135. * @see {@link ObjectLoader#parse}
  11136. */
  11137. toJSON( meta ) {
  11138. // meta is a string when called from JSON.stringify
  11139. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  11140. const output = {};
  11141. // meta is a hash used to collect geometries, materials.
  11142. // not providing it implies that this is the root object
  11143. // being serialized.
  11144. if ( isRootObject ) {
  11145. // initialize meta obj
  11146. meta = {
  11147. geometries: {},
  11148. materials: {},
  11149. textures: {},
  11150. images: {},
  11151. shapes: {},
  11152. skeletons: {},
  11153. animations: {},
  11154. nodes: {}
  11155. };
  11156. output.metadata = {
  11157. version: 4.7,
  11158. type: 'Object',
  11159. generator: 'Object3D.toJSON'
  11160. };
  11161. }
  11162. // standard Object3D serialization
  11163. const object = {};
  11164. object.uuid = this.uuid;
  11165. object.type = this.type;
  11166. if ( this.name !== '' ) object.name = this.name;
  11167. if ( this.castShadow === true ) object.castShadow = true;
  11168. if ( this.receiveShadow === true ) object.receiveShadow = true;
  11169. if ( this.visible === false ) object.visible = false;
  11170. if ( this.frustumCulled === false ) object.frustumCulled = false;
  11171. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  11172. if ( this.static !== false ) object.static = this.static;
  11173. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  11174. object.layers = this.layers.mask;
  11175. object.matrix = this.matrix.toArray();
  11176. object.up = this.up.toArray();
  11177. if ( this.pivot !== null ) object.pivot = this.pivot.toArray();
  11178. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11179. // object specific properties
  11180. if ( this.isInstancedMesh ) {
  11181. object.type = 'InstancedMesh';
  11182. object.count = this.count;
  11183. object.instanceMatrix = this.instanceMatrix.toJSON();
  11184. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11185. }
  11186. if ( this.isBatchedMesh ) {
  11187. object.type = 'BatchedMesh';
  11188. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11189. object.sortObjects = this.sortObjects;
  11190. object.drawRanges = this._drawRanges;
  11191. object.reservedRanges = this._reservedRanges;
  11192. object.geometryInfo = this._geometryInfo.map( info => ( {
  11193. ...info,
  11194. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11195. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11196. } ) );
  11197. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11198. object.availableInstanceIds = this._availableInstanceIds.slice();
  11199. object.availableGeometryIds = this._availableGeometryIds.slice();
  11200. object.nextIndexStart = this._nextIndexStart;
  11201. object.nextVertexStart = this._nextVertexStart;
  11202. object.geometryCount = this._geometryCount;
  11203. object.maxInstanceCount = this._maxInstanceCount;
  11204. object.maxVertexCount = this._maxVertexCount;
  11205. object.maxIndexCount = this._maxIndexCount;
  11206. object.geometryInitialized = this._geometryInitialized;
  11207. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11208. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11209. if ( this._colorsTexture !== null ) {
  11210. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11211. }
  11212. if ( this.boundingSphere !== null ) {
  11213. object.boundingSphere = this.boundingSphere.toJSON();
  11214. }
  11215. if ( this.boundingBox !== null ) {
  11216. object.boundingBox = this.boundingBox.toJSON();
  11217. }
  11218. }
  11219. //
  11220. function serialize( library, element ) {
  11221. if ( library[ element.uuid ] === undefined ) {
  11222. library[ element.uuid ] = element.toJSON( meta );
  11223. }
  11224. return element.uuid;
  11225. }
  11226. if ( this.isScene ) {
  11227. if ( this.background ) {
  11228. if ( this.background.isColor ) {
  11229. object.background = this.background.toJSON();
  11230. } else if ( this.background.isTexture ) {
  11231. object.background = this.background.toJSON( meta ).uuid;
  11232. }
  11233. }
  11234. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11235. object.environment = this.environment.toJSON( meta ).uuid;
  11236. }
  11237. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11238. object.geometry = serialize( meta.geometries, this.geometry );
  11239. const parameters = this.geometry.parameters;
  11240. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11241. const shapes = parameters.shapes;
  11242. if ( Array.isArray( shapes ) ) {
  11243. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11244. const shape = shapes[ i ];
  11245. serialize( meta.shapes, shape );
  11246. }
  11247. } else {
  11248. serialize( meta.shapes, shapes );
  11249. }
  11250. }
  11251. }
  11252. if ( this.isSkinnedMesh ) {
  11253. object.bindMode = this.bindMode;
  11254. object.bindMatrix = this.bindMatrix.toArray();
  11255. if ( this.skeleton !== undefined ) {
  11256. serialize( meta.skeletons, this.skeleton );
  11257. object.skeleton = this.skeleton.uuid;
  11258. }
  11259. }
  11260. if ( this.material !== undefined ) {
  11261. if ( Array.isArray( this.material ) ) {
  11262. const uuids = [];
  11263. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11264. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11265. }
  11266. object.material = uuids;
  11267. } else {
  11268. object.material = serialize( meta.materials, this.material );
  11269. }
  11270. }
  11271. //
  11272. if ( this.children.length > 0 ) {
  11273. object.children = [];
  11274. for ( let i = 0; i < this.children.length; i ++ ) {
  11275. object.children.push( this.children[ i ].toJSON( meta ).object );
  11276. }
  11277. }
  11278. //
  11279. if ( this.animations.length > 0 ) {
  11280. object.animations = [];
  11281. for ( let i = 0; i < this.animations.length; i ++ ) {
  11282. const animation = this.animations[ i ];
  11283. object.animations.push( serialize( meta.animations, animation ) );
  11284. }
  11285. }
  11286. if ( isRootObject ) {
  11287. const geometries = extractFromCache( meta.geometries );
  11288. const materials = extractFromCache( meta.materials );
  11289. const textures = extractFromCache( meta.textures );
  11290. const images = extractFromCache( meta.images );
  11291. const shapes = extractFromCache( meta.shapes );
  11292. const skeletons = extractFromCache( meta.skeletons );
  11293. const animations = extractFromCache( meta.animations );
  11294. const nodes = extractFromCache( meta.nodes );
  11295. if ( geometries.length > 0 ) output.geometries = geometries;
  11296. if ( materials.length > 0 ) output.materials = materials;
  11297. if ( textures.length > 0 ) output.textures = textures;
  11298. if ( images.length > 0 ) output.images = images;
  11299. if ( shapes.length > 0 ) output.shapes = shapes;
  11300. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11301. if ( animations.length > 0 ) output.animations = animations;
  11302. if ( nodes.length > 0 ) output.nodes = nodes;
  11303. }
  11304. output.object = object;
  11305. return output;
  11306. // extract data from the cache hash
  11307. // remove metadata on each item
  11308. // and return as array
  11309. function extractFromCache( cache ) {
  11310. const values = [];
  11311. for ( const key in cache ) {
  11312. const data = cache[ key ];
  11313. delete data.metadata;
  11314. values.push( data );
  11315. }
  11316. return values;
  11317. }
  11318. }
  11319. /**
  11320. * Returns a new 3D object with copied values from this instance.
  11321. *
  11322. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11323. * @return {Object3D} A clone of this instance.
  11324. */
  11325. clone( recursive ) {
  11326. return new this.constructor().copy( this, recursive );
  11327. }
  11328. /**
  11329. * Copies the values of the given 3D object to this instance.
  11330. *
  11331. * @param {Object3D} source - The 3D object to copy.
  11332. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11333. * @return {Object3D} A reference to this instance.
  11334. */
  11335. copy( source, recursive = true ) {
  11336. this.name = source.name;
  11337. this.up.copy( source.up );
  11338. this.position.copy( source.position );
  11339. this.rotation.order = source.rotation.order;
  11340. this.quaternion.copy( source.quaternion );
  11341. this.scale.copy( source.scale );
  11342. if ( source.pivot !== null ) {
  11343. this.pivot = source.pivot.clone();
  11344. }
  11345. this.matrix.copy( source.matrix );
  11346. this.matrixWorld.copy( source.matrixWorld );
  11347. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11348. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11349. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11350. this.layers.mask = source.layers.mask;
  11351. this.visible = source.visible;
  11352. this.castShadow = source.castShadow;
  11353. this.receiveShadow = source.receiveShadow;
  11354. this.frustumCulled = source.frustumCulled;
  11355. this.renderOrder = source.renderOrder;
  11356. this.static = source.static;
  11357. this.animations = source.animations.slice();
  11358. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11359. if ( recursive === true ) {
  11360. for ( let i = 0; i < source.children.length; i ++ ) {
  11361. const child = source.children[ i ];
  11362. this.add( child.clone() );
  11363. }
  11364. }
  11365. return this;
  11366. }
  11367. }
  11368. /**
  11369. * The default up direction for objects, also used as the default
  11370. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11371. *
  11372. * @static
  11373. * @type {Vector3}
  11374. * @default (0,1,0)
  11375. */
  11376. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11377. /**
  11378. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11379. * newly created 3D objects.
  11380. *
  11381. * @static
  11382. * @type {boolean}
  11383. * @default true
  11384. */
  11385. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11386. /**
  11387. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11388. * newly created 3D objects.
  11389. *
  11390. * @static
  11391. * @type {boolean}
  11392. * @default true
  11393. */
  11394. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11395. const _v0$2 = /*@__PURE__*/ new Vector3();
  11396. const _v1$3 = /*@__PURE__*/ new Vector3();
  11397. const _v2$2 = /*@__PURE__*/ new Vector3();
  11398. const _v3$2 = /*@__PURE__*/ new Vector3();
  11399. const _vab = /*@__PURE__*/ new Vector3();
  11400. const _vac = /*@__PURE__*/ new Vector3();
  11401. const _vbc = /*@__PURE__*/ new Vector3();
  11402. const _vap = /*@__PURE__*/ new Vector3();
  11403. const _vbp = /*@__PURE__*/ new Vector3();
  11404. const _vcp = /*@__PURE__*/ new Vector3();
  11405. const _v40 = /*@__PURE__*/ new Vector4();
  11406. const _v41 = /*@__PURE__*/ new Vector4();
  11407. const _v42 = /*@__PURE__*/ new Vector4();
  11408. /**
  11409. * A geometric triangle as defined by three vectors representing its three corners.
  11410. */
  11411. class Triangle {
  11412. /**
  11413. * Constructs a new triangle.
  11414. *
  11415. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11416. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11417. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11418. */
  11419. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11420. /**
  11421. * The first corner of the triangle.
  11422. *
  11423. * @type {Vector3}
  11424. */
  11425. this.a = a;
  11426. /**
  11427. * The second corner of the triangle.
  11428. *
  11429. * @type {Vector3}
  11430. */
  11431. this.b = b;
  11432. /**
  11433. * The third corner of the triangle.
  11434. *
  11435. * @type {Vector3}
  11436. */
  11437. this.c = c;
  11438. }
  11439. /**
  11440. * Computes the normal vector of a triangle.
  11441. *
  11442. * @param {Vector3} a - The first corner of the triangle.
  11443. * @param {Vector3} b - The second corner of the triangle.
  11444. * @param {Vector3} c - The third corner of the triangle.
  11445. * @param {Vector3} target - The target vector that is used to store the method's result.
  11446. * @return {Vector3} The triangle's normal.
  11447. */
  11448. static getNormal( a, b, c, target ) {
  11449. target.subVectors( c, b );
  11450. _v0$2.subVectors( a, b );
  11451. target.cross( _v0$2 );
  11452. const targetLengthSq = target.lengthSq();
  11453. if ( targetLengthSq > 0 ) {
  11454. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11455. }
  11456. return target.set( 0, 0, 0 );
  11457. }
  11458. /**
  11459. * Computes a barycentric coordinates from the given vector.
  11460. * Returns `null` if the triangle is degenerate.
  11461. *
  11462. * @param {Vector3} point - A point in 3D space.
  11463. * @param {Vector3} a - The first corner of the triangle.
  11464. * @param {Vector3} b - The second corner of the triangle.
  11465. * @param {Vector3} c - The third corner of the triangle.
  11466. * @param {Vector3} target - The target vector that is used to store the method's result.
  11467. * @return {?Vector3} The barycentric coordinates for the given point
  11468. */
  11469. static getBarycoord( point, a, b, c, target ) {
  11470. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11471. _v0$2.subVectors( c, a );
  11472. _v1$3.subVectors( b, a );
  11473. _v2$2.subVectors( point, a );
  11474. const dot00 = _v0$2.dot( _v0$2 );
  11475. const dot01 = _v0$2.dot( _v1$3 );
  11476. const dot02 = _v0$2.dot( _v2$2 );
  11477. const dot11 = _v1$3.dot( _v1$3 );
  11478. const dot12 = _v1$3.dot( _v2$2 );
  11479. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11480. // collinear or singular triangle
  11481. if ( denom === 0 ) {
  11482. target.set( 0, 0, 0 );
  11483. return null;
  11484. }
  11485. const invDenom = 1 / denom;
  11486. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11487. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11488. // barycentric coordinates must always sum to 1
  11489. return target.set( 1 - u - v, v, u );
  11490. }
  11491. /**
  11492. * Returns `true` if the given point, when projected onto the plane of the
  11493. * triangle, lies within the triangle.
  11494. *
  11495. * @param {Vector3} point - The point in 3D space to test.
  11496. * @param {Vector3} a - The first corner of the triangle.
  11497. * @param {Vector3} b - The second corner of the triangle.
  11498. * @param {Vector3} c - The third corner of the triangle.
  11499. * @return {boolean} Whether the given point, when projected onto the plane of the
  11500. * triangle, lies within the triangle or not.
  11501. */
  11502. static containsPoint( point, a, b, c ) {
  11503. // if the triangle is degenerate then we can't contain a point
  11504. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11505. return false;
  11506. }
  11507. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11508. }
  11509. /**
  11510. * Computes the value barycentrically interpolated for the given point on the
  11511. * triangle. Returns `null` if the triangle is degenerate.
  11512. *
  11513. * @param {Vector3} point - Position of interpolated point.
  11514. * @param {Vector3} p1 - The first corner of the triangle.
  11515. * @param {Vector3} p2 - The second corner of the triangle.
  11516. * @param {Vector3} p3 - The third corner of the triangle.
  11517. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11518. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11519. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11520. * @param {Vector3} target - The target vector that is used to store the method's result.
  11521. * @return {?Vector3} The interpolated value.
  11522. */
  11523. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11524. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11525. target.x = 0;
  11526. target.y = 0;
  11527. if ( 'z' in target ) target.z = 0;
  11528. if ( 'w' in target ) target.w = 0;
  11529. return null;
  11530. }
  11531. target.setScalar( 0 );
  11532. target.addScaledVector( v1, _v3$2.x );
  11533. target.addScaledVector( v2, _v3$2.y );
  11534. target.addScaledVector( v3, _v3$2.z );
  11535. return target;
  11536. }
  11537. /**
  11538. * Computes the value barycentrically interpolated for the given attribute and indices.
  11539. *
  11540. * @param {BufferAttribute} attr - The attribute to interpolate.
  11541. * @param {number} i1 - Index of first vertex.
  11542. * @param {number} i2 - Index of second vertex.
  11543. * @param {number} i3 - Index of third vertex.
  11544. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11545. * @param {Vector3} target - The target vector that is used to store the method's result.
  11546. * @return {Vector3} The interpolated attribute value.
  11547. */
  11548. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11549. _v40.setScalar( 0 );
  11550. _v41.setScalar( 0 );
  11551. _v42.setScalar( 0 );
  11552. _v40.fromBufferAttribute( attr, i1 );
  11553. _v41.fromBufferAttribute( attr, i2 );
  11554. _v42.fromBufferAttribute( attr, i3 );
  11555. target.setScalar( 0 );
  11556. target.addScaledVector( _v40, barycoord.x );
  11557. target.addScaledVector( _v41, barycoord.y );
  11558. target.addScaledVector( _v42, barycoord.z );
  11559. return target;
  11560. }
  11561. /**
  11562. * Returns `true` if the triangle is oriented towards the given direction.
  11563. *
  11564. * @param {Vector3} a - The first corner of the triangle.
  11565. * @param {Vector3} b - The second corner of the triangle.
  11566. * @param {Vector3} c - The third corner of the triangle.
  11567. * @param {Vector3} direction - The (normalized) direction vector.
  11568. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11569. */
  11570. static isFrontFacing( a, b, c, direction ) {
  11571. _v0$2.subVectors( c, b );
  11572. _v1$3.subVectors( a, b );
  11573. // strictly front facing
  11574. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11575. }
  11576. /**
  11577. * Sets the triangle's vertices by copying the given values.
  11578. *
  11579. * @param {Vector3} a - The first corner of the triangle.
  11580. * @param {Vector3} b - The second corner of the triangle.
  11581. * @param {Vector3} c - The third corner of the triangle.
  11582. * @return {Triangle} A reference to this triangle.
  11583. */
  11584. set( a, b, c ) {
  11585. this.a.copy( a );
  11586. this.b.copy( b );
  11587. this.c.copy( c );
  11588. return this;
  11589. }
  11590. /**
  11591. * Sets the triangle's vertices by copying the given array values.
  11592. *
  11593. * @param {Array<Vector3>} points - An array with 3D points.
  11594. * @param {number} i0 - The array index representing the first corner of the triangle.
  11595. * @param {number} i1 - The array index representing the second corner of the triangle.
  11596. * @param {number} i2 - The array index representing the third corner of the triangle.
  11597. * @return {Triangle} A reference to this triangle.
  11598. */
  11599. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11600. this.a.copy( points[ i0 ] );
  11601. this.b.copy( points[ i1 ] );
  11602. this.c.copy( points[ i2 ] );
  11603. return this;
  11604. }
  11605. /**
  11606. * Sets the triangle's vertices by copying the given attribute values.
  11607. *
  11608. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11609. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11610. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11611. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11612. * @return {Triangle} A reference to this triangle.
  11613. */
  11614. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11615. this.a.fromBufferAttribute( attribute, i0 );
  11616. this.b.fromBufferAttribute( attribute, i1 );
  11617. this.c.fromBufferAttribute( attribute, i2 );
  11618. return this;
  11619. }
  11620. /**
  11621. * Returns a new triangle with copied values from this instance.
  11622. *
  11623. * @return {Triangle} A clone of this instance.
  11624. */
  11625. clone() {
  11626. return new this.constructor().copy( this );
  11627. }
  11628. /**
  11629. * Copies the values of the given triangle to this instance.
  11630. *
  11631. * @param {Triangle} triangle - The triangle to copy.
  11632. * @return {Triangle} A reference to this triangle.
  11633. */
  11634. copy( triangle ) {
  11635. this.a.copy( triangle.a );
  11636. this.b.copy( triangle.b );
  11637. this.c.copy( triangle.c );
  11638. return this;
  11639. }
  11640. /**
  11641. * Computes the area of the triangle.
  11642. *
  11643. * @return {number} The triangle's area.
  11644. */
  11645. getArea() {
  11646. _v0$2.subVectors( this.c, this.b );
  11647. _v1$3.subVectors( this.a, this.b );
  11648. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11649. }
  11650. /**
  11651. * Computes the midpoint of the triangle.
  11652. *
  11653. * @param {Vector3} target - The target vector that is used to store the method's result.
  11654. * @return {Vector3} The triangle's midpoint.
  11655. */
  11656. getMidpoint( target ) {
  11657. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11658. }
  11659. /**
  11660. * Computes the normal of the triangle.
  11661. *
  11662. * @param {Vector3} target - The target vector that is used to store the method's result.
  11663. * @return {Vector3} The triangle's normal.
  11664. */
  11665. getNormal( target ) {
  11666. return Triangle.getNormal( this.a, this.b, this.c, target );
  11667. }
  11668. /**
  11669. * Computes a plane the triangle lies within.
  11670. *
  11671. * @param {Plane} target - The target vector that is used to store the method's result.
  11672. * @return {Plane} The plane the triangle lies within.
  11673. */
  11674. getPlane( target ) {
  11675. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11676. }
  11677. /**
  11678. * Computes a barycentric coordinates from the given vector.
  11679. * Returns `null` if the triangle is degenerate.
  11680. *
  11681. * @param {Vector3} point - A point in 3D space.
  11682. * @param {Vector3} target - The target vector that is used to store the method's result.
  11683. * @return {?Vector3} The barycentric coordinates for the given point
  11684. */
  11685. getBarycoord( point, target ) {
  11686. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11687. }
  11688. /**
  11689. * Computes the value barycentrically interpolated for the given point on the
  11690. * triangle. Returns `null` if the triangle is degenerate.
  11691. *
  11692. * @param {Vector3} point - Position of interpolated point.
  11693. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11694. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11695. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11696. * @param {Vector3} target - The target vector that is used to store the method's result.
  11697. * @return {?Vector3} The interpolated value.
  11698. */
  11699. getInterpolation( point, v1, v2, v3, target ) {
  11700. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11701. }
  11702. /**
  11703. * Returns `true` if the given point, when projected onto the plane of the
  11704. * triangle, lies within the triangle.
  11705. *
  11706. * @param {Vector3} point - The point in 3D space to test.
  11707. * @return {boolean} Whether the given point, when projected onto the plane of the
  11708. * triangle, lies within the triangle or not.
  11709. */
  11710. containsPoint( point ) {
  11711. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11712. }
  11713. /**
  11714. * Returns `true` if the triangle is oriented towards the given direction.
  11715. *
  11716. * @param {Vector3} direction - The (normalized) direction vector.
  11717. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11718. */
  11719. isFrontFacing( direction ) {
  11720. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11721. }
  11722. /**
  11723. * Returns `true` if this triangle intersects with the given box.
  11724. *
  11725. * @param {Box3} box - The box to intersect.
  11726. * @return {boolean} Whether this triangle intersects with the given box or not.
  11727. */
  11728. intersectsBox( box ) {
  11729. return box.intersectsTriangle( this );
  11730. }
  11731. /**
  11732. * Returns the closest point on the triangle to the given point.
  11733. *
  11734. * @param {Vector3} p - The point to compute the closest point for.
  11735. * @param {Vector3} target - The target vector that is used to store the method's result.
  11736. * @return {Vector3} The closest point on the triangle.
  11737. */
  11738. closestPointToPoint( p, target ) {
  11739. const a = this.a, b = this.b, c = this.c;
  11740. let v, w;
  11741. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11742. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11743. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11744. // basically, we're distinguishing which of the voronoi regions of the triangle
  11745. // the point lies in with the minimum amount of redundant computation.
  11746. _vab.subVectors( b, a );
  11747. _vac.subVectors( c, a );
  11748. _vap.subVectors( p, a );
  11749. const d1 = _vab.dot( _vap );
  11750. const d2 = _vac.dot( _vap );
  11751. if ( d1 <= 0 && d2 <= 0 ) {
  11752. // vertex region of A; barycentric coords (1, 0, 0)
  11753. return target.copy( a );
  11754. }
  11755. _vbp.subVectors( p, b );
  11756. const d3 = _vab.dot( _vbp );
  11757. const d4 = _vac.dot( _vbp );
  11758. if ( d3 >= 0 && d4 <= d3 ) {
  11759. // vertex region of B; barycentric coords (0, 1, 0)
  11760. return target.copy( b );
  11761. }
  11762. const vc = d1 * d4 - d3 * d2;
  11763. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11764. v = d1 / ( d1 - d3 );
  11765. // edge region of AB; barycentric coords (1-v, v, 0)
  11766. return target.copy( a ).addScaledVector( _vab, v );
  11767. }
  11768. _vcp.subVectors( p, c );
  11769. const d5 = _vab.dot( _vcp );
  11770. const d6 = _vac.dot( _vcp );
  11771. if ( d6 >= 0 && d5 <= d6 ) {
  11772. // vertex region of C; barycentric coords (0, 0, 1)
  11773. return target.copy( c );
  11774. }
  11775. const vb = d5 * d2 - d1 * d6;
  11776. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11777. w = d2 / ( d2 - d6 );
  11778. // edge region of AC; barycentric coords (1-w, 0, w)
  11779. return target.copy( a ).addScaledVector( _vac, w );
  11780. }
  11781. const va = d3 * d6 - d5 * d4;
  11782. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11783. _vbc.subVectors( c, b );
  11784. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11785. // edge region of BC; barycentric coords (0, 1-w, w)
  11786. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11787. }
  11788. // face region
  11789. const denom = 1 / ( va + vb + vc );
  11790. // u = va * denom
  11791. v = vb * denom;
  11792. w = vc * denom;
  11793. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11794. }
  11795. /**
  11796. * Returns `true` if this triangle is equal with the given one.
  11797. *
  11798. * @param {Triangle} triangle - The triangle to test for equality.
  11799. * @return {boolean} Whether this triangle is equal with the given one.
  11800. */
  11801. equals( triangle ) {
  11802. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11803. }
  11804. }
  11805. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11806. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11807. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11808. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11809. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11810. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11811. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11812. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11813. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11814. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11815. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11816. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11817. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11818. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11819. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11820. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11821. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11822. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11823. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11824. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11825. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11826. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11827. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11828. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11829. const _hslA = { h: 0, s: 0, l: 0 };
  11830. const _hslB = { h: 0, s: 0, l: 0 };
  11831. function hue2rgb( p, q, t ) {
  11832. if ( t < 0 ) t += 1;
  11833. if ( t > 1 ) t -= 1;
  11834. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11835. if ( t < 1 / 2 ) return q;
  11836. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11837. return p;
  11838. }
  11839. /**
  11840. * A Color instance is represented by RGB components in the linear <i>working
  11841. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11842. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11843. * strings) are converted to the working color space automatically.
  11844. *
  11845. * ```js
  11846. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11847. * const color = new THREE.Color().setHex( 0x112233 );
  11848. * ```
  11849. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11850. * ```js
  11851. * // assumed already LinearSRGBColorSpace; no conversion
  11852. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11853. *
  11854. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11855. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11856. * ```
  11857. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11858. * see <i>Color management</i>. Iterating through a Color instance will yield
  11859. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11860. * in any of the following ways:
  11861. * ```js
  11862. * //empty constructor - will default white
  11863. * const color1 = new THREE.Color();
  11864. *
  11865. * //Hexadecimal color (recommended)
  11866. * const color2 = new THREE.Color( 0xff0000 );
  11867. *
  11868. * //RGB string
  11869. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11870. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11871. *
  11872. * //X11 color name - all 140 color names are supported.
  11873. * //Note the lack of CamelCase in the name
  11874. * const color5 = new THREE.Color( 'skyblue' );
  11875. * //HSL string
  11876. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11877. *
  11878. * //Separate RGB values between 0 and 1
  11879. * const color7 = new THREE.Color( 1, 0, 0 );
  11880. * ```
  11881. */
  11882. class Color {
  11883. /**
  11884. * Constructs a new color.
  11885. *
  11886. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11887. * and that method is used throughout the rest of the documentation.
  11888. *
  11889. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11890. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11891. * @param {number} [g] - The green component.
  11892. * @param {number} [b] - The blue component.
  11893. */
  11894. constructor( r, g, b ) {
  11895. /**
  11896. * This flag can be used for type testing.
  11897. *
  11898. * @type {boolean}
  11899. * @readonly
  11900. * @default true
  11901. */
  11902. this.isColor = true;
  11903. /**
  11904. * The red component.
  11905. *
  11906. * @type {number}
  11907. * @default 1
  11908. */
  11909. this.r = 1;
  11910. /**
  11911. * The green component.
  11912. *
  11913. * @type {number}
  11914. * @default 1
  11915. */
  11916. this.g = 1;
  11917. /**
  11918. * The blue component.
  11919. *
  11920. * @type {number}
  11921. * @default 1
  11922. */
  11923. this.b = 1;
  11924. return this.set( r, g, b );
  11925. }
  11926. /**
  11927. * Sets the colors's components from the given values.
  11928. *
  11929. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11930. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11931. * @param {number} [g] - The green component.
  11932. * @param {number} [b] - The blue component.
  11933. * @return {Color} A reference to this color.
  11934. */
  11935. set( r, g, b ) {
  11936. if ( g === undefined && b === undefined ) {
  11937. // r is THREE.Color, hex or string
  11938. const value = r;
  11939. if ( value && value.isColor ) {
  11940. this.copy( value );
  11941. } else if ( typeof value === 'number' ) {
  11942. this.setHex( value );
  11943. } else if ( typeof value === 'string' ) {
  11944. this.setStyle( value );
  11945. }
  11946. } else {
  11947. this.setRGB( r, g, b );
  11948. }
  11949. return this;
  11950. }
  11951. /**
  11952. * Sets the colors's components to the given scalar value.
  11953. *
  11954. * @param {number} scalar - The scalar value.
  11955. * @return {Color} A reference to this color.
  11956. */
  11957. setScalar( scalar ) {
  11958. this.r = scalar;
  11959. this.g = scalar;
  11960. this.b = scalar;
  11961. return this;
  11962. }
  11963. /**
  11964. * Sets this color from a hexadecimal value.
  11965. *
  11966. * @param {number} hex - The hexadecimal value.
  11967. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11968. * @return {Color} A reference to this color.
  11969. */
  11970. setHex( hex, colorSpace = SRGBColorSpace ) {
  11971. hex = Math.floor( hex );
  11972. this.r = ( hex >> 16 & 255 ) / 255;
  11973. this.g = ( hex >> 8 & 255 ) / 255;
  11974. this.b = ( hex & 255 ) / 255;
  11975. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11976. return this;
  11977. }
  11978. /**
  11979. * Sets this color from RGB values.
  11980. *
  11981. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11982. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11983. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11984. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11985. * @return {Color} A reference to this color.
  11986. */
  11987. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11988. this.r = r;
  11989. this.g = g;
  11990. this.b = b;
  11991. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11992. return this;
  11993. }
  11994. /**
  11995. * Sets this color from RGB values.
  11996. *
  11997. * @param {number} h - Hue value between `0.0` and `1.0`.
  11998. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11999. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12000. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12001. * @return {Color} A reference to this color.
  12002. */
  12003. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  12004. // h,s,l ranges are in 0.0 - 1.0
  12005. h = euclideanModulo( h, 1 );
  12006. s = clamp( s, 0, 1 );
  12007. l = clamp( l, 0, 1 );
  12008. if ( s === 0 ) {
  12009. this.r = this.g = this.b = l;
  12010. } else {
  12011. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  12012. const q = ( 2 * l ) - p;
  12013. this.r = hue2rgb( q, p, h + 1 / 3 );
  12014. this.g = hue2rgb( q, p, h );
  12015. this.b = hue2rgb( q, p, h - 1 / 3 );
  12016. }
  12017. ColorManagement.colorSpaceToWorking( this, colorSpace );
  12018. return this;
  12019. }
  12020. /**
  12021. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  12022. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  12023. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  12024. * all 140 color names are supported).
  12025. *
  12026. * @param {string} style - Color as a CSS-style string.
  12027. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12028. * @return {Color} A reference to this color.
  12029. */
  12030. setStyle( style, colorSpace = SRGBColorSpace ) {
  12031. function handleAlpha( string ) {
  12032. if ( string === undefined ) return;
  12033. if ( parseFloat( string ) < 1 ) {
  12034. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  12035. }
  12036. }
  12037. let m;
  12038. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  12039. // rgb / hsl
  12040. let color;
  12041. const name = m[ 1 ];
  12042. const components = m[ 2 ];
  12043. switch ( name ) {
  12044. case 'rgb':
  12045. case 'rgba':
  12046. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12047. // rgb(255,0,0) rgba(255,0,0,0.5)
  12048. handleAlpha( color[ 4 ] );
  12049. return this.setRGB(
  12050. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  12051. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  12052. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  12053. colorSpace
  12054. );
  12055. }
  12056. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12057. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  12058. handleAlpha( color[ 4 ] );
  12059. return this.setRGB(
  12060. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  12061. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  12062. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  12063. colorSpace
  12064. );
  12065. }
  12066. break;
  12067. case 'hsl':
  12068. case 'hsla':
  12069. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  12070. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  12071. handleAlpha( color[ 4 ] );
  12072. return this.setHSL(
  12073. parseFloat( color[ 1 ] ) / 360,
  12074. parseFloat( color[ 2 ] ) / 100,
  12075. parseFloat( color[ 3 ] ) / 100,
  12076. colorSpace
  12077. );
  12078. }
  12079. break;
  12080. default:
  12081. warn( 'Color: Unknown color model ' + style );
  12082. }
  12083. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  12084. // hex color
  12085. const hex = m[ 1 ];
  12086. const size = hex.length;
  12087. if ( size === 3 ) {
  12088. // #ff0
  12089. return this.setRGB(
  12090. parseInt( hex.charAt( 0 ), 16 ) / 15,
  12091. parseInt( hex.charAt( 1 ), 16 ) / 15,
  12092. parseInt( hex.charAt( 2 ), 16 ) / 15,
  12093. colorSpace
  12094. );
  12095. } else if ( size === 6 ) {
  12096. // #ff0000
  12097. return this.setHex( parseInt( hex, 16 ), colorSpace );
  12098. } else {
  12099. warn( 'Color: Invalid hex color ' + style );
  12100. }
  12101. } else if ( style && style.length > 0 ) {
  12102. return this.setColorName( style, colorSpace );
  12103. }
  12104. return this;
  12105. }
  12106. /**
  12107. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  12108. * you don't need the other CSS-style formats.
  12109. *
  12110. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  12111. * ```js
  12112. * Color.NAMES.aliceblue // returns 0xF0F8FF
  12113. * ```
  12114. *
  12115. * @param {string} style - The color name.
  12116. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12117. * @return {Color} A reference to this color.
  12118. */
  12119. setColorName( style, colorSpace = SRGBColorSpace ) {
  12120. // color keywords
  12121. const hex = _colorKeywords[ style.toLowerCase() ];
  12122. if ( hex !== undefined ) {
  12123. // red
  12124. this.setHex( hex, colorSpace );
  12125. } else {
  12126. // unknown color
  12127. warn( 'Color: Unknown color ' + style );
  12128. }
  12129. return this;
  12130. }
  12131. /**
  12132. * Returns a new color with copied values from this instance.
  12133. *
  12134. * @return {Color} A clone of this instance.
  12135. */
  12136. clone() {
  12137. return new this.constructor( this.r, this.g, this.b );
  12138. }
  12139. /**
  12140. * Copies the values of the given color to this instance.
  12141. *
  12142. * @param {Color} color - The color to copy.
  12143. * @return {Color} A reference to this color.
  12144. */
  12145. copy( color ) {
  12146. this.r = color.r;
  12147. this.g = color.g;
  12148. this.b = color.b;
  12149. return this;
  12150. }
  12151. /**
  12152. * Copies the given color into this color, and then converts this color from
  12153. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12154. *
  12155. * @param {Color} color - The color to copy/convert.
  12156. * @return {Color} A reference to this color.
  12157. */
  12158. copySRGBToLinear( color ) {
  12159. this.r = SRGBToLinear( color.r );
  12160. this.g = SRGBToLinear( color.g );
  12161. this.b = SRGBToLinear( color.b );
  12162. return this;
  12163. }
  12164. /**
  12165. * Copies the given color into this color, and then converts this color from
  12166. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12167. *
  12168. * @param {Color} color - The color to copy/convert.
  12169. * @return {Color} A reference to this color.
  12170. */
  12171. copyLinearToSRGB( color ) {
  12172. this.r = LinearToSRGB( color.r );
  12173. this.g = LinearToSRGB( color.g );
  12174. this.b = LinearToSRGB( color.b );
  12175. return this;
  12176. }
  12177. /**
  12178. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  12179. *
  12180. * @return {Color} A reference to this color.
  12181. */
  12182. convertSRGBToLinear() {
  12183. this.copySRGBToLinear( this );
  12184. return this;
  12185. }
  12186. /**
  12187. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12188. *
  12189. * @return {Color} A reference to this color.
  12190. */
  12191. convertLinearToSRGB() {
  12192. this.copyLinearToSRGB( this );
  12193. return this;
  12194. }
  12195. /**
  12196. * Returns the hexadecimal value of this color.
  12197. *
  12198. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12199. * @return {number} The hexadecimal value.
  12200. */
  12201. getHex( colorSpace = SRGBColorSpace ) {
  12202. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12203. 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 ) );
  12204. }
  12205. /**
  12206. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12207. *
  12208. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12209. * @return {string} The hexadecimal value as a string.
  12210. */
  12211. getHexString( colorSpace = SRGBColorSpace ) {
  12212. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12213. }
  12214. /**
  12215. * Converts the colors RGB values into the HSL format and stores them into the
  12216. * given target object.
  12217. *
  12218. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12219. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12220. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12221. */
  12222. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12223. // h,s,l ranges are in 0.0 - 1.0
  12224. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12225. const r = _color.r, g = _color.g, b = _color.b;
  12226. const max = Math.max( r, g, b );
  12227. const min = Math.min( r, g, b );
  12228. let hue, saturation;
  12229. const lightness = ( min + max ) / 2.0;
  12230. if ( min === max ) {
  12231. hue = 0;
  12232. saturation = 0;
  12233. } else {
  12234. const delta = max - min;
  12235. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12236. switch ( max ) {
  12237. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12238. case g: hue = ( b - r ) / delta + 2; break;
  12239. case b: hue = ( r - g ) / delta + 4; break;
  12240. }
  12241. hue /= 6;
  12242. }
  12243. target.h = hue;
  12244. target.s = saturation;
  12245. target.l = lightness;
  12246. return target;
  12247. }
  12248. /**
  12249. * Returns the RGB values of this color and stores them into the given target object.
  12250. *
  12251. * @param {Color} target - The target color that is used to store the method's result.
  12252. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12253. * @return {Color} The RGB representation of this color.
  12254. */
  12255. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12256. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12257. target.r = _color.r;
  12258. target.g = _color.g;
  12259. target.b = _color.b;
  12260. return target;
  12261. }
  12262. /**
  12263. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12264. *
  12265. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12266. * @return {string} The CSS representation of this color.
  12267. */
  12268. getStyle( colorSpace = SRGBColorSpace ) {
  12269. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12270. const r = _color.r, g = _color.g, b = _color.b;
  12271. if ( colorSpace !== SRGBColorSpace ) {
  12272. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12273. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12274. }
  12275. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12276. }
  12277. /**
  12278. * Adds the given HSL values to this color's values.
  12279. * Internally, this converts the color's RGB values to HSL, adds HSL
  12280. * and then converts the color back to RGB.
  12281. *
  12282. * @param {number} h - Hue value between `0.0` and `1.0`.
  12283. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12284. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12285. * @return {Color} A reference to this color.
  12286. */
  12287. offsetHSL( h, s, l ) {
  12288. this.getHSL( _hslA );
  12289. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12290. }
  12291. /**
  12292. * Adds the RGB values of the given color to the RGB values of this color.
  12293. *
  12294. * @param {Color} color - The color to add.
  12295. * @return {Color} A reference to this color.
  12296. */
  12297. add( color ) {
  12298. this.r += color.r;
  12299. this.g += color.g;
  12300. this.b += color.b;
  12301. return this;
  12302. }
  12303. /**
  12304. * Adds the RGB values of the given colors and stores the result in this instance.
  12305. *
  12306. * @param {Color} color1 - The first color.
  12307. * @param {Color} color2 - The second color.
  12308. * @return {Color} A reference to this color.
  12309. */
  12310. addColors( color1, color2 ) {
  12311. this.r = color1.r + color2.r;
  12312. this.g = color1.g + color2.g;
  12313. this.b = color1.b + color2.b;
  12314. return this;
  12315. }
  12316. /**
  12317. * Adds the given scalar value to the RGB values of this color.
  12318. *
  12319. * @param {number} s - The scalar to add.
  12320. * @return {Color} A reference to this color.
  12321. */
  12322. addScalar( s ) {
  12323. this.r += s;
  12324. this.g += s;
  12325. this.b += s;
  12326. return this;
  12327. }
  12328. /**
  12329. * Subtracts the RGB values of the given color from the RGB values of this color.
  12330. *
  12331. * @param {Color} color - The color to subtract.
  12332. * @return {Color} A reference to this color.
  12333. */
  12334. sub( color ) {
  12335. this.r = Math.max( 0, this.r - color.r );
  12336. this.g = Math.max( 0, this.g - color.g );
  12337. this.b = Math.max( 0, this.b - color.b );
  12338. return this;
  12339. }
  12340. /**
  12341. * Multiplies the RGB values of the given color with the RGB values of this color.
  12342. *
  12343. * @param {Color} color - The color to multiply.
  12344. * @return {Color} A reference to this color.
  12345. */
  12346. multiply( color ) {
  12347. this.r *= color.r;
  12348. this.g *= color.g;
  12349. this.b *= color.b;
  12350. return this;
  12351. }
  12352. /**
  12353. * Multiplies the given scalar value with the RGB values of this color.
  12354. *
  12355. * @param {number} s - The scalar to multiply.
  12356. * @return {Color} A reference to this color.
  12357. */
  12358. multiplyScalar( s ) {
  12359. this.r *= s;
  12360. this.g *= s;
  12361. this.b *= s;
  12362. return this;
  12363. }
  12364. /**
  12365. * Linearly interpolates this color's RGB values toward the RGB values of the
  12366. * given color. The alpha argument can be thought of as the ratio between
  12367. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12368. *
  12369. * @param {Color} color - The color to converge on.
  12370. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12371. * @return {Color} A reference to this color.
  12372. */
  12373. lerp( color, alpha ) {
  12374. this.r += ( color.r - this.r ) * alpha;
  12375. this.g += ( color.g - this.g ) * alpha;
  12376. this.b += ( color.b - this.b ) * alpha;
  12377. return this;
  12378. }
  12379. /**
  12380. * Linearly interpolates between the given colors and stores the result in this instance.
  12381. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12382. * is the first and `1.0` is the second color.
  12383. *
  12384. * @param {Color} color1 - The first color.
  12385. * @param {Color} color2 - The second color.
  12386. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12387. * @return {Color} A reference to this color.
  12388. */
  12389. lerpColors( color1, color2, alpha ) {
  12390. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12391. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12392. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12393. return this;
  12394. }
  12395. /**
  12396. * Linearly interpolates this color's HSL values toward the HSL values of the
  12397. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12398. * from one color to the other, but instead going through all the hues in between
  12399. * those two colors. The alpha argument can be thought of as the ratio between
  12400. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12401. *
  12402. * @param {Color} color - The color to converge on.
  12403. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12404. * @return {Color} A reference to this color.
  12405. */
  12406. lerpHSL( color, alpha ) {
  12407. this.getHSL( _hslA );
  12408. color.getHSL( _hslB );
  12409. const h = lerp( _hslA.h, _hslB.h, alpha );
  12410. const s = lerp( _hslA.s, _hslB.s, alpha );
  12411. const l = lerp( _hslA.l, _hslB.l, alpha );
  12412. this.setHSL( h, s, l );
  12413. return this;
  12414. }
  12415. /**
  12416. * Sets the color's RGB components from the given 3D vector.
  12417. *
  12418. * @param {Vector3} v - The vector to set.
  12419. * @return {Color} A reference to this color.
  12420. */
  12421. setFromVector3( v ) {
  12422. this.r = v.x;
  12423. this.g = v.y;
  12424. this.b = v.z;
  12425. return this;
  12426. }
  12427. /**
  12428. * Transforms this color with the given 3x3 matrix.
  12429. *
  12430. * @param {Matrix3} m - The matrix.
  12431. * @return {Color} A reference to this color.
  12432. */
  12433. applyMatrix3( m ) {
  12434. const r = this.r, g = this.g, b = this.b;
  12435. const e = m.elements;
  12436. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12437. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12438. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12439. return this;
  12440. }
  12441. /**
  12442. * Returns `true` if this color is equal with the given one.
  12443. *
  12444. * @param {Color} c - The color to test for equality.
  12445. * @return {boolean} Whether this bounding color is equal with the given one.
  12446. */
  12447. equals( c ) {
  12448. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12449. }
  12450. /**
  12451. * Sets this color's RGB components from the given array.
  12452. *
  12453. * @param {Array<number>} array - An array holding the RGB values.
  12454. * @param {number} [offset=0] - The offset into the array.
  12455. * @return {Color} A reference to this color.
  12456. */
  12457. fromArray( array, offset = 0 ) {
  12458. this.r = array[ offset ];
  12459. this.g = array[ offset + 1 ];
  12460. this.b = array[ offset + 2 ];
  12461. return this;
  12462. }
  12463. /**
  12464. * Writes the RGB components of this color to the given array. If no array is provided,
  12465. * the method returns a new instance.
  12466. *
  12467. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12468. * @param {number} [offset=0] - Index of the first element in the array.
  12469. * @return {Array<number>} The color components.
  12470. */
  12471. toArray( array = [], offset = 0 ) {
  12472. array[ offset ] = this.r;
  12473. array[ offset + 1 ] = this.g;
  12474. array[ offset + 2 ] = this.b;
  12475. return array;
  12476. }
  12477. /**
  12478. * Sets the components of this color from the given buffer attribute.
  12479. *
  12480. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12481. * @param {number} index - The index into the attribute.
  12482. * @return {Color} A reference to this color.
  12483. */
  12484. fromBufferAttribute( attribute, index ) {
  12485. this.r = attribute.getX( index );
  12486. this.g = attribute.getY( index );
  12487. this.b = attribute.getZ( index );
  12488. return this;
  12489. }
  12490. /**
  12491. * This methods defines the serialization result of this class. Returns the color
  12492. * as a hexadecimal value.
  12493. *
  12494. * @return {number} The hexadecimal value.
  12495. */
  12496. toJSON() {
  12497. return this.getHex();
  12498. }
  12499. *[ Symbol.iterator ]() {
  12500. yield this.r;
  12501. yield this.g;
  12502. yield this.b;
  12503. }
  12504. }
  12505. const _color = /*@__PURE__*/ new Color();
  12506. /**
  12507. * A dictionary with X11 color names.
  12508. *
  12509. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12510. *
  12511. * @static
  12512. * @type {Object}
  12513. */
  12514. Color.NAMES = _colorKeywords;
  12515. let _materialId = 0;
  12516. /**
  12517. * Abstract base class for materials.
  12518. *
  12519. * Materials define the appearance of renderable 3D objects.
  12520. *
  12521. * @abstract
  12522. * @augments EventDispatcher
  12523. */
  12524. class Material extends EventDispatcher {
  12525. /**
  12526. * Constructs a new material.
  12527. */
  12528. constructor() {
  12529. super();
  12530. /**
  12531. * This flag can be used for type testing.
  12532. *
  12533. * @type {boolean}
  12534. * @readonly
  12535. * @default true
  12536. */
  12537. this.isMaterial = true;
  12538. /**
  12539. * The ID of the material.
  12540. *
  12541. * @name Material#id
  12542. * @type {number}
  12543. * @readonly
  12544. */
  12545. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12546. /**
  12547. * The UUID of the material.
  12548. *
  12549. * @type {string}
  12550. * @readonly
  12551. */
  12552. this.uuid = generateUUID();
  12553. /**
  12554. * The name of the material.
  12555. *
  12556. * @type {string}
  12557. */
  12558. this.name = '';
  12559. /**
  12560. * The type property is used for detecting the object type
  12561. * in context of serialization/deserialization.
  12562. *
  12563. * @type {string}
  12564. * @readonly
  12565. */
  12566. this.type = 'Material';
  12567. /**
  12568. * Defines the blending type of the material.
  12569. *
  12570. * It must be set to `CustomBlending` if custom blending properties like
  12571. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12572. * should have any effect.
  12573. *
  12574. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12575. * @default NormalBlending
  12576. */
  12577. this.blending = NormalBlending;
  12578. /**
  12579. * Defines which side of faces will be rendered - front, back or both.
  12580. *
  12581. * @type {(FrontSide|BackSide|DoubleSide)}
  12582. * @default FrontSide
  12583. */
  12584. this.side = FrontSide;
  12585. /**
  12586. * If set to `true`, vertex colors should be used.
  12587. *
  12588. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12589. * four (RGBA) component color buffer attribute is used.
  12590. *
  12591. * @type {boolean}
  12592. * @default false
  12593. */
  12594. this.vertexColors = false;
  12595. /**
  12596. * Defines how transparent the material is.
  12597. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12598. *
  12599. * If the {@link Material#transparent} is not set to `true`,
  12600. * the material will remain fully opaque and this value will only affect its color.
  12601. *
  12602. * @type {number}
  12603. * @default 1
  12604. */
  12605. this.opacity = 1;
  12606. /**
  12607. * Defines whether this material is transparent. This has an effect on
  12608. * rendering as transparent objects need special treatment and are rendered
  12609. * after non-transparent objects.
  12610. *
  12611. * When set to true, the extent to which the material is transparent is
  12612. * controlled by {@link Material#opacity}.
  12613. *
  12614. * @type {boolean}
  12615. * @default false
  12616. */
  12617. this.transparent = false;
  12618. /**
  12619. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12620. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12621. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12622. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12623. *
  12624. * @type {boolean}
  12625. * @default false
  12626. */
  12627. this.alphaHash = false;
  12628. /**
  12629. * Defines the blending source factor.
  12630. *
  12631. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12632. * @default SrcAlphaFactor
  12633. */
  12634. this.blendSrc = SrcAlphaFactor;
  12635. /**
  12636. * Defines the blending destination factor.
  12637. *
  12638. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12639. * @default OneMinusSrcAlphaFactor
  12640. */
  12641. this.blendDst = OneMinusSrcAlphaFactor;
  12642. /**
  12643. * Defines the blending equation.
  12644. *
  12645. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12646. * @default AddEquation
  12647. */
  12648. this.blendEquation = AddEquation;
  12649. /**
  12650. * Defines the blending source alpha factor.
  12651. *
  12652. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12653. * @default null
  12654. */
  12655. this.blendSrcAlpha = null;
  12656. /**
  12657. * Defines the blending destination alpha factor.
  12658. *
  12659. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12660. * @default null
  12661. */
  12662. this.blendDstAlpha = null;
  12663. /**
  12664. * Defines the blending equation of the alpha channel.
  12665. *
  12666. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12667. * @default null
  12668. */
  12669. this.blendEquationAlpha = null;
  12670. /**
  12671. * Represents the RGB values of the constant blend color.
  12672. *
  12673. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12674. *
  12675. * @type {Color}
  12676. * @default (0,0,0)
  12677. */
  12678. this.blendColor = new Color( 0, 0, 0 );
  12679. /**
  12680. * Represents the alpha value of the constant blend color.
  12681. *
  12682. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12683. *
  12684. * @type {number}
  12685. * @default 0
  12686. */
  12687. this.blendAlpha = 0;
  12688. /**
  12689. * Defines the depth function.
  12690. *
  12691. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12692. * @default LessEqualDepth
  12693. */
  12694. this.depthFunc = LessEqualDepth;
  12695. /**
  12696. * Whether to have depth test enabled when rendering this material.
  12697. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12698. *
  12699. * @type {boolean}
  12700. * @default true
  12701. */
  12702. this.depthTest = true;
  12703. /**
  12704. * Whether rendering this material has any effect on the depth buffer.
  12705. *
  12706. * When drawing 2D overlays it can be useful to disable the depth writing in
  12707. * order to layer several things together without creating z-index artifacts.
  12708. *
  12709. * @type {boolean}
  12710. * @default true
  12711. */
  12712. this.depthWrite = true;
  12713. /**
  12714. * The bit mask to use when writing to the stencil buffer.
  12715. *
  12716. * @type {number}
  12717. * @default 0xff
  12718. */
  12719. this.stencilWriteMask = 0xff;
  12720. /**
  12721. * The stencil comparison function to use.
  12722. *
  12723. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12724. * @default AlwaysStencilFunc
  12725. */
  12726. this.stencilFunc = AlwaysStencilFunc;
  12727. /**
  12728. * The value to use when performing stencil comparisons or stencil operations.
  12729. *
  12730. * @type {number}
  12731. * @default 0
  12732. */
  12733. this.stencilRef = 0;
  12734. /**
  12735. * The bit mask to use when comparing against the stencil buffer.
  12736. *
  12737. * @type {number}
  12738. * @default 0xff
  12739. */
  12740. this.stencilFuncMask = 0xff;
  12741. /**
  12742. * Which stencil operation to perform when the comparison function returns `false`.
  12743. *
  12744. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12745. * @default KeepStencilOp
  12746. */
  12747. this.stencilFail = KeepStencilOp;
  12748. /**
  12749. * Which stencil operation to perform when the comparison function returns
  12750. * `true` but the depth test fails.
  12751. *
  12752. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12753. * @default KeepStencilOp
  12754. */
  12755. this.stencilZFail = KeepStencilOp;
  12756. /**
  12757. * Which stencil operation to perform when the comparison function returns
  12758. * `true` and the depth test passes.
  12759. *
  12760. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12761. * @default KeepStencilOp
  12762. */
  12763. this.stencilZPass = KeepStencilOp;
  12764. /**
  12765. * Whether stencil operations are performed against the stencil buffer. In
  12766. * order to perform writes or comparisons against the stencil buffer this
  12767. * value must be `true`.
  12768. *
  12769. * @type {boolean}
  12770. * @default false
  12771. */
  12772. this.stencilWrite = false;
  12773. /**
  12774. * User-defined clipping planes specified as THREE.Plane objects in world
  12775. * space. These planes apply to the objects this material is attached to.
  12776. * Points in space whose signed distance to the plane is negative are clipped
  12777. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12778. * be `true`.
  12779. *
  12780. * @type {?Array<Plane>}
  12781. * @default null
  12782. */
  12783. this.clippingPlanes = null;
  12784. /**
  12785. * Changes the behavior of clipping planes so that only their intersection is
  12786. * clipped, rather than their union.
  12787. *
  12788. * @type {boolean}
  12789. * @default false
  12790. */
  12791. this.clipIntersection = false;
  12792. /**
  12793. * Defines whether to clip shadows according to the clipping planes specified
  12794. * on this material.
  12795. *
  12796. * @type {boolean}
  12797. * @default false
  12798. */
  12799. this.clipShadows = false;
  12800. /**
  12801. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12802. * is determined as follows:
  12803. *
  12804. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12805. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12806. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12807. *
  12808. * @type {?(FrontSide|BackSide|DoubleSide)}
  12809. * @default null
  12810. */
  12811. this.shadowSide = null;
  12812. /**
  12813. * Whether to render the material's color.
  12814. *
  12815. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12816. * objects that occlude other objects.
  12817. *
  12818. * @type {boolean}
  12819. * @default true
  12820. */
  12821. this.colorWrite = true;
  12822. /**
  12823. * Override the renderer's default precision for this material.
  12824. *
  12825. * @type {?('highp'|'mediump'|'lowp')}
  12826. * @default null
  12827. */
  12828. this.precision = null;
  12829. /**
  12830. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12831. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12832. * The offset is added before the depth test is performed and before the value is written
  12833. * into the depth buffer.
  12834. *
  12835. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12836. * rendering solids with highlighted edges.
  12837. *
  12838. * @type {boolean}
  12839. * @default false
  12840. */
  12841. this.polygonOffset = false;
  12842. /**
  12843. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12844. *
  12845. * @type {number}
  12846. * @default 0
  12847. */
  12848. this.polygonOffsetFactor = 0;
  12849. /**
  12850. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12851. *
  12852. * @type {number}
  12853. * @default 0
  12854. */
  12855. this.polygonOffsetUnits = 0;
  12856. /**
  12857. * Whether to apply dithering to the color to remove the appearance of banding.
  12858. *
  12859. * @type {boolean}
  12860. * @default false
  12861. */
  12862. this.dithering = false;
  12863. /**
  12864. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12865. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12866. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12867. *
  12868. * @type {boolean}
  12869. * @default false
  12870. */
  12871. this.alphaToCoverage = false;
  12872. /**
  12873. * Whether to premultiply the alpha (transparency) value.
  12874. *
  12875. * @type {boolean}
  12876. * @default false
  12877. */
  12878. this.premultipliedAlpha = false;
  12879. /**
  12880. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12881. *
  12882. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12883. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12884. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12885. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12886. * disable the two pass rendering to avoid performance issues.
  12887. *
  12888. * @type {boolean}
  12889. * @default false
  12890. */
  12891. this.forceSinglePass = false;
  12892. /**
  12893. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12894. *
  12895. * @type {boolean}
  12896. * @default true
  12897. */
  12898. this.allowOverride = true;
  12899. /**
  12900. * Defines whether 3D objects using this material are visible.
  12901. *
  12902. * @type {boolean}
  12903. * @default true
  12904. */
  12905. this.visible = true;
  12906. /**
  12907. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12908. *
  12909. * It is ignored when rendering to a render target or using post processing or when using
  12910. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12911. *
  12912. * @type {boolean}
  12913. * @default true
  12914. */
  12915. this.toneMapped = true;
  12916. /**
  12917. * An object that can be used to store custom data about the Material. It
  12918. * should not hold references to functions as these will not be cloned.
  12919. *
  12920. * @type {Object}
  12921. */
  12922. this.userData = {};
  12923. /**
  12924. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12925. *
  12926. * @type {number}
  12927. * @readonly
  12928. * @default 0
  12929. */
  12930. this.version = 0;
  12931. this._alphaTest = 0;
  12932. }
  12933. /**
  12934. * Sets the alpha value to be used when running an alpha test. The material
  12935. * will not be rendered if the opacity is lower than this value.
  12936. *
  12937. * @type {number}
  12938. * @readonly
  12939. * @default 0
  12940. */
  12941. get alphaTest() {
  12942. return this._alphaTest;
  12943. }
  12944. set alphaTest( value ) {
  12945. if ( this._alphaTest > 0 !== value > 0 ) {
  12946. this.version ++;
  12947. }
  12948. this._alphaTest = value;
  12949. }
  12950. /**
  12951. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12952. *
  12953. * This method can only be used when rendering with {@link WebGLRenderer}.
  12954. *
  12955. * @param {WebGLRenderer} renderer - The renderer.
  12956. * @param {Scene} scene - The scene.
  12957. * @param {Camera} camera - The camera that is used to render the scene.
  12958. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12959. * @param {Object3D} object - The 3D object.
  12960. * @param {Object} group - The geometry group data.
  12961. */
  12962. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12963. /**
  12964. * An optional callback that is executed immediately before the shader
  12965. * program is compiled. This function is called with the shader source code
  12966. * as a parameter. Useful for the modification of built-in materials.
  12967. *
  12968. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12969. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12970. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12971. *
  12972. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12973. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12974. */
  12975. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12976. /**
  12977. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12978. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12979. * shader or recompile the shader for this material as needed.
  12980. *
  12981. * This method can only be used when rendering with {@link WebGLRenderer}.
  12982. *
  12983. * @return {string} The custom program cache key.
  12984. */
  12985. customProgramCacheKey() {
  12986. return this.onBeforeCompile.toString();
  12987. }
  12988. /**
  12989. * This method can be used to set default values from parameter objects.
  12990. * It is a generic implementation so it can be used with different types
  12991. * of materials.
  12992. *
  12993. * @param {Object} [values] - The material values to set.
  12994. */
  12995. setValues( values ) {
  12996. if ( values === undefined ) return;
  12997. for ( const key in values ) {
  12998. const newValue = values[ key ];
  12999. if ( newValue === undefined ) {
  13000. warn( `Material: parameter '${ key }' has value of undefined.` );
  13001. continue;
  13002. }
  13003. const currentValue = this[ key ];
  13004. if ( currentValue === undefined ) {
  13005. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  13006. continue;
  13007. }
  13008. if ( currentValue && currentValue.isColor ) {
  13009. currentValue.set( newValue );
  13010. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  13011. currentValue.copy( newValue );
  13012. } else {
  13013. this[ key ] = newValue;
  13014. }
  13015. }
  13016. }
  13017. /**
  13018. * Serializes the material into JSON.
  13019. *
  13020. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  13021. * @return {Object} A JSON object representing the serialized material.
  13022. * @see {@link ObjectLoader#parse}
  13023. */
  13024. toJSON( meta ) {
  13025. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  13026. if ( isRootObject ) {
  13027. meta = {
  13028. textures: {},
  13029. images: {}
  13030. };
  13031. }
  13032. const data = {
  13033. metadata: {
  13034. version: 4.7,
  13035. type: 'Material',
  13036. generator: 'Material.toJSON'
  13037. }
  13038. };
  13039. // standard Material serialization
  13040. data.uuid = this.uuid;
  13041. data.type = this.type;
  13042. if ( this.name !== '' ) data.name = this.name;
  13043. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  13044. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  13045. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  13046. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  13047. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  13048. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  13049. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  13050. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  13051. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  13052. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  13053. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  13054. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  13055. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  13056. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  13057. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  13058. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  13059. }
  13060. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  13061. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  13062. }
  13063. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  13064. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  13065. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  13066. }
  13067. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  13068. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  13069. }
  13070. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  13071. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  13072. }
  13073. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  13074. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  13075. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  13076. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  13077. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  13078. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  13079. }
  13080. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  13081. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  13082. }
  13083. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  13084. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  13085. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  13086. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  13087. }
  13088. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  13089. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  13090. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  13091. if ( this.lightMap && this.lightMap.isTexture ) {
  13092. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  13093. data.lightMapIntensity = this.lightMapIntensity;
  13094. }
  13095. if ( this.aoMap && this.aoMap.isTexture ) {
  13096. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  13097. data.aoMapIntensity = this.aoMapIntensity;
  13098. }
  13099. if ( this.bumpMap && this.bumpMap.isTexture ) {
  13100. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  13101. data.bumpScale = this.bumpScale;
  13102. }
  13103. if ( this.normalMap && this.normalMap.isTexture ) {
  13104. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  13105. data.normalMapType = this.normalMapType;
  13106. data.normalScale = this.normalScale.toArray();
  13107. }
  13108. if ( this.displacementMap && this.displacementMap.isTexture ) {
  13109. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  13110. data.displacementScale = this.displacementScale;
  13111. data.displacementBias = this.displacementBias;
  13112. }
  13113. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  13114. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  13115. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  13116. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  13117. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  13118. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  13119. if ( this.envMap && this.envMap.isTexture ) {
  13120. data.envMap = this.envMap.toJSON( meta ).uuid;
  13121. if ( this.combine !== undefined ) data.combine = this.combine;
  13122. }
  13123. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  13124. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  13125. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  13126. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  13127. if ( this.gradientMap && this.gradientMap.isTexture ) {
  13128. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  13129. }
  13130. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  13131. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  13132. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  13133. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  13134. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  13135. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  13136. if ( this.size !== undefined ) data.size = this.size;
  13137. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  13138. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  13139. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  13140. if ( this.side !== FrontSide ) data.side = this.side;
  13141. if ( this.vertexColors === true ) data.vertexColors = true;
  13142. if ( this.opacity < 1 ) data.opacity = this.opacity;
  13143. if ( this.transparent === true ) data.transparent = true;
  13144. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  13145. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  13146. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  13147. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  13148. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  13149. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  13150. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  13151. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  13152. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  13153. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  13154. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  13155. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  13156. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  13157. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  13158. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  13159. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  13160. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  13161. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  13162. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  13163. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  13164. // rotation (SpriteMaterial)
  13165. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  13166. if ( this.polygonOffset === true ) data.polygonOffset = true;
  13167. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  13168. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  13169. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  13170. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  13171. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  13172. if ( this.scale !== undefined ) data.scale = this.scale;
  13173. if ( this.dithering === true ) data.dithering = true;
  13174. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  13175. if ( this.alphaHash === true ) data.alphaHash = true;
  13176. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  13177. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  13178. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  13179. if ( this.allowOverride === false ) data.allowOverride = false;
  13180. if ( this.wireframe === true ) data.wireframe = true;
  13181. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  13182. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13183. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13184. if ( this.flatShading === true ) data.flatShading = true;
  13185. if ( this.visible === false ) data.visible = false;
  13186. if ( this.toneMapped === false ) data.toneMapped = false;
  13187. if ( this.fog === false ) data.fog = false;
  13188. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13189. // TODO: Copied from Object3D.toJSON
  13190. function extractFromCache( cache ) {
  13191. const values = [];
  13192. for ( const key in cache ) {
  13193. const data = cache[ key ];
  13194. delete data.metadata;
  13195. values.push( data );
  13196. }
  13197. return values;
  13198. }
  13199. if ( isRootObject ) {
  13200. const textures = extractFromCache( meta.textures );
  13201. const images = extractFromCache( meta.images );
  13202. if ( textures.length > 0 ) data.textures = textures;
  13203. if ( images.length > 0 ) data.images = images;
  13204. }
  13205. return data;
  13206. }
  13207. /**
  13208. * Returns a new material with copied values from this instance.
  13209. *
  13210. * @return {Material} A clone of this instance.
  13211. */
  13212. clone() {
  13213. return new this.constructor().copy( this );
  13214. }
  13215. /**
  13216. * Copies the values of the given material to this instance.
  13217. *
  13218. * @param {Material} source - The material to copy.
  13219. * @return {Material} A reference to this instance.
  13220. */
  13221. copy( source ) {
  13222. this.name = source.name;
  13223. this.blending = source.blending;
  13224. this.side = source.side;
  13225. this.vertexColors = source.vertexColors;
  13226. this.opacity = source.opacity;
  13227. this.transparent = source.transparent;
  13228. this.blendSrc = source.blendSrc;
  13229. this.blendDst = source.blendDst;
  13230. this.blendEquation = source.blendEquation;
  13231. this.blendSrcAlpha = source.blendSrcAlpha;
  13232. this.blendDstAlpha = source.blendDstAlpha;
  13233. this.blendEquationAlpha = source.blendEquationAlpha;
  13234. this.blendColor.copy( source.blendColor );
  13235. this.blendAlpha = source.blendAlpha;
  13236. this.depthFunc = source.depthFunc;
  13237. this.depthTest = source.depthTest;
  13238. this.depthWrite = source.depthWrite;
  13239. this.stencilWriteMask = source.stencilWriteMask;
  13240. this.stencilFunc = source.stencilFunc;
  13241. this.stencilRef = source.stencilRef;
  13242. this.stencilFuncMask = source.stencilFuncMask;
  13243. this.stencilFail = source.stencilFail;
  13244. this.stencilZFail = source.stencilZFail;
  13245. this.stencilZPass = source.stencilZPass;
  13246. this.stencilWrite = source.stencilWrite;
  13247. const srcPlanes = source.clippingPlanes;
  13248. let dstPlanes = null;
  13249. if ( srcPlanes !== null ) {
  13250. const n = srcPlanes.length;
  13251. dstPlanes = new Array( n );
  13252. for ( let i = 0; i !== n; ++ i ) {
  13253. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13254. }
  13255. }
  13256. this.clippingPlanes = dstPlanes;
  13257. this.clipIntersection = source.clipIntersection;
  13258. this.clipShadows = source.clipShadows;
  13259. this.shadowSide = source.shadowSide;
  13260. this.colorWrite = source.colorWrite;
  13261. this.precision = source.precision;
  13262. this.polygonOffset = source.polygonOffset;
  13263. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13264. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13265. this.dithering = source.dithering;
  13266. this.alphaTest = source.alphaTest;
  13267. this.alphaHash = source.alphaHash;
  13268. this.alphaToCoverage = source.alphaToCoverage;
  13269. this.premultipliedAlpha = source.premultipliedAlpha;
  13270. this.forceSinglePass = source.forceSinglePass;
  13271. this.allowOverride = source.allowOverride;
  13272. this.visible = source.visible;
  13273. this.toneMapped = source.toneMapped;
  13274. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13275. return this;
  13276. }
  13277. /**
  13278. * Frees the GPU-related resources allocated by this instance. Call this
  13279. * method whenever this instance is no longer used in your app.
  13280. *
  13281. * @fires Material#dispose
  13282. */
  13283. dispose() {
  13284. /**
  13285. * Fires when the material has been disposed of.
  13286. *
  13287. * @event Material#dispose
  13288. * @type {Object}
  13289. */
  13290. this.dispatchEvent( { type: 'dispose' } );
  13291. }
  13292. /**
  13293. * Setting this property to `true` indicates the engine the material
  13294. * needs to be recompiled.
  13295. *
  13296. * @type {boolean}
  13297. * @default false
  13298. * @param {boolean} value
  13299. */
  13300. set needsUpdate( value ) {
  13301. if ( value === true ) this.version ++;
  13302. }
  13303. }
  13304. /**
  13305. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13306. *
  13307. * This material is not affected by lights.
  13308. *
  13309. * @augments Material
  13310. * @demo scenes/material-browser.html#MeshBasicMaterial
  13311. */
  13312. class MeshBasicMaterial extends Material {
  13313. /**
  13314. * Constructs a new mesh basic material.
  13315. *
  13316. * @param {Object} [parameters] - An object with one or more properties
  13317. * defining the material's appearance. Any property of the material
  13318. * (including any property from inherited materials) can be passed
  13319. * in here. Color values can be passed any type of value accepted
  13320. * by {@link Color#set}.
  13321. */
  13322. constructor( parameters ) {
  13323. super();
  13324. /**
  13325. * This flag can be used for type testing.
  13326. *
  13327. * @type {boolean}
  13328. * @readonly
  13329. * @default true
  13330. */
  13331. this.isMeshBasicMaterial = true;
  13332. this.type = 'MeshBasicMaterial';
  13333. /**
  13334. * Color of the material.
  13335. *
  13336. * @type {Color}
  13337. * @default (1,1,1)
  13338. */
  13339. this.color = new Color( 0xffffff ); // diffuse
  13340. /**
  13341. * The color map. May optionally include an alpha channel, typically combined
  13342. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13343. * color is modulated by the diffuse `color`.
  13344. *
  13345. * @type {?Texture}
  13346. * @default null
  13347. */
  13348. this.map = null;
  13349. /**
  13350. * The light map. Requires a second set of UVs.
  13351. *
  13352. * @type {?Texture}
  13353. * @default null
  13354. */
  13355. this.lightMap = null;
  13356. /**
  13357. * Intensity of the baked light.
  13358. *
  13359. * @type {number}
  13360. * @default 1
  13361. */
  13362. this.lightMapIntensity = 1.0;
  13363. /**
  13364. * The red channel of this texture is used as the ambient occlusion map.
  13365. * Requires a second set of UVs.
  13366. *
  13367. * @type {?Texture}
  13368. * @default null
  13369. */
  13370. this.aoMap = null;
  13371. /**
  13372. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13373. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13374. * red channel is also `1`, ambient light is fully occluded on a surface.
  13375. *
  13376. * @type {number}
  13377. * @default 1
  13378. */
  13379. this.aoMapIntensity = 1.0;
  13380. /**
  13381. * Specular map used by the material.
  13382. *
  13383. * @type {?Texture}
  13384. * @default null
  13385. */
  13386. this.specularMap = null;
  13387. /**
  13388. * The alpha map is a grayscale texture that controls the opacity across the
  13389. * surface (black: fully transparent; white: fully opaque).
  13390. *
  13391. * Only the color of the texture is used, ignoring the alpha channel if one
  13392. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13393. * when sampling this texture due to the extra bit of precision provided for
  13394. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13395. * luminance/alpha textures will also still work as expected.
  13396. *
  13397. * @type {?Texture}
  13398. * @default null
  13399. */
  13400. this.alphaMap = null;
  13401. /**
  13402. * The environment map.
  13403. *
  13404. * @type {?Texture}
  13405. * @default null
  13406. */
  13407. this.envMap = null;
  13408. /**
  13409. * The rotation of the environment map in radians.
  13410. *
  13411. * @type {Euler}
  13412. * @default (0,0,0)
  13413. */
  13414. this.envMapRotation = new Euler();
  13415. /**
  13416. * How to combine the result of the surface's color with the environment map, if any.
  13417. *
  13418. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13419. * blend between the two colors.
  13420. *
  13421. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13422. * @default MultiplyOperation
  13423. */
  13424. this.combine = MultiplyOperation;
  13425. /**
  13426. * How much the environment map affects the surface.
  13427. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13428. *
  13429. * @type {number}
  13430. * @default 1
  13431. */
  13432. this.reflectivity = 1;
  13433. /**
  13434. * The index of refraction (IOR) of air (approximately 1) divided by the
  13435. * index of refraction of the material. It is used with environment mapping
  13436. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13437. * The refraction ratio should not exceed `1`.
  13438. *
  13439. * @type {number}
  13440. * @default 0.98
  13441. */
  13442. this.refractionRatio = 0.98;
  13443. /**
  13444. * Renders the geometry as a wireframe.
  13445. *
  13446. * @type {boolean}
  13447. * @default false
  13448. */
  13449. this.wireframe = false;
  13450. /**
  13451. * Controls the thickness of the wireframe.
  13452. *
  13453. * Can only be used with {@link SVGRenderer}.
  13454. *
  13455. * @type {number}
  13456. * @default 1
  13457. */
  13458. this.wireframeLinewidth = 1;
  13459. /**
  13460. * Defines appearance of wireframe ends.
  13461. *
  13462. * Can only be used with {@link SVGRenderer}.
  13463. *
  13464. * @type {('round'|'bevel'|'miter')}
  13465. * @default 'round'
  13466. */
  13467. this.wireframeLinecap = 'round';
  13468. /**
  13469. * Defines appearance of wireframe joints.
  13470. *
  13471. * Can only be used with {@link SVGRenderer}.
  13472. *
  13473. * @type {('round'|'bevel'|'miter')}
  13474. * @default 'round'
  13475. */
  13476. this.wireframeLinejoin = 'round';
  13477. /**
  13478. * Whether the material is affected by fog or not.
  13479. *
  13480. * @type {boolean}
  13481. * @default true
  13482. */
  13483. this.fog = true;
  13484. this.setValues( parameters );
  13485. }
  13486. copy( source ) {
  13487. super.copy( source );
  13488. this.color.copy( source.color );
  13489. this.map = source.map;
  13490. this.lightMap = source.lightMap;
  13491. this.lightMapIntensity = source.lightMapIntensity;
  13492. this.aoMap = source.aoMap;
  13493. this.aoMapIntensity = source.aoMapIntensity;
  13494. this.specularMap = source.specularMap;
  13495. this.alphaMap = source.alphaMap;
  13496. this.envMap = source.envMap;
  13497. this.envMapRotation.copy( source.envMapRotation );
  13498. this.combine = source.combine;
  13499. this.reflectivity = source.reflectivity;
  13500. this.refractionRatio = source.refractionRatio;
  13501. this.wireframe = source.wireframe;
  13502. this.wireframeLinewidth = source.wireframeLinewidth;
  13503. this.wireframeLinecap = source.wireframeLinecap;
  13504. this.wireframeLinejoin = source.wireframeLinejoin;
  13505. this.fog = source.fog;
  13506. return this;
  13507. }
  13508. }
  13509. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13510. const _tables = /*@__PURE__*/ _generateTables();
  13511. function _generateTables() {
  13512. // float32 to float16 helpers
  13513. const buffer = new ArrayBuffer( 4 );
  13514. const floatView = new Float32Array( buffer );
  13515. const uint32View = new Uint32Array( buffer );
  13516. const baseTable = new Uint32Array( 512 );
  13517. const shiftTable = new Uint32Array( 512 );
  13518. for ( let i = 0; i < 256; ++ i ) {
  13519. const e = i - 127;
  13520. // very small number (0, -0)
  13521. if ( e < -27 ) {
  13522. baseTable[ i ] = 0x0000;
  13523. baseTable[ i | 0x100 ] = 0x8000;
  13524. shiftTable[ i ] = 24;
  13525. shiftTable[ i | 0x100 ] = 24;
  13526. // small number (denorm)
  13527. } else if ( e < -14 ) {
  13528. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13529. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13530. shiftTable[ i ] = - e - 1;
  13531. shiftTable[ i | 0x100 ] = - e - 1;
  13532. // normal number
  13533. } else if ( e <= 15 ) {
  13534. baseTable[ i ] = ( e + 15 ) << 10;
  13535. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13536. shiftTable[ i ] = 13;
  13537. shiftTable[ i | 0x100 ] = 13;
  13538. // large number (Infinity, -Infinity)
  13539. } else if ( e < 128 ) {
  13540. baseTable[ i ] = 0x7c00;
  13541. baseTable[ i | 0x100 ] = 0xfc00;
  13542. shiftTable[ i ] = 24;
  13543. shiftTable[ i | 0x100 ] = 24;
  13544. // stay (NaN, Infinity, -Infinity)
  13545. } else {
  13546. baseTable[ i ] = 0x7c00;
  13547. baseTable[ i | 0x100 ] = 0xfc00;
  13548. shiftTable[ i ] = 13;
  13549. shiftTable[ i | 0x100 ] = 13;
  13550. }
  13551. }
  13552. // float16 to float32 helpers
  13553. const mantissaTable = new Uint32Array( 2048 );
  13554. const exponentTable = new Uint32Array( 64 );
  13555. const offsetTable = new Uint32Array( 64 );
  13556. for ( let i = 1; i < 1024; ++ i ) {
  13557. let m = i << 13; // zero pad mantissa bits
  13558. let e = 0; // zero exponent
  13559. // normalized
  13560. while ( ( m & 0x00800000 ) === 0 ) {
  13561. m <<= 1;
  13562. e -= 0x00800000; // decrement exponent
  13563. }
  13564. m &= -8388609; // clear leading 1 bit
  13565. e += 0x38800000; // adjust bias
  13566. mantissaTable[ i ] = m | e;
  13567. }
  13568. for ( let i = 1024; i < 2048; ++ i ) {
  13569. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13570. }
  13571. for ( let i = 1; i < 31; ++ i ) {
  13572. exponentTable[ i ] = i << 23;
  13573. }
  13574. exponentTable[ 31 ] = 0x47800000;
  13575. exponentTable[ 32 ] = 0x80000000;
  13576. for ( let i = 33; i < 63; ++ i ) {
  13577. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13578. }
  13579. exponentTable[ 63 ] = 0xc7800000;
  13580. for ( let i = 1; i < 64; ++ i ) {
  13581. if ( i !== 32 ) {
  13582. offsetTable[ i ] = 1024;
  13583. }
  13584. }
  13585. return {
  13586. floatView: floatView,
  13587. uint32View: uint32View,
  13588. baseTable: baseTable,
  13589. shiftTable: shiftTable,
  13590. mantissaTable: mantissaTable,
  13591. exponentTable: exponentTable,
  13592. offsetTable: offsetTable
  13593. };
  13594. }
  13595. /**
  13596. * Returns a half precision floating point value (FP16) from the given single
  13597. * precision floating point value (FP32).
  13598. *
  13599. * @param {number} val - A single precision floating point value.
  13600. * @return {number} The FP16 value.
  13601. */
  13602. function toHalfFloat( val ) {
  13603. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13604. val = clamp( val, -65504, 65504 );
  13605. _tables.floatView[ 0 ] = val;
  13606. const f = _tables.uint32View[ 0 ];
  13607. const e = ( f >> 23 ) & 0x1ff;
  13608. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13609. }
  13610. /**
  13611. * Returns a single precision floating point value (FP32) from the given half
  13612. * precision floating point value (FP16).
  13613. *
  13614. * @param {number} val - A half precision floating point value.
  13615. * @return {number} The FP32 value.
  13616. */
  13617. function fromHalfFloat( val ) {
  13618. const m = val >> 10;
  13619. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13620. return _tables.floatView[ 0 ];
  13621. }
  13622. /**
  13623. * A class containing utility functions for data.
  13624. *
  13625. * @hideconstructor
  13626. */
  13627. class DataUtils {
  13628. /**
  13629. * Returns a half precision floating point value (FP16) from the given single
  13630. * precision floating point value (FP32).
  13631. *
  13632. * @param {number} val - A single precision floating point value.
  13633. * @return {number} The FP16 value.
  13634. */
  13635. static toHalfFloat( val ) {
  13636. return toHalfFloat( val );
  13637. }
  13638. /**
  13639. * Returns a single precision floating point value (FP32) from the given half
  13640. * precision floating point value (FP16).
  13641. *
  13642. * @param {number} val - A half precision floating point value.
  13643. * @return {number} The FP32 value.
  13644. */
  13645. static fromHalfFloat( val ) {
  13646. return fromHalfFloat( val );
  13647. }
  13648. }
  13649. const _vector$9 = /*@__PURE__*/ new Vector3();
  13650. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13651. let _id$3 = 0;
  13652. /**
  13653. * This class stores data for an attribute (such as vertex positions, face
  13654. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13655. * a geometry, which allows for more efficient passing of data to the GPU.
  13656. *
  13657. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13658. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13659. */
  13660. class BufferAttribute {
  13661. /**
  13662. * Constructs a new buffer attribute.
  13663. *
  13664. * @param {TypedArray} array - The array holding the attribute data.
  13665. * @param {number} itemSize - The item size.
  13666. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13667. */
  13668. constructor( array, itemSize, normalized = false ) {
  13669. if ( Array.isArray( array ) ) {
  13670. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13671. }
  13672. /**
  13673. * This flag can be used for type testing.
  13674. *
  13675. * @type {boolean}
  13676. * @readonly
  13677. * @default true
  13678. */
  13679. this.isBufferAttribute = true;
  13680. /**
  13681. * The ID of the buffer attribute.
  13682. *
  13683. * @name BufferAttribute#id
  13684. * @type {number}
  13685. * @readonly
  13686. */
  13687. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13688. /**
  13689. * The name of the buffer attribute.
  13690. *
  13691. * @type {string}
  13692. */
  13693. this.name = '';
  13694. /**
  13695. * The array holding the attribute data. It should have `itemSize * numVertices`
  13696. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13697. *
  13698. * @type {TypedArray}
  13699. */
  13700. this.array = array;
  13701. /**
  13702. * The number of values of the array that should be associated with a particular vertex.
  13703. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13704. * normal, or color), then the value should be `3`.
  13705. *
  13706. * @type {number}
  13707. */
  13708. this.itemSize = itemSize;
  13709. /**
  13710. * Represents the number of items this buffer attribute stores. It is internally computed
  13711. * by dividing the `array` length by the `itemSize`.
  13712. *
  13713. * @type {number}
  13714. * @readonly
  13715. */
  13716. this.count = array !== undefined ? array.length / itemSize : 0;
  13717. /**
  13718. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13719. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13720. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13721. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13722. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13723. *
  13724. * @type {boolean}
  13725. */
  13726. this.normalized = normalized;
  13727. /**
  13728. * Defines the intended usage pattern of the data store for optimization purposes.
  13729. *
  13730. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13731. * instantiate a new one and set the desired usage before the next render.
  13732. *
  13733. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13734. * @default StaticDrawUsage
  13735. */
  13736. this.usage = StaticDrawUsage;
  13737. /**
  13738. * This can be used to only update some components of stored vectors (for example, just the
  13739. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13740. *
  13741. * @type {Array<Object>}
  13742. */
  13743. this.updateRanges = [];
  13744. /**
  13745. * Configures the bound GPU type for use in shaders.
  13746. *
  13747. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13748. * For lower precision float types, use `Float16BufferAttribute`.
  13749. *
  13750. * @type {(FloatType|IntType)}
  13751. * @default FloatType
  13752. */
  13753. this.gpuType = FloatType;
  13754. /**
  13755. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13756. *
  13757. * @type {number}
  13758. */
  13759. this.version = 0;
  13760. }
  13761. /**
  13762. * A callback function that is executed after the renderer has transferred the attribute
  13763. * array data to the GPU.
  13764. */
  13765. onUploadCallback() {}
  13766. /**
  13767. * Flag to indicate that this attribute has changed and should be re-sent to
  13768. * the GPU. Set this to `true` when you modify the value of the array.
  13769. *
  13770. * @type {number}
  13771. * @default false
  13772. * @param {boolean} value
  13773. */
  13774. set needsUpdate( value ) {
  13775. if ( value === true ) this.version ++;
  13776. }
  13777. /**
  13778. * Sets the usage of this buffer attribute.
  13779. *
  13780. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13781. * @return {BufferAttribute} A reference to this buffer attribute.
  13782. */
  13783. setUsage( value ) {
  13784. this.usage = value;
  13785. return this;
  13786. }
  13787. /**
  13788. * Adds a range of data in the data array to be updated on the GPU.
  13789. *
  13790. * @param {number} start - Position at which to start update.
  13791. * @param {number} count - The number of components to update.
  13792. */
  13793. addUpdateRange( start, count ) {
  13794. this.updateRanges.push( { start, count } );
  13795. }
  13796. /**
  13797. * Clears the update ranges.
  13798. */
  13799. clearUpdateRanges() {
  13800. this.updateRanges.length = 0;
  13801. }
  13802. /**
  13803. * Copies the values of the given buffer attribute to this instance.
  13804. *
  13805. * @param {BufferAttribute} source - The buffer attribute to copy.
  13806. * @return {BufferAttribute} A reference to this instance.
  13807. */
  13808. copy( source ) {
  13809. this.name = source.name;
  13810. this.array = new source.array.constructor( source.array );
  13811. this.itemSize = source.itemSize;
  13812. this.count = source.count;
  13813. this.normalized = source.normalized;
  13814. this.usage = source.usage;
  13815. this.gpuType = source.gpuType;
  13816. return this;
  13817. }
  13818. /**
  13819. * Copies a vector from the given buffer attribute to this one. The start
  13820. * and destination position in the attribute buffers are represented by the
  13821. * given indices.
  13822. *
  13823. * @param {number} index1 - The destination index into this buffer attribute.
  13824. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13825. * @param {number} index2 - The source index into the given buffer attribute.
  13826. * @return {BufferAttribute} A reference to this instance.
  13827. */
  13828. copyAt( index1, attribute, index2 ) {
  13829. index1 *= this.itemSize;
  13830. index2 *= attribute.itemSize;
  13831. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13832. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13833. }
  13834. return this;
  13835. }
  13836. /**
  13837. * Copies the given array data into this buffer attribute.
  13838. *
  13839. * @param {(TypedArray|Array)} array - The array to copy.
  13840. * @return {BufferAttribute} A reference to this instance.
  13841. */
  13842. copyArray( array ) {
  13843. this.array.set( array );
  13844. return this;
  13845. }
  13846. /**
  13847. * Applies the given 3x3 matrix to the given attribute. Works with
  13848. * item size `2` and `3`.
  13849. *
  13850. * @param {Matrix3} m - The matrix to apply.
  13851. * @return {BufferAttribute} A reference to this instance.
  13852. */
  13853. applyMatrix3( m ) {
  13854. if ( this.itemSize === 2 ) {
  13855. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13856. _vector2$1.fromBufferAttribute( this, i );
  13857. _vector2$1.applyMatrix3( m );
  13858. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13859. }
  13860. } else if ( this.itemSize === 3 ) {
  13861. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13862. _vector$9.fromBufferAttribute( this, i );
  13863. _vector$9.applyMatrix3( m );
  13864. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13865. }
  13866. }
  13867. return this;
  13868. }
  13869. /**
  13870. * Applies the given 4x4 matrix to the given attribute. Only works with
  13871. * item size `3`.
  13872. *
  13873. * @param {Matrix4} m - The matrix to apply.
  13874. * @return {BufferAttribute} A reference to this instance.
  13875. */
  13876. applyMatrix4( m ) {
  13877. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13878. _vector$9.fromBufferAttribute( this, i );
  13879. _vector$9.applyMatrix4( m );
  13880. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13881. }
  13882. return this;
  13883. }
  13884. /**
  13885. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13886. * item size `3`.
  13887. *
  13888. * @param {Matrix3} m - The normal matrix to apply.
  13889. * @return {BufferAttribute} A reference to this instance.
  13890. */
  13891. applyNormalMatrix( m ) {
  13892. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13893. _vector$9.fromBufferAttribute( this, i );
  13894. _vector$9.applyNormalMatrix( m );
  13895. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13896. }
  13897. return this;
  13898. }
  13899. /**
  13900. * Applies the given 4x4 matrix to the given attribute. Only works with
  13901. * item size `3` and with direction vectors.
  13902. *
  13903. * @param {Matrix4} m - The matrix to apply.
  13904. * @return {BufferAttribute} A reference to this instance.
  13905. */
  13906. transformDirection( m ) {
  13907. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13908. _vector$9.fromBufferAttribute( this, i );
  13909. _vector$9.transformDirection( m );
  13910. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13911. }
  13912. return this;
  13913. }
  13914. /**
  13915. * Sets the given array data in the buffer attribute.
  13916. *
  13917. * @param {(TypedArray|Array)} value - The array data to set.
  13918. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13919. * @return {BufferAttribute} A reference to this instance.
  13920. */
  13921. set( value, offset = 0 ) {
  13922. // Matching BufferAttribute constructor, do not normalize the array.
  13923. this.array.set( value, offset );
  13924. return this;
  13925. }
  13926. /**
  13927. * Returns the given component of the vector at the given index.
  13928. *
  13929. * @param {number} index - The index into the buffer attribute.
  13930. * @param {number} component - The component index.
  13931. * @return {number} The returned value.
  13932. */
  13933. getComponent( index, component ) {
  13934. let value = this.array[ index * this.itemSize + component ];
  13935. if ( this.normalized ) value = denormalize( value, this.array );
  13936. return value;
  13937. }
  13938. /**
  13939. * Sets the given value to the given component of the vector at the given index.
  13940. *
  13941. * @param {number} index - The index into the buffer attribute.
  13942. * @param {number} component - The component index.
  13943. * @param {number} value - The value to set.
  13944. * @return {BufferAttribute} A reference to this instance.
  13945. */
  13946. setComponent( index, component, value ) {
  13947. if ( this.normalized ) value = normalize( value, this.array );
  13948. this.array[ index * this.itemSize + component ] = value;
  13949. return this;
  13950. }
  13951. /**
  13952. * Returns the x component of the vector at the given index.
  13953. *
  13954. * @param {number} index - The index into the buffer attribute.
  13955. * @return {number} The x component.
  13956. */
  13957. getX( index ) {
  13958. let x = this.array[ index * this.itemSize ];
  13959. if ( this.normalized ) x = denormalize( x, this.array );
  13960. return x;
  13961. }
  13962. /**
  13963. * Sets the x component of the vector at the given index.
  13964. *
  13965. * @param {number} index - The index into the buffer attribute.
  13966. * @param {number} x - The value to set.
  13967. * @return {BufferAttribute} A reference to this instance.
  13968. */
  13969. setX( index, x ) {
  13970. if ( this.normalized ) x = normalize( x, this.array );
  13971. this.array[ index * this.itemSize ] = x;
  13972. return this;
  13973. }
  13974. /**
  13975. * Returns the y component of the vector at the given index.
  13976. *
  13977. * @param {number} index - The index into the buffer attribute.
  13978. * @return {number} The y component.
  13979. */
  13980. getY( index ) {
  13981. let y = this.array[ index * this.itemSize + 1 ];
  13982. if ( this.normalized ) y = denormalize( y, this.array );
  13983. return y;
  13984. }
  13985. /**
  13986. * Sets the y component of the vector at the given index.
  13987. *
  13988. * @param {number} index - The index into the buffer attribute.
  13989. * @param {number} y - The value to set.
  13990. * @return {BufferAttribute} A reference to this instance.
  13991. */
  13992. setY( index, y ) {
  13993. if ( this.normalized ) y = normalize( y, this.array );
  13994. this.array[ index * this.itemSize + 1 ] = y;
  13995. return this;
  13996. }
  13997. /**
  13998. * Returns the z component of the vector at the given index.
  13999. *
  14000. * @param {number} index - The index into the buffer attribute.
  14001. * @return {number} The z component.
  14002. */
  14003. getZ( index ) {
  14004. let z = this.array[ index * this.itemSize + 2 ];
  14005. if ( this.normalized ) z = denormalize( z, this.array );
  14006. return z;
  14007. }
  14008. /**
  14009. * Sets the z component of the vector at the given index.
  14010. *
  14011. * @param {number} index - The index into the buffer attribute.
  14012. * @param {number} z - The value to set.
  14013. * @return {BufferAttribute} A reference to this instance.
  14014. */
  14015. setZ( index, z ) {
  14016. if ( this.normalized ) z = normalize( z, this.array );
  14017. this.array[ index * this.itemSize + 2 ] = z;
  14018. return this;
  14019. }
  14020. /**
  14021. * Returns the w component of the vector at the given index.
  14022. *
  14023. * @param {number} index - The index into the buffer attribute.
  14024. * @return {number} The w component.
  14025. */
  14026. getW( index ) {
  14027. let w = this.array[ index * this.itemSize + 3 ];
  14028. if ( this.normalized ) w = denormalize( w, this.array );
  14029. return w;
  14030. }
  14031. /**
  14032. * Sets the w component of the vector at the given index.
  14033. *
  14034. * @param {number} index - The index into the buffer attribute.
  14035. * @param {number} w - The value to set.
  14036. * @return {BufferAttribute} A reference to this instance.
  14037. */
  14038. setW( index, w ) {
  14039. if ( this.normalized ) w = normalize( w, this.array );
  14040. this.array[ index * this.itemSize + 3 ] = w;
  14041. return this;
  14042. }
  14043. /**
  14044. * Sets the x and y component of the vector at the given index.
  14045. *
  14046. * @param {number} index - The index into the buffer attribute.
  14047. * @param {number} x - The value for the x component to set.
  14048. * @param {number} y - The value for the y component to set.
  14049. * @return {BufferAttribute} A reference to this instance.
  14050. */
  14051. setXY( index, x, y ) {
  14052. index *= this.itemSize;
  14053. if ( this.normalized ) {
  14054. x = normalize( x, this.array );
  14055. y = normalize( y, this.array );
  14056. }
  14057. this.array[ index + 0 ] = x;
  14058. this.array[ index + 1 ] = y;
  14059. return this;
  14060. }
  14061. /**
  14062. * Sets the x, y and z component of the vector at the given index.
  14063. *
  14064. * @param {number} index - The index into the buffer attribute.
  14065. * @param {number} x - The value for the x component to set.
  14066. * @param {number} y - The value for the y component to set.
  14067. * @param {number} z - The value for the z component to set.
  14068. * @return {BufferAttribute} A reference to this instance.
  14069. */
  14070. setXYZ( index, x, y, z ) {
  14071. index *= this.itemSize;
  14072. if ( this.normalized ) {
  14073. x = normalize( x, this.array );
  14074. y = normalize( y, this.array );
  14075. z = normalize( z, this.array );
  14076. }
  14077. this.array[ index + 0 ] = x;
  14078. this.array[ index + 1 ] = y;
  14079. this.array[ index + 2 ] = z;
  14080. return this;
  14081. }
  14082. /**
  14083. * Sets the x, y, z and w component of the vector at the given index.
  14084. *
  14085. * @param {number} index - The index into the buffer attribute.
  14086. * @param {number} x - The value for the x component to set.
  14087. * @param {number} y - The value for the y component to set.
  14088. * @param {number} z - The value for the z component to set.
  14089. * @param {number} w - The value for the w component to set.
  14090. * @return {BufferAttribute} A reference to this instance.
  14091. */
  14092. setXYZW( index, x, y, z, w ) {
  14093. index *= this.itemSize;
  14094. if ( this.normalized ) {
  14095. x = normalize( x, this.array );
  14096. y = normalize( y, this.array );
  14097. z = normalize( z, this.array );
  14098. w = normalize( w, this.array );
  14099. }
  14100. this.array[ index + 0 ] = x;
  14101. this.array[ index + 1 ] = y;
  14102. this.array[ index + 2 ] = z;
  14103. this.array[ index + 3 ] = w;
  14104. return this;
  14105. }
  14106. /**
  14107. * Sets the given callback function that is executed after the Renderer has transferred
  14108. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  14109. * the upload when attribute data are not needed anymore on the CPU side.
  14110. *
  14111. * @param {Function} callback - The `onUpload()` callback.
  14112. * @return {BufferAttribute} A reference to this instance.
  14113. */
  14114. onUpload( callback ) {
  14115. this.onUploadCallback = callback;
  14116. return this;
  14117. }
  14118. /**
  14119. * Returns a new buffer attribute with copied values from this instance.
  14120. *
  14121. * @return {BufferAttribute} A clone of this instance.
  14122. */
  14123. clone() {
  14124. return new this.constructor( this.array, this.itemSize ).copy( this );
  14125. }
  14126. /**
  14127. * Serializes the buffer attribute into JSON.
  14128. *
  14129. * @return {Object} A JSON object representing the serialized buffer attribute.
  14130. */
  14131. toJSON() {
  14132. const data = {
  14133. itemSize: this.itemSize,
  14134. type: this.array.constructor.name,
  14135. array: Array.from( this.array ),
  14136. normalized: this.normalized
  14137. };
  14138. if ( this.name !== '' ) data.name = this.name;
  14139. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  14140. return data;
  14141. }
  14142. }
  14143. /**
  14144. * Convenient class that can be used when creating a `Int8` buffer attribute with
  14145. * a plain `Array` instance.
  14146. *
  14147. * @augments BufferAttribute
  14148. */
  14149. class Int8BufferAttribute extends BufferAttribute {
  14150. /**
  14151. * Constructs a new buffer attribute.
  14152. *
  14153. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  14154. * @param {number} itemSize - The item size.
  14155. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14156. */
  14157. constructor( array, itemSize, normalized ) {
  14158. super( new Int8Array( array ), itemSize, normalized );
  14159. }
  14160. }
  14161. /**
  14162. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  14163. * a plain `Array` instance.
  14164. *
  14165. * @augments BufferAttribute
  14166. */
  14167. class Uint8BufferAttribute extends BufferAttribute {
  14168. /**
  14169. * Constructs a new buffer attribute.
  14170. *
  14171. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  14172. * @param {number} itemSize - The item size.
  14173. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14174. */
  14175. constructor( array, itemSize, normalized ) {
  14176. super( new Uint8Array( array ), itemSize, normalized );
  14177. }
  14178. }
  14179. /**
  14180. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  14181. * a plain `Array` instance.
  14182. *
  14183. * @augments BufferAttribute
  14184. */
  14185. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14186. /**
  14187. * Constructs a new buffer attribute.
  14188. *
  14189. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14190. * @param {number} itemSize - The item size.
  14191. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14192. */
  14193. constructor( array, itemSize, normalized ) {
  14194. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14195. }
  14196. }
  14197. /**
  14198. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14199. * a plain `Array` instance.
  14200. *
  14201. * @augments BufferAttribute
  14202. */
  14203. class Int16BufferAttribute extends BufferAttribute {
  14204. /**
  14205. * Constructs a new buffer attribute.
  14206. *
  14207. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14208. * @param {number} itemSize - The item size.
  14209. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14210. */
  14211. constructor( array, itemSize, normalized ) {
  14212. super( new Int16Array( array ), itemSize, normalized );
  14213. }
  14214. }
  14215. /**
  14216. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14217. * a plain `Array` instance.
  14218. *
  14219. * @augments BufferAttribute
  14220. */
  14221. class Uint16BufferAttribute extends BufferAttribute {
  14222. /**
  14223. * Constructs a new buffer attribute.
  14224. *
  14225. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14226. * @param {number} itemSize - The item size.
  14227. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14228. */
  14229. constructor( array, itemSize, normalized ) {
  14230. super( new Uint16Array( array ), itemSize, normalized );
  14231. }
  14232. }
  14233. /**
  14234. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14235. * a plain `Array` instance.
  14236. *
  14237. * @augments BufferAttribute
  14238. */
  14239. class Int32BufferAttribute extends BufferAttribute {
  14240. /**
  14241. * Constructs a new buffer attribute.
  14242. *
  14243. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14244. * @param {number} itemSize - The item size.
  14245. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14246. */
  14247. constructor( array, itemSize, normalized ) {
  14248. super( new Int32Array( array ), itemSize, normalized );
  14249. }
  14250. }
  14251. /**
  14252. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14253. * a plain `Array` instance.
  14254. *
  14255. * @augments BufferAttribute
  14256. */
  14257. class Uint32BufferAttribute extends BufferAttribute {
  14258. /**
  14259. * Constructs a new buffer attribute.
  14260. *
  14261. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14262. * @param {number} itemSize - The item size.
  14263. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14264. */
  14265. constructor( array, itemSize, normalized ) {
  14266. super( new Uint32Array( array ), itemSize, normalized );
  14267. }
  14268. }
  14269. /**
  14270. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14271. * a plain `Array` instance.
  14272. *
  14273. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14274. * browser support is still problematic.
  14275. *
  14276. * @augments BufferAttribute
  14277. */
  14278. class Float16BufferAttribute extends BufferAttribute {
  14279. /**
  14280. * Constructs a new buffer attribute.
  14281. *
  14282. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14283. * @param {number} itemSize - The item size.
  14284. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14285. */
  14286. constructor( array, itemSize, normalized ) {
  14287. super( new Uint16Array( array ), itemSize, normalized );
  14288. this.isFloat16BufferAttribute = true;
  14289. }
  14290. getX( index ) {
  14291. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14292. if ( this.normalized ) x = denormalize( x, this.array );
  14293. return x;
  14294. }
  14295. setX( index, x ) {
  14296. if ( this.normalized ) x = normalize( x, this.array );
  14297. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14298. return this;
  14299. }
  14300. getY( index ) {
  14301. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14302. if ( this.normalized ) y = denormalize( y, this.array );
  14303. return y;
  14304. }
  14305. setY( index, y ) {
  14306. if ( this.normalized ) y = normalize( y, this.array );
  14307. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14308. return this;
  14309. }
  14310. getZ( index ) {
  14311. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14312. if ( this.normalized ) z = denormalize( z, this.array );
  14313. return z;
  14314. }
  14315. setZ( index, z ) {
  14316. if ( this.normalized ) z = normalize( z, this.array );
  14317. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14318. return this;
  14319. }
  14320. getW( index ) {
  14321. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14322. if ( this.normalized ) w = denormalize( w, this.array );
  14323. return w;
  14324. }
  14325. setW( index, w ) {
  14326. if ( this.normalized ) w = normalize( w, this.array );
  14327. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14328. return this;
  14329. }
  14330. setXY( index, x, y ) {
  14331. index *= this.itemSize;
  14332. if ( this.normalized ) {
  14333. x = normalize( x, this.array );
  14334. y = normalize( y, this.array );
  14335. }
  14336. this.array[ index + 0 ] = toHalfFloat( x );
  14337. this.array[ index + 1 ] = toHalfFloat( y );
  14338. return this;
  14339. }
  14340. setXYZ( index, x, y, z ) {
  14341. index *= this.itemSize;
  14342. if ( this.normalized ) {
  14343. x = normalize( x, this.array );
  14344. y = normalize( y, this.array );
  14345. z = normalize( z, this.array );
  14346. }
  14347. this.array[ index + 0 ] = toHalfFloat( x );
  14348. this.array[ index + 1 ] = toHalfFloat( y );
  14349. this.array[ index + 2 ] = toHalfFloat( z );
  14350. return this;
  14351. }
  14352. setXYZW( index, x, y, z, w ) {
  14353. index *= this.itemSize;
  14354. if ( this.normalized ) {
  14355. x = normalize( x, this.array );
  14356. y = normalize( y, this.array );
  14357. z = normalize( z, this.array );
  14358. w = normalize( w, this.array );
  14359. }
  14360. this.array[ index + 0 ] = toHalfFloat( x );
  14361. this.array[ index + 1 ] = toHalfFloat( y );
  14362. this.array[ index + 2 ] = toHalfFloat( z );
  14363. this.array[ index + 3 ] = toHalfFloat( w );
  14364. return this;
  14365. }
  14366. }
  14367. /**
  14368. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14369. * a plain `Array` instance.
  14370. *
  14371. * @augments BufferAttribute
  14372. */
  14373. class Float32BufferAttribute extends BufferAttribute {
  14374. /**
  14375. * Constructs a new buffer attribute.
  14376. *
  14377. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14378. * @param {number} itemSize - The item size.
  14379. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14380. */
  14381. constructor( array, itemSize, normalized ) {
  14382. super( new Float32Array( array ), itemSize, normalized );
  14383. }
  14384. }
  14385. let _id$2 = 0;
  14386. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14387. const _obj = /*@__PURE__*/ new Object3D();
  14388. const _offset = /*@__PURE__*/ new Vector3();
  14389. const _box$2 = /*@__PURE__*/ new Box3();
  14390. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14391. const _vector$8 = /*@__PURE__*/ new Vector3();
  14392. /**
  14393. * A representation of mesh, line, or point geometry. Includes vertex
  14394. * positions, face indices, normals, colors, UVs, and custom attributes
  14395. * within buffers, reducing the cost of passing all this data to the GPU.
  14396. *
  14397. * ```js
  14398. * const geometry = new THREE.BufferGeometry();
  14399. * // create a simple square shape. We duplicate the top left and bottom right
  14400. * // vertices because each vertex needs to appear once per triangle.
  14401. * const vertices = new Float32Array( [
  14402. * -1.0, -1.0, 1.0, // v0
  14403. * 1.0, -1.0, 1.0, // v1
  14404. * 1.0, 1.0, 1.0, // v2
  14405. *
  14406. * 1.0, 1.0, 1.0, // v3
  14407. * -1.0, 1.0, 1.0, // v4
  14408. * -1.0, -1.0, 1.0 // v5
  14409. * ] );
  14410. * // itemSize = 3 because there are 3 values (components) per vertex
  14411. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14412. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14413. * const mesh = new THREE.Mesh( geometry, material );
  14414. * ```
  14415. *
  14416. * @augments EventDispatcher
  14417. */
  14418. class BufferGeometry extends EventDispatcher {
  14419. /**
  14420. * Constructs a new geometry.
  14421. */
  14422. constructor() {
  14423. super();
  14424. /**
  14425. * This flag can be used for type testing.
  14426. *
  14427. * @type {boolean}
  14428. * @readonly
  14429. * @default true
  14430. */
  14431. this.isBufferGeometry = true;
  14432. /**
  14433. * The ID of the geometry.
  14434. *
  14435. * @name BufferGeometry#id
  14436. * @type {number}
  14437. * @readonly
  14438. */
  14439. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14440. /**
  14441. * The UUID of the geometry.
  14442. *
  14443. * @type {string}
  14444. * @readonly
  14445. */
  14446. this.uuid = generateUUID();
  14447. /**
  14448. * The name of the geometry.
  14449. *
  14450. * @type {string}
  14451. */
  14452. this.name = '';
  14453. this.type = 'BufferGeometry';
  14454. /**
  14455. * Allows for vertices to be re-used across multiple triangles; this is
  14456. * called using "indexed triangles". Each triangle is associated with the
  14457. * indices of three vertices. This attribute therefore stores the index of
  14458. * each vertex for each triangular face. If this attribute is not set, the
  14459. * renderer assumes that each three contiguous positions represent a single triangle.
  14460. *
  14461. * @type {?BufferAttribute}
  14462. * @default null
  14463. */
  14464. this.index = null;
  14465. /**
  14466. * A (storage) buffer attribute which was generated with a compute shader and
  14467. * now defines indirect draw calls.
  14468. *
  14469. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14470. *
  14471. * @type {?BufferAttribute}
  14472. * @default null
  14473. */
  14474. this.indirect = null;
  14475. /**
  14476. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14477. *
  14478. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14479. *
  14480. * @type {number|Array<number>}
  14481. * @default 0
  14482. */
  14483. this.indirectOffset = 0;
  14484. /**
  14485. * This dictionary has as id the name of the attribute to be set and as value
  14486. * the buffer attribute to set it to. Rather than accessing this property directly,
  14487. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14488. *
  14489. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14490. */
  14491. this.attributes = {};
  14492. /**
  14493. * This dictionary holds the morph targets of the geometry.
  14494. *
  14495. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14496. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14497. *
  14498. * @type {Object}
  14499. */
  14500. this.morphAttributes = {};
  14501. /**
  14502. * Used to control the morph target behavior; when set to `true`, the morph
  14503. * target data is treated as relative offsets, rather than as absolute
  14504. * positions/normals.
  14505. *
  14506. * @type {boolean}
  14507. * @default false
  14508. */
  14509. this.morphTargetsRelative = false;
  14510. /**
  14511. * Split the geometry into groups, each of which will be rendered in a
  14512. * separate draw call. This allows an array of materials to be used with the geometry.
  14513. *
  14514. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14515. *
  14516. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14517. * indices, and must not leave vertices or indices unused.
  14518. *
  14519. * @type {Array<Object>}
  14520. */
  14521. this.groups = [];
  14522. /**
  14523. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14524. *
  14525. * @type {?Box3}
  14526. * @default null
  14527. */
  14528. this.boundingBox = null;
  14529. /**
  14530. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14531. *
  14532. * @type {?Sphere}
  14533. * @default null
  14534. */
  14535. this.boundingSphere = null;
  14536. /**
  14537. * Determines the part of the geometry to render. This should not be set directly,
  14538. * instead use `setDrawRange()`.
  14539. *
  14540. * @type {{start:number,count:number}}
  14541. */
  14542. this.drawRange = { start: 0, count: Infinity };
  14543. /**
  14544. * An object that can be used to store custom data about the geometry.
  14545. * It should not hold references to functions as these will not be cloned.
  14546. *
  14547. * @type {Object}
  14548. */
  14549. this.userData = {};
  14550. }
  14551. /**
  14552. * Returns the index of this geometry.
  14553. *
  14554. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14555. */
  14556. getIndex() {
  14557. return this.index;
  14558. }
  14559. /**
  14560. * Sets the given index to this geometry.
  14561. *
  14562. * @param {Array<number>|BufferAttribute} index - The index to set.
  14563. * @return {BufferGeometry} A reference to this instance.
  14564. */
  14565. setIndex( index ) {
  14566. if ( Array.isArray( index ) ) {
  14567. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14568. } else {
  14569. this.index = index;
  14570. }
  14571. return this;
  14572. }
  14573. /**
  14574. * Sets the given indirect attribute to this geometry.
  14575. *
  14576. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14577. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14578. * @return {BufferGeometry} A reference to this instance.
  14579. */
  14580. setIndirect( indirect, indirectOffset = 0 ) {
  14581. this.indirect = indirect;
  14582. this.indirectOffset = indirectOffset;
  14583. return this;
  14584. }
  14585. /**
  14586. * Returns the indirect attribute of this geometry.
  14587. *
  14588. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14589. */
  14590. getIndirect() {
  14591. return this.indirect;
  14592. }
  14593. /**
  14594. * Returns the buffer attribute for the given name.
  14595. *
  14596. * @param {string} name - The attribute name.
  14597. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14598. * Returns `undefined` if not attribute has been found.
  14599. */
  14600. getAttribute( name ) {
  14601. return this.attributes[ name ];
  14602. }
  14603. /**
  14604. * Sets the given attribute for the given name.
  14605. *
  14606. * @param {string} name - The attribute name.
  14607. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14608. * @return {BufferGeometry} A reference to this instance.
  14609. */
  14610. setAttribute( name, attribute ) {
  14611. this.attributes[ name ] = attribute;
  14612. return this;
  14613. }
  14614. /**
  14615. * Deletes the attribute for the given name.
  14616. *
  14617. * @param {string} name - The attribute name to delete.
  14618. * @return {BufferGeometry} A reference to this instance.
  14619. */
  14620. deleteAttribute( name ) {
  14621. delete this.attributes[ name ];
  14622. return this;
  14623. }
  14624. /**
  14625. * Returns `true` if this geometry has an attribute for the given name.
  14626. *
  14627. * @param {string} name - The attribute name.
  14628. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14629. */
  14630. hasAttribute( name ) {
  14631. return this.attributes[ name ] !== undefined;
  14632. }
  14633. /**
  14634. * Adds a group to this geometry.
  14635. *
  14636. * @param {number} start - The first element in this draw call. That is the first
  14637. * vertex for non-indexed geometry, otherwise the first triangle index.
  14638. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14639. * @param {number} [materialIndex=0] - The material array index to use.
  14640. */
  14641. addGroup( start, count, materialIndex = 0 ) {
  14642. this.groups.push( {
  14643. start: start,
  14644. count: count,
  14645. materialIndex: materialIndex
  14646. } );
  14647. }
  14648. /**
  14649. * Clears all groups.
  14650. */
  14651. clearGroups() {
  14652. this.groups = [];
  14653. }
  14654. /**
  14655. * Sets the draw range for this geometry.
  14656. *
  14657. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14658. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14659. * For indexed BufferGeometry, `count` is the number of indices to render.
  14660. */
  14661. setDrawRange( start, count ) {
  14662. this.drawRange.start = start;
  14663. this.drawRange.count = count;
  14664. }
  14665. /**
  14666. * Applies the given 4x4 transformation matrix to the geometry.
  14667. *
  14668. * @param {Matrix4} matrix - The matrix to apply.
  14669. * @return {BufferGeometry} A reference to this instance.
  14670. */
  14671. applyMatrix4( matrix ) {
  14672. const position = this.attributes.position;
  14673. if ( position !== undefined ) {
  14674. position.applyMatrix4( matrix );
  14675. position.needsUpdate = true;
  14676. }
  14677. const normal = this.attributes.normal;
  14678. if ( normal !== undefined ) {
  14679. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14680. normal.applyNormalMatrix( normalMatrix );
  14681. normal.needsUpdate = true;
  14682. }
  14683. const tangent = this.attributes.tangent;
  14684. if ( tangent !== undefined ) {
  14685. tangent.transformDirection( matrix );
  14686. tangent.needsUpdate = true;
  14687. }
  14688. if ( this.boundingBox !== null ) {
  14689. this.computeBoundingBox();
  14690. }
  14691. if ( this.boundingSphere !== null ) {
  14692. this.computeBoundingSphere();
  14693. }
  14694. return this;
  14695. }
  14696. /**
  14697. * Applies the rotation represented by the Quaternion to the geometry.
  14698. *
  14699. * @param {Quaternion} q - The Quaternion to apply.
  14700. * @return {BufferGeometry} A reference to this instance.
  14701. */
  14702. applyQuaternion( q ) {
  14703. _m1$2.makeRotationFromQuaternion( q );
  14704. this.applyMatrix4( _m1$2 );
  14705. return this;
  14706. }
  14707. /**
  14708. * Rotates the geometry about the X axis. This is typically done as a one time
  14709. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14710. * real-time mesh rotation.
  14711. *
  14712. * @param {number} angle - The angle in radians.
  14713. * @return {BufferGeometry} A reference to this instance.
  14714. */
  14715. rotateX( angle ) {
  14716. // rotate geometry around world x-axis
  14717. _m1$2.makeRotationX( angle );
  14718. this.applyMatrix4( _m1$2 );
  14719. return this;
  14720. }
  14721. /**
  14722. * Rotates the geometry about the Y axis. This is typically done as a one time
  14723. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14724. * real-time mesh rotation.
  14725. *
  14726. * @param {number} angle - The angle in radians.
  14727. * @return {BufferGeometry} A reference to this instance.
  14728. */
  14729. rotateY( angle ) {
  14730. // rotate geometry around world y-axis
  14731. _m1$2.makeRotationY( angle );
  14732. this.applyMatrix4( _m1$2 );
  14733. return this;
  14734. }
  14735. /**
  14736. * Rotates the geometry about the Z axis. This is typically done as a one time
  14737. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14738. * real-time mesh rotation.
  14739. *
  14740. * @param {number} angle - The angle in radians.
  14741. * @return {BufferGeometry} A reference to this instance.
  14742. */
  14743. rotateZ( angle ) {
  14744. // rotate geometry around world z-axis
  14745. _m1$2.makeRotationZ( angle );
  14746. this.applyMatrix4( _m1$2 );
  14747. return this;
  14748. }
  14749. /**
  14750. * Translates the geometry. This is typically done as a one time
  14751. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14752. * real-time mesh rotation.
  14753. *
  14754. * @param {number} x - The x offset.
  14755. * @param {number} y - The y offset.
  14756. * @param {number} z - The z offset.
  14757. * @return {BufferGeometry} A reference to this instance.
  14758. */
  14759. translate( x, y, z ) {
  14760. // translate geometry
  14761. _m1$2.makeTranslation( x, y, z );
  14762. this.applyMatrix4( _m1$2 );
  14763. return this;
  14764. }
  14765. /**
  14766. * Scales the geometry. This is typically done as a one time
  14767. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14768. * real-time mesh rotation.
  14769. *
  14770. * @param {number} x - The x scale.
  14771. * @param {number} y - The y scale.
  14772. * @param {number} z - The z scale.
  14773. * @return {BufferGeometry} A reference to this instance.
  14774. */
  14775. scale( x, y, z ) {
  14776. // scale geometry
  14777. _m1$2.makeScale( x, y, z );
  14778. this.applyMatrix4( _m1$2 );
  14779. return this;
  14780. }
  14781. /**
  14782. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14783. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14784. * real-time mesh rotation.
  14785. *
  14786. * @param {Vector3} vector - The target point.
  14787. * @return {BufferGeometry} A reference to this instance.
  14788. */
  14789. lookAt( vector ) {
  14790. _obj.lookAt( vector );
  14791. _obj.updateMatrix();
  14792. this.applyMatrix4( _obj.matrix );
  14793. return this;
  14794. }
  14795. /**
  14796. * Center the geometry based on its bounding box.
  14797. *
  14798. * @return {BufferGeometry} A reference to this instance.
  14799. */
  14800. center() {
  14801. this.computeBoundingBox();
  14802. this.boundingBox.getCenter( _offset ).negate();
  14803. this.translate( _offset.x, _offset.y, _offset.z );
  14804. return this;
  14805. }
  14806. /**
  14807. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14808. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14809. * set to `0`.
  14810. *
  14811. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14812. * data from the array. The length of the array must match the vertex count.
  14813. *
  14814. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14815. * @return {BufferGeometry} A reference to this instance.
  14816. */
  14817. setFromPoints( points ) {
  14818. const positionAttribute = this.getAttribute( 'position' );
  14819. if ( positionAttribute === undefined ) {
  14820. const position = [];
  14821. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14822. const point = points[ i ];
  14823. position.push( point.x, point.y, point.z || 0 );
  14824. }
  14825. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14826. } else {
  14827. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14828. for ( let i = 0; i < l; i ++ ) {
  14829. const point = points[ i ];
  14830. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14831. }
  14832. if ( points.length > positionAttribute.count ) {
  14833. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14834. }
  14835. positionAttribute.needsUpdate = true;
  14836. }
  14837. return this;
  14838. }
  14839. /**
  14840. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14841. * The bounding box is not computed by the engine; it must be computed by your app.
  14842. * You may need to recompute the bounding box if the geometry vertices are modified.
  14843. */
  14844. computeBoundingBox() {
  14845. if ( this.boundingBox === null ) {
  14846. this.boundingBox = new Box3();
  14847. }
  14848. const position = this.attributes.position;
  14849. const morphAttributesPosition = this.morphAttributes.position;
  14850. if ( position && position.isGLBufferAttribute ) {
  14851. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14852. this.boundingBox.set(
  14853. new Vector3( - Infinity, - Infinity, - Infinity ),
  14854. new Vector3( + Infinity, + Infinity, + Infinity )
  14855. );
  14856. return;
  14857. }
  14858. if ( position !== undefined ) {
  14859. this.boundingBox.setFromBufferAttribute( position );
  14860. // process morph attributes if present
  14861. if ( morphAttributesPosition ) {
  14862. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14863. const morphAttribute = morphAttributesPosition[ i ];
  14864. _box$2.setFromBufferAttribute( morphAttribute );
  14865. if ( this.morphTargetsRelative ) {
  14866. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14867. this.boundingBox.expandByPoint( _vector$8 );
  14868. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14869. this.boundingBox.expandByPoint( _vector$8 );
  14870. } else {
  14871. this.boundingBox.expandByPoint( _box$2.min );
  14872. this.boundingBox.expandByPoint( _box$2.max );
  14873. }
  14874. }
  14875. }
  14876. } else {
  14877. this.boundingBox.makeEmpty();
  14878. }
  14879. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14880. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14881. }
  14882. }
  14883. /**
  14884. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14885. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14886. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14887. */
  14888. computeBoundingSphere() {
  14889. if ( this.boundingSphere === null ) {
  14890. this.boundingSphere = new Sphere();
  14891. }
  14892. const position = this.attributes.position;
  14893. const morphAttributesPosition = this.morphAttributes.position;
  14894. if ( position && position.isGLBufferAttribute ) {
  14895. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14896. this.boundingSphere.set( new Vector3(), Infinity );
  14897. return;
  14898. }
  14899. if ( position ) {
  14900. // first, find the center of the bounding sphere
  14901. const center = this.boundingSphere.center;
  14902. _box$2.setFromBufferAttribute( position );
  14903. // process morph attributes if present
  14904. if ( morphAttributesPosition ) {
  14905. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14906. const morphAttribute = morphAttributesPosition[ i ];
  14907. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14908. if ( this.morphTargetsRelative ) {
  14909. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14910. _box$2.expandByPoint( _vector$8 );
  14911. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14912. _box$2.expandByPoint( _vector$8 );
  14913. } else {
  14914. _box$2.expandByPoint( _boxMorphTargets.min );
  14915. _box$2.expandByPoint( _boxMorphTargets.max );
  14916. }
  14917. }
  14918. }
  14919. _box$2.getCenter( center );
  14920. // second, try to find a boundingSphere with a radius smaller than the
  14921. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14922. let maxRadiusSq = 0;
  14923. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14924. _vector$8.fromBufferAttribute( position, i );
  14925. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14926. }
  14927. // process morph attributes if present
  14928. if ( morphAttributesPosition ) {
  14929. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14930. const morphAttribute = morphAttributesPosition[ i ];
  14931. const morphTargetsRelative = this.morphTargetsRelative;
  14932. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14933. _vector$8.fromBufferAttribute( morphAttribute, j );
  14934. if ( morphTargetsRelative ) {
  14935. _offset.fromBufferAttribute( position, j );
  14936. _vector$8.add( _offset );
  14937. }
  14938. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14939. }
  14940. }
  14941. }
  14942. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14943. if ( isNaN( this.boundingSphere.radius ) ) {
  14944. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14945. }
  14946. }
  14947. }
  14948. /**
  14949. * Calculates and adds a tangent attribute to this geometry.
  14950. *
  14951. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14952. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14953. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14954. */
  14955. computeTangents() {
  14956. const index = this.index;
  14957. const attributes = this.attributes;
  14958. // based on http://www.terathon.com/code/tangent.html
  14959. // (per vertex tangents)
  14960. if ( index === null ||
  14961. attributes.position === undefined ||
  14962. attributes.normal === undefined ||
  14963. attributes.uv === undefined ) {
  14964. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14965. return;
  14966. }
  14967. const positionAttribute = attributes.position;
  14968. const normalAttribute = attributes.normal;
  14969. const uvAttribute = attributes.uv;
  14970. if ( this.hasAttribute( 'tangent' ) === false ) {
  14971. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14972. }
  14973. const tangentAttribute = this.getAttribute( 'tangent' );
  14974. const tan1 = [], tan2 = [];
  14975. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14976. tan1[ i ] = new Vector3();
  14977. tan2[ i ] = new Vector3();
  14978. }
  14979. const vA = new Vector3(),
  14980. vB = new Vector3(),
  14981. vC = new Vector3(),
  14982. uvA = new Vector2(),
  14983. uvB = new Vector2(),
  14984. uvC = new Vector2(),
  14985. sdir = new Vector3(),
  14986. tdir = new Vector3();
  14987. function handleTriangle( a, b, c ) {
  14988. vA.fromBufferAttribute( positionAttribute, a );
  14989. vB.fromBufferAttribute( positionAttribute, b );
  14990. vC.fromBufferAttribute( positionAttribute, c );
  14991. uvA.fromBufferAttribute( uvAttribute, a );
  14992. uvB.fromBufferAttribute( uvAttribute, b );
  14993. uvC.fromBufferAttribute( uvAttribute, c );
  14994. vB.sub( vA );
  14995. vC.sub( vA );
  14996. uvB.sub( uvA );
  14997. uvC.sub( uvA );
  14998. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14999. // silently ignore degenerate uv triangles having coincident or colinear vertices
  15000. if ( ! isFinite( r ) ) return;
  15001. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  15002. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  15003. tan1[ a ].add( sdir );
  15004. tan1[ b ].add( sdir );
  15005. tan1[ c ].add( sdir );
  15006. tan2[ a ].add( tdir );
  15007. tan2[ b ].add( tdir );
  15008. tan2[ c ].add( tdir );
  15009. }
  15010. let groups = this.groups;
  15011. if ( groups.length === 0 ) {
  15012. groups = [ {
  15013. start: 0,
  15014. count: index.count
  15015. } ];
  15016. }
  15017. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15018. const group = groups[ i ];
  15019. const start = group.start;
  15020. const count = group.count;
  15021. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15022. handleTriangle(
  15023. index.getX( j + 0 ),
  15024. index.getX( j + 1 ),
  15025. index.getX( j + 2 )
  15026. );
  15027. }
  15028. }
  15029. const tmp = new Vector3(), tmp2 = new Vector3();
  15030. const n = new Vector3(), n2 = new Vector3();
  15031. function handleVertex( v ) {
  15032. n.fromBufferAttribute( normalAttribute, v );
  15033. n2.copy( n );
  15034. const t = tan1[ v ];
  15035. // Gram-Schmidt orthogonalize
  15036. tmp.copy( t );
  15037. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  15038. // Calculate handedness
  15039. tmp2.crossVectors( n2, t );
  15040. const test = tmp2.dot( tan2[ v ] );
  15041. const w = ( test < 0.0 ) ? -1 : 1.0;
  15042. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  15043. }
  15044. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  15045. const group = groups[ i ];
  15046. const start = group.start;
  15047. const count = group.count;
  15048. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  15049. handleVertex( index.getX( j + 0 ) );
  15050. handleVertex( index.getX( j + 1 ) );
  15051. handleVertex( index.getX( j + 2 ) );
  15052. }
  15053. }
  15054. }
  15055. /**
  15056. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  15057. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  15058. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  15059. * to be the same as the face normal.
  15060. */
  15061. computeVertexNormals() {
  15062. const index = this.index;
  15063. const positionAttribute = this.getAttribute( 'position' );
  15064. if ( positionAttribute !== undefined ) {
  15065. let normalAttribute = this.getAttribute( 'normal' );
  15066. if ( normalAttribute === undefined ) {
  15067. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  15068. this.setAttribute( 'normal', normalAttribute );
  15069. } else {
  15070. // reset existing normals to zero
  15071. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  15072. normalAttribute.setXYZ( i, 0, 0, 0 );
  15073. }
  15074. }
  15075. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  15076. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  15077. const cb = new Vector3(), ab = new Vector3();
  15078. // indexed elements
  15079. if ( index ) {
  15080. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  15081. const vA = index.getX( i + 0 );
  15082. const vB = index.getX( i + 1 );
  15083. const vC = index.getX( i + 2 );
  15084. pA.fromBufferAttribute( positionAttribute, vA );
  15085. pB.fromBufferAttribute( positionAttribute, vB );
  15086. pC.fromBufferAttribute( positionAttribute, vC );
  15087. cb.subVectors( pC, pB );
  15088. ab.subVectors( pA, pB );
  15089. cb.cross( ab );
  15090. nA.fromBufferAttribute( normalAttribute, vA );
  15091. nB.fromBufferAttribute( normalAttribute, vB );
  15092. nC.fromBufferAttribute( normalAttribute, vC );
  15093. nA.add( cb );
  15094. nB.add( cb );
  15095. nC.add( cb );
  15096. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  15097. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  15098. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  15099. }
  15100. } else {
  15101. // non-indexed elements (unconnected triangle soup)
  15102. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  15103. pA.fromBufferAttribute( positionAttribute, i + 0 );
  15104. pB.fromBufferAttribute( positionAttribute, i + 1 );
  15105. pC.fromBufferAttribute( positionAttribute, i + 2 );
  15106. cb.subVectors( pC, pB );
  15107. ab.subVectors( pA, pB );
  15108. cb.cross( ab );
  15109. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  15110. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  15111. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  15112. }
  15113. }
  15114. this.normalizeNormals();
  15115. normalAttribute.needsUpdate = true;
  15116. }
  15117. }
  15118. /**
  15119. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  15120. * correct lighting on the geometry surfaces.
  15121. */
  15122. normalizeNormals() {
  15123. const normals = this.attributes.normal;
  15124. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  15125. _vector$8.fromBufferAttribute( normals, i );
  15126. _vector$8.normalize();
  15127. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  15128. }
  15129. }
  15130. /**
  15131. * Return a new non-index version of this indexed geometry. If the geometry
  15132. * is already non-indexed, the method is a NOOP.
  15133. *
  15134. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  15135. */
  15136. toNonIndexed() {
  15137. function convertBufferAttribute( attribute, indices ) {
  15138. const array = attribute.array;
  15139. const itemSize = attribute.itemSize;
  15140. const normalized = attribute.normalized;
  15141. const array2 = new array.constructor( indices.length * itemSize );
  15142. let index = 0, index2 = 0;
  15143. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  15144. if ( attribute.isInterleavedBufferAttribute ) {
  15145. index = indices[ i ] * attribute.data.stride + attribute.offset;
  15146. } else {
  15147. index = indices[ i ] * itemSize;
  15148. }
  15149. for ( let j = 0; j < itemSize; j ++ ) {
  15150. array2[ index2 ++ ] = array[ index ++ ];
  15151. }
  15152. }
  15153. return new BufferAttribute( array2, itemSize, normalized );
  15154. }
  15155. //
  15156. if ( this.index === null ) {
  15157. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  15158. return this;
  15159. }
  15160. const geometry2 = new BufferGeometry();
  15161. const indices = this.index.array;
  15162. const attributes = this.attributes;
  15163. // attributes
  15164. for ( const name in attributes ) {
  15165. const attribute = attributes[ name ];
  15166. const newAttribute = convertBufferAttribute( attribute, indices );
  15167. geometry2.setAttribute( name, newAttribute );
  15168. }
  15169. // morph attributes
  15170. const morphAttributes = this.morphAttributes;
  15171. for ( const name in morphAttributes ) {
  15172. const morphArray = [];
  15173. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15174. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  15175. const attribute = morphAttribute[ i ];
  15176. const newAttribute = convertBufferAttribute( attribute, indices );
  15177. morphArray.push( newAttribute );
  15178. }
  15179. geometry2.morphAttributes[ name ] = morphArray;
  15180. }
  15181. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  15182. // groups
  15183. const groups = this.groups;
  15184. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15185. const group = groups[ i ];
  15186. geometry2.addGroup( group.start, group.count, group.materialIndex );
  15187. }
  15188. return geometry2;
  15189. }
  15190. /**
  15191. * Serializes the geometry into JSON.
  15192. *
  15193. * @return {Object} A JSON object representing the serialized geometry.
  15194. */
  15195. toJSON() {
  15196. const data = {
  15197. metadata: {
  15198. version: 4.7,
  15199. type: 'BufferGeometry',
  15200. generator: 'BufferGeometry.toJSON'
  15201. }
  15202. };
  15203. // standard BufferGeometry serialization
  15204. data.uuid = this.uuid;
  15205. data.type = this.type;
  15206. if ( this.name !== '' ) data.name = this.name;
  15207. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15208. if ( this.parameters !== undefined ) {
  15209. const parameters = this.parameters;
  15210. for ( const key in parameters ) {
  15211. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15212. }
  15213. return data;
  15214. }
  15215. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15216. data.data = { attributes: {} };
  15217. const index = this.index;
  15218. if ( index !== null ) {
  15219. data.data.index = {
  15220. type: index.array.constructor.name,
  15221. array: Array.prototype.slice.call( index.array )
  15222. };
  15223. }
  15224. const attributes = this.attributes;
  15225. for ( const key in attributes ) {
  15226. const attribute = attributes[ key ];
  15227. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15228. }
  15229. const morphAttributes = {};
  15230. let hasMorphAttributes = false;
  15231. for ( const key in this.morphAttributes ) {
  15232. const attributeArray = this.morphAttributes[ key ];
  15233. const array = [];
  15234. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15235. const attribute = attributeArray[ i ];
  15236. array.push( attribute.toJSON( data.data ) );
  15237. }
  15238. if ( array.length > 0 ) {
  15239. morphAttributes[ key ] = array;
  15240. hasMorphAttributes = true;
  15241. }
  15242. }
  15243. if ( hasMorphAttributes ) {
  15244. data.data.morphAttributes = morphAttributes;
  15245. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15246. }
  15247. const groups = this.groups;
  15248. if ( groups.length > 0 ) {
  15249. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15250. }
  15251. const boundingSphere = this.boundingSphere;
  15252. if ( boundingSphere !== null ) {
  15253. data.data.boundingSphere = boundingSphere.toJSON();
  15254. }
  15255. return data;
  15256. }
  15257. /**
  15258. * Returns a new geometry with copied values from this instance.
  15259. *
  15260. * @return {BufferGeometry} A clone of this instance.
  15261. */
  15262. clone() {
  15263. return new this.constructor().copy( this );
  15264. }
  15265. /**
  15266. * Copies the values of the given geometry to this instance.
  15267. *
  15268. * @param {BufferGeometry} source - The geometry to copy.
  15269. * @return {BufferGeometry} A reference to this instance.
  15270. */
  15271. copy( source ) {
  15272. // reset
  15273. this.index = null;
  15274. this.attributes = {};
  15275. this.morphAttributes = {};
  15276. this.groups = [];
  15277. this.boundingBox = null;
  15278. this.boundingSphere = null;
  15279. // used for storing cloned, shared data
  15280. const data = {};
  15281. // name
  15282. this.name = source.name;
  15283. // index
  15284. const index = source.index;
  15285. if ( index !== null ) {
  15286. this.setIndex( index.clone() );
  15287. }
  15288. // attributes
  15289. const attributes = source.attributes;
  15290. for ( const name in attributes ) {
  15291. const attribute = attributes[ name ];
  15292. this.setAttribute( name, attribute.clone( data ) );
  15293. }
  15294. // morph attributes
  15295. const morphAttributes = source.morphAttributes;
  15296. for ( const name in morphAttributes ) {
  15297. const array = [];
  15298. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15299. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15300. array.push( morphAttribute[ i ].clone( data ) );
  15301. }
  15302. this.morphAttributes[ name ] = array;
  15303. }
  15304. this.morphTargetsRelative = source.morphTargetsRelative;
  15305. // groups
  15306. const groups = source.groups;
  15307. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15308. const group = groups[ i ];
  15309. this.addGroup( group.start, group.count, group.materialIndex );
  15310. }
  15311. // bounding box
  15312. const boundingBox = source.boundingBox;
  15313. if ( boundingBox !== null ) {
  15314. this.boundingBox = boundingBox.clone();
  15315. }
  15316. // bounding sphere
  15317. const boundingSphere = source.boundingSphere;
  15318. if ( boundingSphere !== null ) {
  15319. this.boundingSphere = boundingSphere.clone();
  15320. }
  15321. // draw range
  15322. this.drawRange.start = source.drawRange.start;
  15323. this.drawRange.count = source.drawRange.count;
  15324. // user data
  15325. this.userData = source.userData;
  15326. return this;
  15327. }
  15328. /**
  15329. * Frees the GPU-related resources allocated by this instance. Call this
  15330. * method whenever this instance is no longer used in your app.
  15331. *
  15332. * @fires BufferGeometry#dispose
  15333. */
  15334. dispose() {
  15335. this.dispatchEvent( { type: 'dispose' } );
  15336. }
  15337. }
  15338. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15339. const _ray$3 = /*@__PURE__*/ new Ray();
  15340. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15341. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15342. const _vA$1 = /*@__PURE__*/ new Vector3();
  15343. const _vB$1 = /*@__PURE__*/ new Vector3();
  15344. const _vC$1 = /*@__PURE__*/ new Vector3();
  15345. const _tempA = /*@__PURE__*/ new Vector3();
  15346. const _morphA = /*@__PURE__*/ new Vector3();
  15347. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15348. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15349. /**
  15350. * Class representing triangular polygon mesh based objects.
  15351. *
  15352. * ```js
  15353. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15354. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15355. * const mesh = new THREE.Mesh( geometry, material );
  15356. * scene.add( mesh );
  15357. * ```
  15358. *
  15359. * @augments Object3D
  15360. */
  15361. class Mesh extends Object3D {
  15362. /**
  15363. * Constructs a new mesh.
  15364. *
  15365. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15366. * @param {Material|Array<Material>} [material] - The mesh material.
  15367. */
  15368. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15369. super();
  15370. /**
  15371. * This flag can be used for type testing.
  15372. *
  15373. * @type {boolean}
  15374. * @readonly
  15375. * @default true
  15376. */
  15377. this.isMesh = true;
  15378. this.type = 'Mesh';
  15379. /**
  15380. * The mesh geometry.
  15381. *
  15382. * @type {BufferGeometry}
  15383. */
  15384. this.geometry = geometry;
  15385. /**
  15386. * The mesh material.
  15387. *
  15388. * @type {Material|Array<Material>}
  15389. * @default MeshBasicMaterial
  15390. */
  15391. this.material = material;
  15392. /**
  15393. * A dictionary representing the morph targets in the geometry. The key is the
  15394. * morph targets name, the value its attribute index. This member is `undefined`
  15395. * by default and only set when morph targets are detected in the geometry.
  15396. *
  15397. * @type {Object<string,number>|undefined}
  15398. * @default undefined
  15399. */
  15400. this.morphTargetDictionary = undefined;
  15401. /**
  15402. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15403. * is applied. This member is `undefined` by default and only set when morph targets are
  15404. * detected in the geometry.
  15405. *
  15406. * @type {Array<number>|undefined}
  15407. * @default undefined
  15408. */
  15409. this.morphTargetInfluences = undefined;
  15410. /**
  15411. * The number of instances of this mesh.
  15412. * Can only be used with {@link WebGPURenderer}.
  15413. *
  15414. * @type {number}
  15415. * @default 1
  15416. */
  15417. this.count = 1;
  15418. this.updateMorphTargets();
  15419. }
  15420. copy( source, recursive ) {
  15421. super.copy( source, recursive );
  15422. if ( source.morphTargetInfluences !== undefined ) {
  15423. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15424. }
  15425. if ( source.morphTargetDictionary !== undefined ) {
  15426. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15427. }
  15428. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15429. this.geometry = source.geometry;
  15430. return this;
  15431. }
  15432. /**
  15433. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15434. * to make sure existing morph targets can influence this 3D object.
  15435. */
  15436. updateMorphTargets() {
  15437. const geometry = this.geometry;
  15438. const morphAttributes = geometry.morphAttributes;
  15439. const keys = Object.keys( morphAttributes );
  15440. if ( keys.length > 0 ) {
  15441. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15442. if ( morphAttribute !== undefined ) {
  15443. this.morphTargetInfluences = [];
  15444. this.morphTargetDictionary = {};
  15445. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15446. const name = morphAttribute[ m ].name || String( m );
  15447. this.morphTargetInfluences.push( 0 );
  15448. this.morphTargetDictionary[ name ] = m;
  15449. }
  15450. }
  15451. }
  15452. }
  15453. /**
  15454. * Returns the local-space position of the vertex at the given index, taking into
  15455. * account the current animation state of both morph targets and skinning.
  15456. *
  15457. * @param {number} index - The vertex index.
  15458. * @param {Vector3} target - The target object that is used to store the method's result.
  15459. * @return {Vector3} The vertex position in local space.
  15460. */
  15461. getVertexPosition( index, target ) {
  15462. const geometry = this.geometry;
  15463. const position = geometry.attributes.position;
  15464. const morphPosition = geometry.morphAttributes.position;
  15465. const morphTargetsRelative = geometry.morphTargetsRelative;
  15466. target.fromBufferAttribute( position, index );
  15467. const morphInfluences = this.morphTargetInfluences;
  15468. if ( morphPosition && morphInfluences ) {
  15469. _morphA.set( 0, 0, 0 );
  15470. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15471. const influence = morphInfluences[ i ];
  15472. const morphAttribute = morphPosition[ i ];
  15473. if ( influence === 0 ) continue;
  15474. _tempA.fromBufferAttribute( morphAttribute, index );
  15475. if ( morphTargetsRelative ) {
  15476. _morphA.addScaledVector( _tempA, influence );
  15477. } else {
  15478. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15479. }
  15480. }
  15481. target.add( _morphA );
  15482. }
  15483. return target;
  15484. }
  15485. /**
  15486. * Computes intersection points between a casted ray and this line.
  15487. *
  15488. * @param {Raycaster} raycaster - The raycaster.
  15489. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15490. */
  15491. raycast( raycaster, intersects ) {
  15492. const geometry = this.geometry;
  15493. const material = this.material;
  15494. const matrixWorld = this.matrixWorld;
  15495. if ( material === undefined ) return;
  15496. // test with bounding sphere in world space
  15497. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15498. _sphere$6.copy( geometry.boundingSphere );
  15499. _sphere$6.applyMatrix4( matrixWorld );
  15500. // check distance from ray origin to bounding sphere
  15501. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15502. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15503. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15504. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15505. }
  15506. // convert ray to local space of mesh
  15507. _inverseMatrix$3.copy( matrixWorld ).invert();
  15508. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15509. // test with bounding box in local space
  15510. if ( geometry.boundingBox !== null ) {
  15511. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15512. }
  15513. // test for intersections with geometry
  15514. this._computeIntersections( raycaster, intersects, _ray$3 );
  15515. }
  15516. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15517. let intersection;
  15518. const geometry = this.geometry;
  15519. const material = this.material;
  15520. const index = geometry.index;
  15521. const position = geometry.attributes.position;
  15522. const uv = geometry.attributes.uv;
  15523. const uv1 = geometry.attributes.uv1;
  15524. const normal = geometry.attributes.normal;
  15525. const groups = geometry.groups;
  15526. const drawRange = geometry.drawRange;
  15527. if ( index !== null ) {
  15528. // indexed buffer geometry
  15529. if ( Array.isArray( material ) ) {
  15530. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15531. const group = groups[ i ];
  15532. const groupMaterial = material[ group.materialIndex ];
  15533. const start = Math.max( group.start, drawRange.start );
  15534. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15535. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15536. const a = index.getX( j );
  15537. const b = index.getX( j + 1 );
  15538. const c = index.getX( j + 2 );
  15539. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15540. if ( intersection ) {
  15541. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15542. intersection.face.materialIndex = group.materialIndex;
  15543. intersects.push( intersection );
  15544. }
  15545. }
  15546. }
  15547. } else {
  15548. const start = Math.max( 0, drawRange.start );
  15549. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15550. for ( let i = start, il = end; i < il; i += 3 ) {
  15551. const a = index.getX( i );
  15552. const b = index.getX( i + 1 );
  15553. const c = index.getX( i + 2 );
  15554. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15555. if ( intersection ) {
  15556. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15557. intersects.push( intersection );
  15558. }
  15559. }
  15560. }
  15561. } else if ( position !== undefined ) {
  15562. // non-indexed buffer geometry
  15563. if ( Array.isArray( material ) ) {
  15564. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15565. const group = groups[ i ];
  15566. const groupMaterial = material[ group.materialIndex ];
  15567. const start = Math.max( group.start, drawRange.start );
  15568. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15569. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15570. const a = j;
  15571. const b = j + 1;
  15572. const c = j + 2;
  15573. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15574. if ( intersection ) {
  15575. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15576. intersection.face.materialIndex = group.materialIndex;
  15577. intersects.push( intersection );
  15578. }
  15579. }
  15580. }
  15581. } else {
  15582. const start = Math.max( 0, drawRange.start );
  15583. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15584. for ( let i = start, il = end; i < il; i += 3 ) {
  15585. const a = i;
  15586. const b = i + 1;
  15587. const c = i + 2;
  15588. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15589. if ( intersection ) {
  15590. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15591. intersects.push( intersection );
  15592. }
  15593. }
  15594. }
  15595. }
  15596. }
  15597. }
  15598. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15599. let intersect;
  15600. if ( material.side === BackSide ) {
  15601. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15602. } else {
  15603. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15604. }
  15605. if ( intersect === null ) return null;
  15606. _intersectionPointWorld.copy( point );
  15607. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15608. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15609. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15610. return {
  15611. distance: distance,
  15612. point: _intersectionPointWorld.clone(),
  15613. object: object
  15614. };
  15615. }
  15616. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15617. object.getVertexPosition( a, _vA$1 );
  15618. object.getVertexPosition( b, _vB$1 );
  15619. object.getVertexPosition( c, _vC$1 );
  15620. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15621. if ( intersection ) {
  15622. const barycoord = new Vector3();
  15623. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15624. if ( uv ) {
  15625. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15626. }
  15627. if ( uv1 ) {
  15628. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15629. }
  15630. if ( normal ) {
  15631. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15632. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15633. intersection.normal.multiplyScalar( -1 );
  15634. }
  15635. }
  15636. const face = {
  15637. a: a,
  15638. b: b,
  15639. c: c,
  15640. normal: new Vector3(),
  15641. materialIndex: 0
  15642. };
  15643. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15644. intersection.face = face;
  15645. intersection.barycoord = barycoord;
  15646. }
  15647. return intersection;
  15648. }
  15649. /**
  15650. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15651. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15652. * of the axes.
  15653. *
  15654. * ```js
  15655. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15656. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15657. * const cube = new THREE.Mesh( geometry, material );
  15658. * scene.add( cube );
  15659. * ```
  15660. *
  15661. * @augments BufferGeometry
  15662. * @demo scenes/geometry-browser.html#BoxGeometry
  15663. */
  15664. class BoxGeometry extends BufferGeometry {
  15665. /**
  15666. * Constructs a new box geometry.
  15667. *
  15668. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15669. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15670. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15671. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15672. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15673. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15674. */
  15675. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15676. super();
  15677. this.type = 'BoxGeometry';
  15678. /**
  15679. * Holds the constructor parameters that have been
  15680. * used to generate the geometry. Any modification
  15681. * after instantiation does not change the geometry.
  15682. *
  15683. * @type {Object}
  15684. */
  15685. this.parameters = {
  15686. width: width,
  15687. height: height,
  15688. depth: depth,
  15689. widthSegments: widthSegments,
  15690. heightSegments: heightSegments,
  15691. depthSegments: depthSegments
  15692. };
  15693. const scope = this;
  15694. // segments
  15695. widthSegments = Math.floor( widthSegments );
  15696. heightSegments = Math.floor( heightSegments );
  15697. depthSegments = Math.floor( depthSegments );
  15698. // buffers
  15699. const indices = [];
  15700. const vertices = [];
  15701. const normals = [];
  15702. const uvs = [];
  15703. // helper variables
  15704. let numberOfVertices = 0;
  15705. let groupStart = 0;
  15706. // build each side of the box geometry
  15707. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15708. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15709. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15710. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15711. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15712. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15713. // build geometry
  15714. this.setIndex( indices );
  15715. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15716. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15717. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15718. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15719. const segmentWidth = width / gridX;
  15720. const segmentHeight = height / gridY;
  15721. const widthHalf = width / 2;
  15722. const heightHalf = height / 2;
  15723. const depthHalf = depth / 2;
  15724. const gridX1 = gridX + 1;
  15725. const gridY1 = gridY + 1;
  15726. let vertexCounter = 0;
  15727. let groupCount = 0;
  15728. const vector = new Vector3();
  15729. // generate vertices, normals and uvs
  15730. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15731. const y = iy * segmentHeight - heightHalf;
  15732. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15733. const x = ix * segmentWidth - widthHalf;
  15734. // set values to correct vector component
  15735. vector[ u ] = x * udir;
  15736. vector[ v ] = y * vdir;
  15737. vector[ w ] = depthHalf;
  15738. // now apply vector to vertex buffer
  15739. vertices.push( vector.x, vector.y, vector.z );
  15740. // set values to correct vector component
  15741. vector[ u ] = 0;
  15742. vector[ v ] = 0;
  15743. vector[ w ] = depth > 0 ? 1 : -1;
  15744. // now apply vector to normal buffer
  15745. normals.push( vector.x, vector.y, vector.z );
  15746. // uvs
  15747. uvs.push( ix / gridX );
  15748. uvs.push( 1 - ( iy / gridY ) );
  15749. // counters
  15750. vertexCounter += 1;
  15751. }
  15752. }
  15753. // indices
  15754. // 1. you need three indices to draw a single face
  15755. // 2. a single segment consists of two faces
  15756. // 3. so we need to generate six (2*3) indices per segment
  15757. for ( let iy = 0; iy < gridY; iy ++ ) {
  15758. for ( let ix = 0; ix < gridX; ix ++ ) {
  15759. const a = numberOfVertices + ix + gridX1 * iy;
  15760. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15761. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15762. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15763. // faces
  15764. indices.push( a, b, d );
  15765. indices.push( b, c, d );
  15766. // increase counter
  15767. groupCount += 6;
  15768. }
  15769. }
  15770. // add a group to the geometry. this will ensure multi material support
  15771. scope.addGroup( groupStart, groupCount, materialIndex );
  15772. // calculate new start value for groups
  15773. groupStart += groupCount;
  15774. // update total number of vertices
  15775. numberOfVertices += vertexCounter;
  15776. }
  15777. }
  15778. copy( source ) {
  15779. super.copy( source );
  15780. this.parameters = Object.assign( {}, source.parameters );
  15781. return this;
  15782. }
  15783. /**
  15784. * Factory method for creating an instance of this class from the given
  15785. * JSON object.
  15786. *
  15787. * @param {Object} data - A JSON object representing the serialized geometry.
  15788. * @return {BoxGeometry} A new instance.
  15789. */
  15790. static fromJSON( data ) {
  15791. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15792. }
  15793. }
  15794. /**
  15795. * Provides utility functions for managing uniforms.
  15796. *
  15797. * @module UniformsUtils
  15798. */
  15799. /**
  15800. * Clones the given uniform definitions by performing a deep-copy. That means
  15801. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15802. * the cloned uniform will refer to a new object reference.
  15803. *
  15804. * @param {Object} src - An object representing uniform definitions.
  15805. * @return {Object} The cloned uniforms.
  15806. */
  15807. function cloneUniforms( src ) {
  15808. const dst = {};
  15809. for ( const u in src ) {
  15810. dst[ u ] = {};
  15811. for ( const p in src[ u ] ) {
  15812. const property = src[ u ][ p ];
  15813. if ( property && ( property.isColor ||
  15814. property.isMatrix3 || property.isMatrix4 ||
  15815. property.isVector2 || property.isVector3 || property.isVector4 ||
  15816. property.isTexture || property.isQuaternion ) ) {
  15817. if ( property.isRenderTargetTexture ) {
  15818. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15819. dst[ u ][ p ] = null;
  15820. } else {
  15821. dst[ u ][ p ] = property.clone();
  15822. }
  15823. } else if ( Array.isArray( property ) ) {
  15824. dst[ u ][ p ] = property.slice();
  15825. } else {
  15826. dst[ u ][ p ] = property;
  15827. }
  15828. }
  15829. }
  15830. return dst;
  15831. }
  15832. /**
  15833. * Merges the given uniform definitions into a single object. Since the
  15834. * method internally uses cloneUniforms(), it performs a deep-copy when
  15835. * producing the merged uniform definitions.
  15836. *
  15837. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15838. * @return {Object} The merged uniforms.
  15839. */
  15840. function mergeUniforms( uniforms ) {
  15841. const merged = {};
  15842. for ( let u = 0; u < uniforms.length; u ++ ) {
  15843. const tmp = cloneUniforms( uniforms[ u ] );
  15844. for ( const p in tmp ) {
  15845. merged[ p ] = tmp[ p ];
  15846. }
  15847. }
  15848. return merged;
  15849. }
  15850. function cloneUniformsGroups( src ) {
  15851. const dst = [];
  15852. for ( let u = 0; u < src.length; u ++ ) {
  15853. dst.push( src[ u ].clone() );
  15854. }
  15855. return dst;
  15856. }
  15857. function getUnlitUniformColorSpace( renderer ) {
  15858. const currentRenderTarget = renderer.getRenderTarget();
  15859. if ( currentRenderTarget === null ) {
  15860. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15861. return renderer.outputColorSpace;
  15862. }
  15863. // https://github.com/mrdoob/three.js/issues/27868
  15864. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15865. return currentRenderTarget.texture.colorSpace;
  15866. }
  15867. return ColorManagement.workingColorSpace;
  15868. }
  15869. // Legacy
  15870. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15871. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15872. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15873. /**
  15874. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15875. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15876. * effect not included with any of the built-in materials.
  15877. *
  15878. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15879. *
  15880. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15881. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15882. * you don't want that, use {@link RawShaderMaterial} instead.
  15883. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15884. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15885. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15886. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15887. * - The loop variable has to be *i*.
  15888. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15889. * value of *i* for the given iteration and can be used in preprocessor
  15890. * statements.
  15891. *
  15892. * ```js
  15893. * const material = new THREE.ShaderMaterial( {
  15894. * uniforms: {
  15895. * time: { value: 1.0 },
  15896. * resolution: { value: new THREE.Vector2() }
  15897. * },
  15898. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15899. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15900. * } );
  15901. * ```
  15902. *
  15903. * @augments Material
  15904. */
  15905. class ShaderMaterial extends Material {
  15906. /**
  15907. * Constructs a new shader material.
  15908. *
  15909. * @param {Object} [parameters] - An object with one or more properties
  15910. * defining the material's appearance. Any property of the material
  15911. * (including any property from inherited materials) can be passed
  15912. * in here. Color values can be passed any type of value accepted
  15913. * by {@link Color#set}.
  15914. */
  15915. constructor( parameters ) {
  15916. super();
  15917. /**
  15918. * This flag can be used for type testing.
  15919. *
  15920. * @type {boolean}
  15921. * @readonly
  15922. * @default true
  15923. */
  15924. this.isShaderMaterial = true;
  15925. this.type = 'ShaderMaterial';
  15926. /**
  15927. * Defines custom constants using `#define` directives within the GLSL code
  15928. * for both the vertex shader and the fragment shader; each key/value pair
  15929. * yields another directive.
  15930. * ```js
  15931. * defines: {
  15932. * FOO: 15,
  15933. * BAR: true
  15934. * }
  15935. * ```
  15936. * Yields the lines:
  15937. * ```
  15938. * #define FOO 15
  15939. * #define BAR true
  15940. * ```
  15941. *
  15942. * @type {Object}
  15943. */
  15944. this.defines = {};
  15945. /**
  15946. * An object of the form:
  15947. * ```js
  15948. * {
  15949. * "uniform1": { value: 1.0 },
  15950. * "uniform2": { value: 2 }
  15951. * }
  15952. * ```
  15953. * specifying the uniforms to be passed to the shader code; keys are uniform
  15954. * names, values are definitions of the form
  15955. * ```
  15956. * {
  15957. * value: 1.0
  15958. * }
  15959. * ```
  15960. * where `value` is the value of the uniform. Names must match the name of
  15961. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15962. * on every frame, so updating the value of the uniform will immediately
  15963. * update the value available to the GLSL code.
  15964. *
  15965. * @type {Object}
  15966. */
  15967. this.uniforms = {};
  15968. /**
  15969. * An array holding uniforms groups for configuring UBOs.
  15970. *
  15971. * @type {Array<UniformsGroup>}
  15972. */
  15973. this.uniformsGroups = [];
  15974. /**
  15975. * Vertex shader GLSL code. This is the actual code for the shader.
  15976. *
  15977. * @type {string}
  15978. */
  15979. this.vertexShader = default_vertex;
  15980. /**
  15981. * Fragment shader GLSL code. This is the actual code for the shader.
  15982. *
  15983. * @type {string}
  15984. */
  15985. this.fragmentShader = default_fragment;
  15986. /**
  15987. * Controls line thickness or lines.
  15988. *
  15989. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15990. * width of one pixel.
  15991. *
  15992. * @type {number}
  15993. * @default 1
  15994. */
  15995. this.linewidth = 1;
  15996. /**
  15997. * Renders the geometry as a wireframe.
  15998. *
  15999. * @type {boolean}
  16000. * @default false
  16001. */
  16002. this.wireframe = false;
  16003. /**
  16004. * Controls the thickness of the wireframe.
  16005. *
  16006. * WebGL and WebGPU ignore this property and always render
  16007. * 1 pixel wide lines.
  16008. *
  16009. * @type {number}
  16010. * @default 1
  16011. */
  16012. this.wireframeLinewidth = 1;
  16013. /**
  16014. * Defines whether the material color is affected by global fog settings; `true`
  16015. * to pass fog uniforms to the shader.
  16016. *
  16017. * Setting this property to `true` requires the definition of fog uniforms. It is
  16018. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  16019. * with predefined fog uniforms.
  16020. *
  16021. * ```js
  16022. * const material = new ShaderMaterial( {
  16023. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  16024. * vertexShader: vertexShader,
  16025. * fragmentShader: fragmentShader,
  16026. * fog: true
  16027. * } );
  16028. * ```
  16029. *
  16030. * @type {boolean}
  16031. * @default false
  16032. */
  16033. this.fog = false;
  16034. /**
  16035. * Defines whether this material uses lighting; `true` to pass uniform data
  16036. * related to lighting to this shader.
  16037. *
  16038. * @type {boolean}
  16039. * @default false
  16040. */
  16041. this.lights = false;
  16042. /**
  16043. * Defines whether this material supports clipping; `true` to let the renderer
  16044. * pass the clippingPlanes uniform.
  16045. *
  16046. * @type {boolean}
  16047. * @default false
  16048. */
  16049. this.clipping = false;
  16050. /**
  16051. * Overwritten and set to `true` by default.
  16052. *
  16053. * @type {boolean}
  16054. * @default true
  16055. */
  16056. this.forceSinglePass = true;
  16057. /**
  16058. * This object allows to enable certain WebGL 2 extensions.
  16059. *
  16060. * - clipCullDistance: set to `true` to use vertex shader clipping
  16061. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  16062. *
  16063. * @type {{clipCullDistance:false,multiDraw:false}}
  16064. */
  16065. this.extensions = {
  16066. clipCullDistance: false, // set to use vertex shader clipping
  16067. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  16068. };
  16069. /**
  16070. * When the rendered geometry doesn't include these attributes but the
  16071. * material does, these default values will be passed to the shaders. This
  16072. * avoids errors when buffer data is missing.
  16073. *
  16074. * - color: [ 1, 1, 1 ]
  16075. * - uv: [ 0, 0 ]
  16076. * - uv1: [ 0, 0 ]
  16077. *
  16078. * @type {Object}
  16079. */
  16080. this.defaultAttributeValues = {
  16081. 'color': [ 1, 1, 1 ],
  16082. 'uv': [ 0, 0 ],
  16083. 'uv1': [ 0, 0 ]
  16084. };
  16085. /**
  16086. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  16087. * to bind a generic vertex index to an attribute variable.
  16088. *
  16089. * @type {string|undefined}
  16090. * @default undefined
  16091. */
  16092. this.index0AttributeName = undefined;
  16093. /**
  16094. * Can be used to force a uniform update while changing uniforms in
  16095. * {@link Object3D#onBeforeRender}.
  16096. *
  16097. * @type {boolean}
  16098. * @default false
  16099. */
  16100. this.uniformsNeedUpdate = false;
  16101. /**
  16102. * Defines the GLSL version of custom shader code.
  16103. *
  16104. * @type {?(GLSL1|GLSL3)}
  16105. * @default null
  16106. */
  16107. this.glslVersion = null;
  16108. if ( parameters !== undefined ) {
  16109. this.setValues( parameters );
  16110. }
  16111. }
  16112. copy( source ) {
  16113. super.copy( source );
  16114. this.fragmentShader = source.fragmentShader;
  16115. this.vertexShader = source.vertexShader;
  16116. this.uniforms = cloneUniforms( source.uniforms );
  16117. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  16118. this.defines = Object.assign( {}, source.defines );
  16119. this.wireframe = source.wireframe;
  16120. this.wireframeLinewidth = source.wireframeLinewidth;
  16121. this.fog = source.fog;
  16122. this.lights = source.lights;
  16123. this.clipping = source.clipping;
  16124. this.extensions = Object.assign( {}, source.extensions );
  16125. this.glslVersion = source.glslVersion;
  16126. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  16127. this.index0AttributeName = source.index0AttributeName;
  16128. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  16129. return this;
  16130. }
  16131. toJSON( meta ) {
  16132. const data = super.toJSON( meta );
  16133. data.glslVersion = this.glslVersion;
  16134. data.uniforms = {};
  16135. for ( const name in this.uniforms ) {
  16136. const uniform = this.uniforms[ name ];
  16137. const value = uniform.value;
  16138. if ( value && value.isTexture ) {
  16139. data.uniforms[ name ] = {
  16140. type: 't',
  16141. value: value.toJSON( meta ).uuid
  16142. };
  16143. } else if ( value && value.isColor ) {
  16144. data.uniforms[ name ] = {
  16145. type: 'c',
  16146. value: value.getHex()
  16147. };
  16148. } else if ( value && value.isVector2 ) {
  16149. data.uniforms[ name ] = {
  16150. type: 'v2',
  16151. value: value.toArray()
  16152. };
  16153. } else if ( value && value.isVector3 ) {
  16154. data.uniforms[ name ] = {
  16155. type: 'v3',
  16156. value: value.toArray()
  16157. };
  16158. } else if ( value && value.isVector4 ) {
  16159. data.uniforms[ name ] = {
  16160. type: 'v4',
  16161. value: value.toArray()
  16162. };
  16163. } else if ( value && value.isMatrix3 ) {
  16164. data.uniforms[ name ] = {
  16165. type: 'm3',
  16166. value: value.toArray()
  16167. };
  16168. } else if ( value && value.isMatrix4 ) {
  16169. data.uniforms[ name ] = {
  16170. type: 'm4',
  16171. value: value.toArray()
  16172. };
  16173. } else {
  16174. data.uniforms[ name ] = {
  16175. value: value
  16176. };
  16177. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  16178. }
  16179. }
  16180. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  16181. data.vertexShader = this.vertexShader;
  16182. data.fragmentShader = this.fragmentShader;
  16183. data.lights = this.lights;
  16184. data.clipping = this.clipping;
  16185. const extensions = {};
  16186. for ( const key in this.extensions ) {
  16187. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  16188. }
  16189. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  16190. return data;
  16191. }
  16192. }
  16193. /**
  16194. * Abstract base class for cameras. This class should always be inherited
  16195. * when you build a new camera.
  16196. *
  16197. * @abstract
  16198. * @augments Object3D
  16199. */
  16200. class Camera extends Object3D {
  16201. /**
  16202. * Constructs a new camera.
  16203. */
  16204. constructor() {
  16205. super();
  16206. /**
  16207. * This flag can be used for type testing.
  16208. *
  16209. * @type {boolean}
  16210. * @readonly
  16211. * @default true
  16212. */
  16213. this.isCamera = true;
  16214. this.type = 'Camera';
  16215. /**
  16216. * The inverse of the camera's world matrix.
  16217. *
  16218. * @type {Matrix4}
  16219. */
  16220. this.matrixWorldInverse = new Matrix4();
  16221. /**
  16222. * The camera's projection matrix.
  16223. *
  16224. * @type {Matrix4}
  16225. */
  16226. this.projectionMatrix = new Matrix4();
  16227. /**
  16228. * The inverse of the camera's projection matrix.
  16229. *
  16230. * @type {Matrix4}
  16231. */
  16232. this.projectionMatrixInverse = new Matrix4();
  16233. /**
  16234. * The coordinate system in which the camera is used.
  16235. *
  16236. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16237. */
  16238. this.coordinateSystem = WebGLCoordinateSystem;
  16239. this._reversedDepth = false;
  16240. }
  16241. /**
  16242. * The flag that indicates whether the camera uses a reversed depth buffer.
  16243. *
  16244. * @type {boolean}
  16245. * @default false
  16246. */
  16247. get reversedDepth() {
  16248. return this._reversedDepth;
  16249. }
  16250. copy( source, recursive ) {
  16251. super.copy( source, recursive );
  16252. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16253. this.projectionMatrix.copy( source.projectionMatrix );
  16254. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16255. this.coordinateSystem = source.coordinateSystem;
  16256. return this;
  16257. }
  16258. /**
  16259. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16260. *
  16261. * This method is overwritten since cameras have a different forward vector compared to other
  16262. * 3D objects. A camera looks down its local, negative z-axis by default.
  16263. *
  16264. * @param {Vector3} target - The target vector the result is stored to.
  16265. * @return {Vector3} The 3D object's direction in world space.
  16266. */
  16267. getWorldDirection( target ) {
  16268. return super.getWorldDirection( target ).negate();
  16269. }
  16270. updateMatrixWorld( force ) {
  16271. super.updateMatrixWorld( force );
  16272. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16273. }
  16274. updateWorldMatrix( updateParents, updateChildren ) {
  16275. super.updateWorldMatrix( updateParents, updateChildren );
  16276. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16277. }
  16278. clone() {
  16279. return new this.constructor().copy( this );
  16280. }
  16281. }
  16282. const _v3$1 = /*@__PURE__*/ new Vector3();
  16283. const _minTarget = /*@__PURE__*/ new Vector2();
  16284. const _maxTarget = /*@__PURE__*/ new Vector2();
  16285. /**
  16286. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16287. *
  16288. * This projection mode is designed to mimic the way the human eye sees. It
  16289. * is the most common projection mode used for rendering a 3D scene.
  16290. *
  16291. * ```js
  16292. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16293. * scene.add( camera );
  16294. * ```
  16295. *
  16296. * @augments Camera
  16297. */
  16298. class PerspectiveCamera extends Camera {
  16299. /**
  16300. * Constructs a new perspective camera.
  16301. *
  16302. * @param {number} [fov=50] - The vertical field of view.
  16303. * @param {number} [aspect=1] - The aspect ratio.
  16304. * @param {number} [near=0.1] - The camera's near plane.
  16305. * @param {number} [far=2000] - The camera's far plane.
  16306. */
  16307. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16308. super();
  16309. /**
  16310. * This flag can be used for type testing.
  16311. *
  16312. * @type {boolean}
  16313. * @readonly
  16314. * @default true
  16315. */
  16316. this.isPerspectiveCamera = true;
  16317. this.type = 'PerspectiveCamera';
  16318. /**
  16319. * The vertical field of view, from bottom to top of view,
  16320. * in degrees.
  16321. *
  16322. * @type {number}
  16323. * @default 50
  16324. */
  16325. this.fov = fov;
  16326. /**
  16327. * The zoom factor of the camera.
  16328. *
  16329. * @type {number}
  16330. * @default 1
  16331. */
  16332. this.zoom = 1;
  16333. /**
  16334. * The camera's near plane. The valid range is greater than `0`
  16335. * and less than the current value of {@link PerspectiveCamera#far}.
  16336. *
  16337. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16338. * valid value for a perspective camera's near plane.
  16339. *
  16340. * @type {number}
  16341. * @default 0.1
  16342. */
  16343. this.near = near;
  16344. /**
  16345. * The camera's far plane. Must be greater than the
  16346. * current value of {@link PerspectiveCamera#near}.
  16347. *
  16348. * @type {number}
  16349. * @default 2000
  16350. */
  16351. this.far = far;
  16352. /**
  16353. * Object distance used for stereoscopy and depth-of-field effects. This
  16354. * parameter does not influence the projection matrix unless a
  16355. * {@link StereoCamera} is being used.
  16356. *
  16357. * @type {number}
  16358. * @default 10
  16359. */
  16360. this.focus = 10;
  16361. /**
  16362. * The aspect ratio, usually the canvas width / canvas height.
  16363. *
  16364. * @type {number}
  16365. * @default 1
  16366. */
  16367. this.aspect = aspect;
  16368. /**
  16369. * Represents the frustum window specification. This property should not be edited
  16370. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16371. *
  16372. * @type {?Object}
  16373. * @default null
  16374. */
  16375. this.view = null;
  16376. /**
  16377. * Film size used for the larger axis. Default is `35` (millimeters). This
  16378. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16379. * is set to a nonzero value.
  16380. *
  16381. * @type {number}
  16382. * @default 35
  16383. */
  16384. this.filmGauge = 35;
  16385. /**
  16386. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16387. *
  16388. * @type {number}
  16389. * @default 0
  16390. */
  16391. this.filmOffset = 0;
  16392. this.updateProjectionMatrix();
  16393. }
  16394. copy( source, recursive ) {
  16395. super.copy( source, recursive );
  16396. this.fov = source.fov;
  16397. this.zoom = source.zoom;
  16398. this.near = source.near;
  16399. this.far = source.far;
  16400. this.focus = source.focus;
  16401. this.aspect = source.aspect;
  16402. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16403. this.filmGauge = source.filmGauge;
  16404. this.filmOffset = source.filmOffset;
  16405. return this;
  16406. }
  16407. /**
  16408. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16409. *
  16410. * The default film gauge is 35, so that the focal length can be specified for
  16411. * a 35mm (full frame) camera.
  16412. *
  16413. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16414. */
  16415. setFocalLength( focalLength ) {
  16416. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16417. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16418. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16419. this.updateProjectionMatrix();
  16420. }
  16421. /**
  16422. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16423. * {@link PerspectiveCamera#filmGauge}.
  16424. *
  16425. * @return {number} The computed focal length.
  16426. */
  16427. getFocalLength() {
  16428. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16429. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16430. }
  16431. /**
  16432. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16433. *
  16434. * @return {number} The effective FOV.
  16435. */
  16436. getEffectiveFOV() {
  16437. return RAD2DEG * 2 * Math.atan(
  16438. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16439. }
  16440. /**
  16441. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16442. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16443. *
  16444. * @return {number} The film width.
  16445. */
  16446. getFilmWidth() {
  16447. // film not completely covered in portrait format (aspect < 1)
  16448. return this.filmGauge * Math.min( this.aspect, 1 );
  16449. }
  16450. /**
  16451. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16452. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16453. *
  16454. * @return {number} The film width.
  16455. */
  16456. getFilmHeight() {
  16457. // film not completely covered in landscape format (aspect > 1)
  16458. return this.filmGauge / Math.max( this.aspect, 1 );
  16459. }
  16460. /**
  16461. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16462. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16463. *
  16464. * @param {number} distance - The viewing distance.
  16465. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16466. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16467. */
  16468. getViewBounds( distance, minTarget, maxTarget ) {
  16469. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16470. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16471. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16472. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16473. }
  16474. /**
  16475. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16476. *
  16477. * @param {number} distance - The viewing distance.
  16478. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16479. * @returns {Vector2} The view size.
  16480. */
  16481. getViewSize( distance, target ) {
  16482. this.getViewBounds( distance, _minTarget, _maxTarget );
  16483. return target.subVectors( _maxTarget, _minTarget );
  16484. }
  16485. /**
  16486. * Sets an offset in a larger frustum. This is useful for multi-window or
  16487. * multi-monitor/multi-machine setups.
  16488. *
  16489. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16490. * the monitors are in grid like this
  16491. *```
  16492. * +---+---+---+
  16493. * | A | B | C |
  16494. * +---+---+---+
  16495. * | D | E | F |
  16496. * +---+---+---+
  16497. *```
  16498. * then for each monitor you would call it like this:
  16499. *```js
  16500. * const w = 1920;
  16501. * const h = 1080;
  16502. * const fullWidth = w * 3;
  16503. * const fullHeight = h * 2;
  16504. *
  16505. * // --A--
  16506. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16507. * // --B--
  16508. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16509. * // --C--
  16510. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16511. * // --D--
  16512. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16513. * // --E--
  16514. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16515. * // --F--
  16516. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16517. * ```
  16518. *
  16519. * Note there is no reason monitors have to be the same size or in a grid.
  16520. *
  16521. * @param {number} fullWidth - The full width of multiview setup.
  16522. * @param {number} fullHeight - The full height of multiview setup.
  16523. * @param {number} x - The horizontal offset of the subcamera.
  16524. * @param {number} y - The vertical offset of the subcamera.
  16525. * @param {number} width - The width of subcamera.
  16526. * @param {number} height - The height of subcamera.
  16527. */
  16528. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16529. this.aspect = fullWidth / fullHeight;
  16530. if ( this.view === null ) {
  16531. this.view = {
  16532. enabled: true,
  16533. fullWidth: 1,
  16534. fullHeight: 1,
  16535. offsetX: 0,
  16536. offsetY: 0,
  16537. width: 1,
  16538. height: 1
  16539. };
  16540. }
  16541. this.view.enabled = true;
  16542. this.view.fullWidth = fullWidth;
  16543. this.view.fullHeight = fullHeight;
  16544. this.view.offsetX = x;
  16545. this.view.offsetY = y;
  16546. this.view.width = width;
  16547. this.view.height = height;
  16548. this.updateProjectionMatrix();
  16549. }
  16550. /**
  16551. * Removes the view offset from the projection matrix.
  16552. */
  16553. clearViewOffset() {
  16554. if ( this.view !== null ) {
  16555. this.view.enabled = false;
  16556. }
  16557. this.updateProjectionMatrix();
  16558. }
  16559. /**
  16560. * Updates the camera's projection matrix. Must be called after any change of
  16561. * camera properties.
  16562. */
  16563. updateProjectionMatrix() {
  16564. const near = this.near;
  16565. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16566. let height = 2 * top;
  16567. let width = this.aspect * height;
  16568. let left = -0.5 * width;
  16569. const view = this.view;
  16570. if ( this.view !== null && this.view.enabled ) {
  16571. const fullWidth = view.fullWidth,
  16572. fullHeight = view.fullHeight;
  16573. left += view.offsetX * width / fullWidth;
  16574. top -= view.offsetY * height / fullHeight;
  16575. width *= view.width / fullWidth;
  16576. height *= view.height / fullHeight;
  16577. }
  16578. const skew = this.filmOffset;
  16579. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16580. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16581. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16582. }
  16583. toJSON( meta ) {
  16584. const data = super.toJSON( meta );
  16585. data.object.fov = this.fov;
  16586. data.object.zoom = this.zoom;
  16587. data.object.near = this.near;
  16588. data.object.far = this.far;
  16589. data.object.focus = this.focus;
  16590. data.object.aspect = this.aspect;
  16591. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16592. data.object.filmGauge = this.filmGauge;
  16593. data.object.filmOffset = this.filmOffset;
  16594. return data;
  16595. }
  16596. }
  16597. const fov = -90; // negative fov is not an error
  16598. const aspect = 1;
  16599. /**
  16600. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16601. * cube render target. The render target can then be used as an environment map for rendering
  16602. * realtime reflections in your scene.
  16603. *
  16604. * ```js
  16605. * // Create cube render target
  16606. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16607. *
  16608. * // Create cube camera
  16609. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16610. * scene.add( cubeCamera );
  16611. *
  16612. * // Create car
  16613. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16614. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16615. * scene.add( car );
  16616. *
  16617. * // Update the render target cube
  16618. * car.visible = false;
  16619. * cubeCamera.position.copy( car.position );
  16620. * cubeCamera.update( renderer, scene );
  16621. *
  16622. * // Render the scene
  16623. * car.visible = true;
  16624. * renderer.render( scene, camera );
  16625. * ```
  16626. *
  16627. * @augments Object3D
  16628. */
  16629. class CubeCamera extends Object3D {
  16630. /**
  16631. * Constructs a new cube camera.
  16632. *
  16633. * @param {number} near - The camera's near plane.
  16634. * @param {number} far - The camera's far plane.
  16635. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16636. */
  16637. constructor( near, far, renderTarget ) {
  16638. super();
  16639. this.type = 'CubeCamera';
  16640. /**
  16641. * A reference to the cube render target.
  16642. *
  16643. * @type {WebGLCubeRenderTarget}
  16644. */
  16645. this.renderTarget = renderTarget;
  16646. /**
  16647. * The current active coordinate system.
  16648. *
  16649. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16650. * @default null
  16651. */
  16652. this.coordinateSystem = null;
  16653. /**
  16654. * The current active mipmap level
  16655. *
  16656. * @type {number}
  16657. * @default 0
  16658. */
  16659. this.activeMipmapLevel = 0;
  16660. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16661. cameraPX.layers = this.layers;
  16662. this.add( cameraPX );
  16663. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16664. cameraNX.layers = this.layers;
  16665. this.add( cameraNX );
  16666. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16667. cameraPY.layers = this.layers;
  16668. this.add( cameraPY );
  16669. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16670. cameraNY.layers = this.layers;
  16671. this.add( cameraNY );
  16672. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16673. cameraPZ.layers = this.layers;
  16674. this.add( cameraPZ );
  16675. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16676. cameraNZ.layers = this.layers;
  16677. this.add( cameraNZ );
  16678. }
  16679. /**
  16680. * Must be called when the coordinate system of the cube camera is changed.
  16681. */
  16682. updateCoordinateSystem() {
  16683. const coordinateSystem = this.coordinateSystem;
  16684. const cameras = this.children.concat();
  16685. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16686. for ( const camera of cameras ) this.remove( camera );
  16687. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16688. cameraPX.up.set( 0, 1, 0 );
  16689. cameraPX.lookAt( 1, 0, 0 );
  16690. cameraNX.up.set( 0, 1, 0 );
  16691. cameraNX.lookAt( -1, 0, 0 );
  16692. cameraPY.up.set( 0, 0, -1 );
  16693. cameraPY.lookAt( 0, 1, 0 );
  16694. cameraNY.up.set( 0, 0, 1 );
  16695. cameraNY.lookAt( 0, -1, 0 );
  16696. cameraPZ.up.set( 0, 1, 0 );
  16697. cameraPZ.lookAt( 0, 0, 1 );
  16698. cameraNZ.up.set( 0, 1, 0 );
  16699. cameraNZ.lookAt( 0, 0, -1 );
  16700. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16701. cameraPX.up.set( 0, -1, 0 );
  16702. cameraPX.lookAt( -1, 0, 0 );
  16703. cameraNX.up.set( 0, -1, 0 );
  16704. cameraNX.lookAt( 1, 0, 0 );
  16705. cameraPY.up.set( 0, 0, 1 );
  16706. cameraPY.lookAt( 0, 1, 0 );
  16707. cameraNY.up.set( 0, 0, -1 );
  16708. cameraNY.lookAt( 0, -1, 0 );
  16709. cameraPZ.up.set( 0, -1, 0 );
  16710. cameraPZ.lookAt( 0, 0, 1 );
  16711. cameraNZ.up.set( 0, -1, 0 );
  16712. cameraNZ.lookAt( 0, 0, -1 );
  16713. } else {
  16714. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16715. }
  16716. for ( const camera of cameras ) {
  16717. this.add( camera );
  16718. camera.updateMatrixWorld();
  16719. }
  16720. }
  16721. /**
  16722. * Calling this method will render the given scene with the given renderer
  16723. * into the cube render target of the camera.
  16724. *
  16725. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16726. * @param {Scene} scene - The scene to render.
  16727. */
  16728. update( renderer, scene ) {
  16729. if ( this.parent === null ) this.updateMatrixWorld();
  16730. const { renderTarget, activeMipmapLevel } = this;
  16731. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16732. this.coordinateSystem = renderer.coordinateSystem;
  16733. this.updateCoordinateSystem();
  16734. }
  16735. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16736. const currentRenderTarget = renderer.getRenderTarget();
  16737. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16738. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16739. const currentXrEnabled = renderer.xr.enabled;
  16740. renderer.xr.enabled = false;
  16741. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16742. renderTarget.texture.generateMipmaps = false;
  16743. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16744. renderer.render( scene, cameraPX );
  16745. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16746. renderer.render( scene, cameraNX );
  16747. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16748. renderer.render( scene, cameraPY );
  16749. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16750. renderer.render( scene, cameraNY );
  16751. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16752. renderer.render( scene, cameraPZ );
  16753. // mipmaps are generated during the last call of render()
  16754. // at this point, all sides of the cube render target are defined
  16755. renderTarget.texture.generateMipmaps = generateMipmaps;
  16756. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16757. renderer.render( scene, cameraNZ );
  16758. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16759. renderer.xr.enabled = currentXrEnabled;
  16760. renderTarget.texture.needsPMREMUpdate = true;
  16761. }
  16762. }
  16763. /**
  16764. * Creates a cube texture made up of six images.
  16765. *
  16766. * ```js
  16767. * const loader = new THREE.CubeTextureLoader();
  16768. * loader.setPath( 'textures/cube/pisa/' );
  16769. *
  16770. * const textureCube = loader.load( [
  16771. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16772. * ] );
  16773. *
  16774. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16775. * ```
  16776. *
  16777. * @augments Texture
  16778. */
  16779. class CubeTexture extends Texture {
  16780. /**
  16781. * Constructs a new cube texture.
  16782. *
  16783. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16784. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16785. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16786. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16787. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16788. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16789. * @param {number} [format=RGBAFormat] - The texture format.
  16790. * @param {number} [type=UnsignedByteType] - The texture type.
  16791. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16792. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16793. */
  16794. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16795. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16796. /**
  16797. * This flag can be used for type testing.
  16798. *
  16799. * @type {boolean}
  16800. * @readonly
  16801. * @default true
  16802. */
  16803. this.isCubeTexture = true;
  16804. /**
  16805. * If set to `true`, the texture is flipped along the vertical axis when
  16806. * uploaded to the GPU.
  16807. *
  16808. * Overwritten and set to `false` by default.
  16809. *
  16810. * @type {boolean}
  16811. * @default false
  16812. */
  16813. this.flipY = false;
  16814. }
  16815. /**
  16816. * Alias for {@link CubeTexture#image}.
  16817. *
  16818. * @type {Array<Image>}
  16819. */
  16820. get images() {
  16821. return this.image;
  16822. }
  16823. set images( value ) {
  16824. this.image = value;
  16825. }
  16826. }
  16827. /**
  16828. * A cube render target used in context of {@link WebGLRenderer}.
  16829. *
  16830. * @augments WebGLRenderTarget
  16831. */
  16832. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16833. /**
  16834. * Constructs a new cube render target.
  16835. *
  16836. * @param {number} [size=1] - The size of the render target.
  16837. * @param {RenderTarget~Options} [options] - The configuration object.
  16838. */
  16839. constructor( size = 1, options = {} ) {
  16840. super( size, size, options );
  16841. /**
  16842. * This flag can be used for type testing.
  16843. *
  16844. * @type {boolean}
  16845. * @readonly
  16846. * @default true
  16847. */
  16848. this.isWebGLCubeRenderTarget = true;
  16849. const image = { width: size, height: size, depth: 1 };
  16850. const images = [ image, image, image, image, image, image ];
  16851. /**
  16852. * Overwritten with a different texture type.
  16853. *
  16854. * @type {DataArrayTexture}
  16855. */
  16856. this.texture = new CubeTexture( images );
  16857. this._setTextureOptions( options );
  16858. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16859. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16860. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16861. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16862. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16863. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16864. this.texture.isRenderTargetTexture = true;
  16865. }
  16866. /**
  16867. * Converts the given equirectangular texture to a cube map.
  16868. *
  16869. * @param {WebGLRenderer} renderer - The renderer.
  16870. * @param {Texture} texture - The equirectangular texture.
  16871. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16872. */
  16873. fromEquirectangularTexture( renderer, texture ) {
  16874. this.texture.type = texture.type;
  16875. this.texture.colorSpace = texture.colorSpace;
  16876. this.texture.generateMipmaps = texture.generateMipmaps;
  16877. this.texture.minFilter = texture.minFilter;
  16878. this.texture.magFilter = texture.magFilter;
  16879. const shader = {
  16880. uniforms: {
  16881. tEquirect: { value: null },
  16882. },
  16883. vertexShader: /* glsl */`
  16884. varying vec3 vWorldDirection;
  16885. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16886. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16887. }
  16888. void main() {
  16889. vWorldDirection = transformDirection( position, modelMatrix );
  16890. #include <begin_vertex>
  16891. #include <project_vertex>
  16892. }
  16893. `,
  16894. fragmentShader: /* glsl */`
  16895. uniform sampler2D tEquirect;
  16896. varying vec3 vWorldDirection;
  16897. #include <common>
  16898. void main() {
  16899. vec3 direction = normalize( vWorldDirection );
  16900. vec2 sampleUV = equirectUv( direction );
  16901. gl_FragColor = texture2D( tEquirect, sampleUV );
  16902. }
  16903. `
  16904. };
  16905. const geometry = new BoxGeometry( 5, 5, 5 );
  16906. const material = new ShaderMaterial( {
  16907. name: 'CubemapFromEquirect',
  16908. uniforms: cloneUniforms( shader.uniforms ),
  16909. vertexShader: shader.vertexShader,
  16910. fragmentShader: shader.fragmentShader,
  16911. side: BackSide,
  16912. blending: NoBlending
  16913. } );
  16914. material.uniforms.tEquirect.value = texture;
  16915. const mesh = new Mesh( geometry, material );
  16916. const currentMinFilter = texture.minFilter;
  16917. // Avoid blurred poles
  16918. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16919. const camera = new CubeCamera( 1, 10, this );
  16920. camera.update( renderer, mesh );
  16921. texture.minFilter = currentMinFilter;
  16922. mesh.geometry.dispose();
  16923. mesh.material.dispose();
  16924. return this;
  16925. }
  16926. /**
  16927. * Clears this cube render target.
  16928. *
  16929. * @param {WebGLRenderer} renderer - The renderer.
  16930. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16931. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16932. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16933. */
  16934. clear( renderer, color = true, depth = true, stencil = true ) {
  16935. const currentRenderTarget = renderer.getRenderTarget();
  16936. for ( let i = 0; i < 6; i ++ ) {
  16937. renderer.setRenderTarget( this, i );
  16938. renderer.clear( color, depth, stencil );
  16939. }
  16940. renderer.setRenderTarget( currentRenderTarget );
  16941. }
  16942. }
  16943. /**
  16944. * This is almost identical to an {@link Object3D}. Its purpose is to
  16945. * make working with groups of objects syntactically clearer.
  16946. *
  16947. * ```js
  16948. * // Create a group and add the two cubes.
  16949. * // These cubes can now be rotated / scaled etc as a group.
  16950. * const group = new THREE.Group();
  16951. *
  16952. * group.add( meshA );
  16953. * group.add( meshB );
  16954. *
  16955. * scene.add( group );
  16956. * ```
  16957. *
  16958. * @augments Object3D
  16959. */
  16960. class Group extends Object3D {
  16961. constructor() {
  16962. super();
  16963. /**
  16964. * This flag can be used for type testing.
  16965. *
  16966. * @type {boolean}
  16967. * @readonly
  16968. * @default true
  16969. */
  16970. this.isGroup = true;
  16971. this.type = 'Group';
  16972. }
  16973. }
  16974. const _moveEvent = { type: 'move' };
  16975. /**
  16976. * Class for representing a XR controller with its
  16977. * different coordinate systems.
  16978. *
  16979. * @private
  16980. */
  16981. class WebXRController {
  16982. /**
  16983. * Constructs a new XR controller.
  16984. */
  16985. constructor() {
  16986. /**
  16987. * A group representing the target ray space
  16988. * of the XR controller.
  16989. *
  16990. * @private
  16991. * @type {?Group}
  16992. * @default null
  16993. */
  16994. this._targetRay = null;
  16995. /**
  16996. * A group representing the grip space
  16997. * of the XR controller.
  16998. *
  16999. * @private
  17000. * @type {?Group}
  17001. * @default null
  17002. */
  17003. this._grip = null;
  17004. /**
  17005. * A group representing the hand space
  17006. * of the XR controller.
  17007. *
  17008. * @private
  17009. * @type {?Group}
  17010. * @default null
  17011. */
  17012. this._hand = null;
  17013. }
  17014. /**
  17015. * Returns a group representing the hand space of the XR controller.
  17016. *
  17017. * @return {Group} A group representing the hand space of the XR controller.
  17018. */
  17019. getHandSpace() {
  17020. if ( this._hand === null ) {
  17021. this._hand = new Group();
  17022. this._hand.matrixAutoUpdate = false;
  17023. this._hand.visible = false;
  17024. this._hand.joints = {};
  17025. this._hand.inputState = { pinching: false };
  17026. }
  17027. return this._hand;
  17028. }
  17029. /**
  17030. * Returns a group representing the target ray space of the XR controller.
  17031. *
  17032. * @return {Group} A group representing the target ray space of the XR controller.
  17033. */
  17034. getTargetRaySpace() {
  17035. if ( this._targetRay === null ) {
  17036. this._targetRay = new Group();
  17037. this._targetRay.matrixAutoUpdate = false;
  17038. this._targetRay.visible = false;
  17039. this._targetRay.hasLinearVelocity = false;
  17040. this._targetRay.linearVelocity = new Vector3();
  17041. this._targetRay.hasAngularVelocity = false;
  17042. this._targetRay.angularVelocity = new Vector3();
  17043. }
  17044. return this._targetRay;
  17045. }
  17046. /**
  17047. * Returns a group representing the grip space of the XR controller.
  17048. *
  17049. * @return {Group} A group representing the grip space of the XR controller.
  17050. */
  17051. getGripSpace() {
  17052. if ( this._grip === null ) {
  17053. this._grip = new Group();
  17054. this._grip.matrixAutoUpdate = false;
  17055. this._grip.visible = false;
  17056. this._grip.hasLinearVelocity = false;
  17057. this._grip.linearVelocity = new Vector3();
  17058. this._grip.hasAngularVelocity = false;
  17059. this._grip.angularVelocity = new Vector3();
  17060. }
  17061. return this._grip;
  17062. }
  17063. /**
  17064. * Dispatches the given event to the groups representing
  17065. * the different coordinate spaces of the XR controller.
  17066. *
  17067. * @param {Object} event - The event to dispatch.
  17068. * @return {WebXRController} A reference to this instance.
  17069. */
  17070. dispatchEvent( event ) {
  17071. if ( this._targetRay !== null ) {
  17072. this._targetRay.dispatchEvent( event );
  17073. }
  17074. if ( this._grip !== null ) {
  17075. this._grip.dispatchEvent( event );
  17076. }
  17077. if ( this._hand !== null ) {
  17078. this._hand.dispatchEvent( event );
  17079. }
  17080. return this;
  17081. }
  17082. /**
  17083. * Connects the controller with the given XR input source.
  17084. *
  17085. * @param {XRInputSource} inputSource - The input source.
  17086. * @return {WebXRController} A reference to this instance.
  17087. */
  17088. connect( inputSource ) {
  17089. if ( inputSource && inputSource.hand ) {
  17090. const hand = this._hand;
  17091. if ( hand ) {
  17092. for ( const inputjoint of inputSource.hand.values() ) {
  17093. // Initialize hand with joints when connected
  17094. this._getHandJoint( hand, inputjoint );
  17095. }
  17096. }
  17097. }
  17098. this.dispatchEvent( { type: 'connected', data: inputSource } );
  17099. return this;
  17100. }
  17101. /**
  17102. * Disconnects the controller from the given XR input source.
  17103. *
  17104. * @param {XRInputSource} inputSource - The input source.
  17105. * @return {WebXRController} A reference to this instance.
  17106. */
  17107. disconnect( inputSource ) {
  17108. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  17109. if ( this._targetRay !== null ) {
  17110. this._targetRay.visible = false;
  17111. }
  17112. if ( this._grip !== null ) {
  17113. this._grip.visible = false;
  17114. }
  17115. if ( this._hand !== null ) {
  17116. this._hand.visible = false;
  17117. }
  17118. return this;
  17119. }
  17120. /**
  17121. * Updates the controller with the given input source, XR frame and reference space.
  17122. * This updates the transformations of the groups that represent the different
  17123. * coordinate systems of the controller.
  17124. *
  17125. * @param {XRInputSource} inputSource - The input source.
  17126. * @param {XRFrame} frame - The XR frame.
  17127. * @param {XRReferenceSpace} referenceSpace - The reference space.
  17128. * @return {WebXRController} A reference to this instance.
  17129. */
  17130. update( inputSource, frame, referenceSpace ) {
  17131. let inputPose = null;
  17132. let gripPose = null;
  17133. let handPose = null;
  17134. const targetRay = this._targetRay;
  17135. const grip = this._grip;
  17136. const hand = this._hand;
  17137. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  17138. if ( hand && inputSource.hand ) {
  17139. handPose = true;
  17140. for ( const inputjoint of inputSource.hand.values() ) {
  17141. // Update the joints groups with the XRJoint poses
  17142. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  17143. // The transform of this joint will be updated with the joint pose on each frame
  17144. const joint = this._getHandJoint( hand, inputjoint );
  17145. if ( jointPose !== null ) {
  17146. joint.matrix.fromArray( jointPose.transform.matrix );
  17147. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  17148. joint.matrixWorldNeedsUpdate = true;
  17149. joint.jointRadius = jointPose.radius;
  17150. }
  17151. joint.visible = jointPose !== null;
  17152. }
  17153. // Custom events
  17154. // Check pinchz
  17155. const indexTip = hand.joints[ 'index-finger-tip' ];
  17156. const thumbTip = hand.joints[ 'thumb-tip' ];
  17157. const distance = indexTip.position.distanceTo( thumbTip.position );
  17158. const distanceToPinch = 0.02;
  17159. const threshold = 0.005;
  17160. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  17161. hand.inputState.pinching = false;
  17162. this.dispatchEvent( {
  17163. type: 'pinchend',
  17164. handedness: inputSource.handedness,
  17165. target: this
  17166. } );
  17167. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  17168. hand.inputState.pinching = true;
  17169. this.dispatchEvent( {
  17170. type: 'pinchstart',
  17171. handedness: inputSource.handedness,
  17172. target: this
  17173. } );
  17174. }
  17175. } else {
  17176. if ( grip !== null && inputSource.gripSpace ) {
  17177. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  17178. if ( gripPose !== null ) {
  17179. grip.matrix.fromArray( gripPose.transform.matrix );
  17180. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  17181. grip.matrixWorldNeedsUpdate = true;
  17182. if ( gripPose.linearVelocity ) {
  17183. grip.hasLinearVelocity = true;
  17184. grip.linearVelocity.copy( gripPose.linearVelocity );
  17185. } else {
  17186. grip.hasLinearVelocity = false;
  17187. }
  17188. if ( gripPose.angularVelocity ) {
  17189. grip.hasAngularVelocity = true;
  17190. grip.angularVelocity.copy( gripPose.angularVelocity );
  17191. } else {
  17192. grip.hasAngularVelocity = false;
  17193. }
  17194. }
  17195. }
  17196. }
  17197. if ( targetRay !== null ) {
  17198. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17199. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17200. if ( inputPose === null && gripPose !== null ) {
  17201. inputPose = gripPose;
  17202. }
  17203. if ( inputPose !== null ) {
  17204. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17205. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17206. targetRay.matrixWorldNeedsUpdate = true;
  17207. if ( inputPose.linearVelocity ) {
  17208. targetRay.hasLinearVelocity = true;
  17209. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17210. } else {
  17211. targetRay.hasLinearVelocity = false;
  17212. }
  17213. if ( inputPose.angularVelocity ) {
  17214. targetRay.hasAngularVelocity = true;
  17215. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17216. } else {
  17217. targetRay.hasAngularVelocity = false;
  17218. }
  17219. this.dispatchEvent( _moveEvent );
  17220. }
  17221. }
  17222. }
  17223. if ( targetRay !== null ) {
  17224. targetRay.visible = ( inputPose !== null );
  17225. }
  17226. if ( grip !== null ) {
  17227. grip.visible = ( gripPose !== null );
  17228. }
  17229. if ( hand !== null ) {
  17230. hand.visible = ( handPose !== null );
  17231. }
  17232. return this;
  17233. }
  17234. /**
  17235. * Returns a group representing the hand joint for the given input joint.
  17236. *
  17237. * @private
  17238. * @param {Group} hand - The group representing the hand space.
  17239. * @param {XRJointSpace} inputjoint - The hand joint data.
  17240. * @return {Group} A group representing the hand joint for the given input joint.
  17241. */
  17242. _getHandJoint( hand, inputjoint ) {
  17243. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17244. const joint = new Group();
  17245. joint.matrixAutoUpdate = false;
  17246. joint.visible = false;
  17247. hand.joints[ inputjoint.jointName ] = joint;
  17248. hand.add( joint );
  17249. }
  17250. return hand.joints[ inputjoint.jointName ];
  17251. }
  17252. }
  17253. /**
  17254. * This class can be used to define an exponential squared fog,
  17255. * which gives a clear view near the camera and a faster than exponentially
  17256. * densening fog farther from the camera.
  17257. *
  17258. * ```js
  17259. * const scene = new THREE.Scene();
  17260. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17261. * ```
  17262. */
  17263. class FogExp2 {
  17264. /**
  17265. * Constructs a new fog.
  17266. *
  17267. * @param {number|Color} color - The fog's color.
  17268. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17269. */
  17270. constructor( color, density = 0.00025 ) {
  17271. /**
  17272. * This flag can be used for type testing.
  17273. *
  17274. * @type {boolean}
  17275. * @readonly
  17276. * @default true
  17277. */
  17278. this.isFogExp2 = true;
  17279. /**
  17280. * The name of the fog.
  17281. *
  17282. * @type {string}
  17283. */
  17284. this.name = '';
  17285. /**
  17286. * The fog's color.
  17287. *
  17288. * @type {Color}
  17289. */
  17290. this.color = new Color( color );
  17291. /**
  17292. * Defines how fast the fog will grow dense.
  17293. *
  17294. * @type {number}
  17295. * @default 0.00025
  17296. */
  17297. this.density = density;
  17298. }
  17299. /**
  17300. * Returns a new fog with copied values from this instance.
  17301. *
  17302. * @return {FogExp2} A clone of this instance.
  17303. */
  17304. clone() {
  17305. return new FogExp2( this.color, this.density );
  17306. }
  17307. /**
  17308. * Serializes the fog into JSON.
  17309. *
  17310. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17311. * @return {Object} A JSON object representing the serialized fog
  17312. */
  17313. toJSON( /* meta */ ) {
  17314. return {
  17315. type: 'FogExp2',
  17316. name: this.name,
  17317. color: this.color.getHex(),
  17318. density: this.density
  17319. };
  17320. }
  17321. }
  17322. /**
  17323. * This class can be used to define a linear fog that grows linearly denser
  17324. * with the distance.
  17325. *
  17326. * ```js
  17327. * const scene = new THREE.Scene();
  17328. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17329. * ```
  17330. */
  17331. class Fog {
  17332. /**
  17333. * Constructs a new fog.
  17334. *
  17335. * @param {number|Color} color - The fog's color.
  17336. * @param {number} [near=1] - The minimum distance to start applying fog.
  17337. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17338. */
  17339. constructor( color, near = 1, far = 1000 ) {
  17340. /**
  17341. * This flag can be used for type testing.
  17342. *
  17343. * @type {boolean}
  17344. * @readonly
  17345. * @default true
  17346. */
  17347. this.isFog = true;
  17348. /**
  17349. * The name of the fog.
  17350. *
  17351. * @type {string}
  17352. */
  17353. this.name = '';
  17354. /**
  17355. * The fog's color.
  17356. *
  17357. * @type {Color}
  17358. */
  17359. this.color = new Color( color );
  17360. /**
  17361. * The minimum distance to start applying fog. Objects that are less than
  17362. * `near` units from the active camera won't be affected by fog.
  17363. *
  17364. * @type {number}
  17365. * @default 1
  17366. */
  17367. this.near = near;
  17368. /**
  17369. * The maximum distance at which fog stops being calculated and applied.
  17370. * Objects that are more than `far` units away from the active camera won't
  17371. * be affected by fog.
  17372. *
  17373. * @type {number}
  17374. * @default 1000
  17375. */
  17376. this.far = far;
  17377. }
  17378. /**
  17379. * Returns a new fog with copied values from this instance.
  17380. *
  17381. * @return {Fog} A clone of this instance.
  17382. */
  17383. clone() {
  17384. return new Fog( this.color, this.near, this.far );
  17385. }
  17386. /**
  17387. * Serializes the fog into JSON.
  17388. *
  17389. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17390. * @return {Object} A JSON object representing the serialized fog
  17391. */
  17392. toJSON( /* meta */ ) {
  17393. return {
  17394. type: 'Fog',
  17395. name: this.name,
  17396. color: this.color.getHex(),
  17397. near: this.near,
  17398. far: this.far
  17399. };
  17400. }
  17401. }
  17402. /**
  17403. * Scenes allow you to set up what is to be rendered and where by three.js.
  17404. * This is where you place 3D objects like meshes, lines or lights.
  17405. *
  17406. * @augments Object3D
  17407. */
  17408. class Scene extends Object3D {
  17409. /**
  17410. * Constructs a new scene.
  17411. */
  17412. constructor() {
  17413. super();
  17414. /**
  17415. * This flag can be used for type testing.
  17416. *
  17417. * @type {boolean}
  17418. * @readonly
  17419. * @default true
  17420. */
  17421. this.isScene = true;
  17422. this.type = 'Scene';
  17423. /**
  17424. * Defines the background of the scene. Valid inputs are:
  17425. *
  17426. * - A color for defining a uniform colored background.
  17427. * - A texture for defining a (flat) textured background.
  17428. * - Cube textures or equirectangular textures for defining a skybox.
  17429. *
  17430. * @type {?(Color|Texture)}
  17431. * @default null
  17432. */
  17433. this.background = null;
  17434. /**
  17435. * Sets the environment map for all physical materials in the scene. However,
  17436. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17437. * material property.
  17438. *
  17439. * @type {?Texture}
  17440. * @default null
  17441. */
  17442. this.environment = null;
  17443. /**
  17444. * A fog instance defining the type of fog that affects everything
  17445. * rendered in the scene.
  17446. *
  17447. * @type {?(Fog|FogExp2)}
  17448. * @default null
  17449. */
  17450. this.fog = null;
  17451. /**
  17452. * Sets the blurriness of the background. Only influences environment maps
  17453. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17454. * and `1`.
  17455. *
  17456. * @type {number}
  17457. * @default 0
  17458. */
  17459. this.backgroundBlurriness = 0;
  17460. /**
  17461. * Attenuates the color of the background. Only applies to background textures.
  17462. *
  17463. * @type {number}
  17464. * @default 1
  17465. */
  17466. this.backgroundIntensity = 1;
  17467. /**
  17468. * The rotation of the background in radians. Only influences environment maps
  17469. * assigned to {@link Scene#background}.
  17470. *
  17471. * @type {Euler}
  17472. * @default (0,0,0)
  17473. */
  17474. this.backgroundRotation = new Euler();
  17475. /**
  17476. * Attenuates the color of the environment. Only influences environment maps
  17477. * assigned to {@link Scene#environment}.
  17478. *
  17479. * @type {number}
  17480. * @default 1
  17481. */
  17482. this.environmentIntensity = 1;
  17483. /**
  17484. * The rotation of the environment map in radians. Only influences physical materials
  17485. * in the scene when {@link Scene#environment} is used.
  17486. *
  17487. * @type {Euler}
  17488. * @default (0,0,0)
  17489. */
  17490. this.environmentRotation = new Euler();
  17491. /**
  17492. * Forces everything in the scene to be rendered with the defined material. It is possible
  17493. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17494. *
  17495. * @type {?Material}
  17496. * @default null
  17497. */
  17498. this.overrideMaterial = null;
  17499. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17500. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17501. }
  17502. }
  17503. copy( source, recursive ) {
  17504. super.copy( source, recursive );
  17505. if ( source.background !== null ) this.background = source.background.clone();
  17506. if ( source.environment !== null ) this.environment = source.environment.clone();
  17507. if ( source.fog !== null ) this.fog = source.fog.clone();
  17508. this.backgroundBlurriness = source.backgroundBlurriness;
  17509. this.backgroundIntensity = source.backgroundIntensity;
  17510. this.backgroundRotation.copy( source.backgroundRotation );
  17511. this.environmentIntensity = source.environmentIntensity;
  17512. this.environmentRotation.copy( source.environmentRotation );
  17513. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17514. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17515. return this;
  17516. }
  17517. toJSON( meta ) {
  17518. const data = super.toJSON( meta );
  17519. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17520. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17521. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17522. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17523. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17524. data.object.environmentRotation = this.environmentRotation.toArray();
  17525. return data;
  17526. }
  17527. }
  17528. /**
  17529. * "Interleaved" means that multiple attributes, possibly of different types,
  17530. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17531. *
  17532. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17533. */
  17534. class InterleavedBuffer {
  17535. /**
  17536. * Constructs a new interleaved buffer.
  17537. *
  17538. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17539. * @param {number} stride - The number of typed-array elements per vertex.
  17540. */
  17541. constructor( array, stride ) {
  17542. /**
  17543. * This flag can be used for type testing.
  17544. *
  17545. * @type {boolean}
  17546. * @readonly
  17547. * @default true
  17548. */
  17549. this.isInterleavedBuffer = true;
  17550. /**
  17551. * A typed array with a shared buffer storing attribute data.
  17552. *
  17553. * @type {TypedArray}
  17554. */
  17555. this.array = array;
  17556. /**
  17557. * The number of typed-array elements per vertex.
  17558. *
  17559. * @type {number}
  17560. */
  17561. this.stride = stride;
  17562. /**
  17563. * The total number of elements in the array
  17564. *
  17565. * @type {number}
  17566. * @readonly
  17567. */
  17568. this.count = array !== undefined ? array.length / stride : 0;
  17569. /**
  17570. * Defines the intended usage pattern of the data store for optimization purposes.
  17571. *
  17572. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17573. * instantiate a new one and set the desired usage before the next render.
  17574. *
  17575. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17576. * @default StaticDrawUsage
  17577. */
  17578. this.usage = StaticDrawUsage;
  17579. /**
  17580. * This can be used to only update some components of stored vectors (for example, just the
  17581. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17582. *
  17583. * @type {Array<Object>}
  17584. */
  17585. this.updateRanges = [];
  17586. /**
  17587. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17588. *
  17589. * @type {number}
  17590. */
  17591. this.version = 0;
  17592. /**
  17593. * The UUID of the interleaved buffer.
  17594. *
  17595. * @type {string}
  17596. * @readonly
  17597. */
  17598. this.uuid = generateUUID();
  17599. }
  17600. /**
  17601. * A callback function that is executed after the renderer has transferred the attribute array
  17602. * data to the GPU.
  17603. */
  17604. onUploadCallback() {}
  17605. /**
  17606. * Flag to indicate that this attribute has changed and should be re-sent to
  17607. * the GPU. Set this to `true` when you modify the value of the array.
  17608. *
  17609. * @type {number}
  17610. * @default false
  17611. * @param {boolean} value
  17612. */
  17613. set needsUpdate( value ) {
  17614. if ( value === true ) this.version ++;
  17615. }
  17616. /**
  17617. * Sets the usage of this interleaved buffer.
  17618. *
  17619. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17620. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17621. */
  17622. setUsage( value ) {
  17623. this.usage = value;
  17624. return this;
  17625. }
  17626. /**
  17627. * Adds a range of data in the data array to be updated on the GPU.
  17628. *
  17629. * @param {number} start - Position at which to start update.
  17630. * @param {number} count - The number of components to update.
  17631. */
  17632. addUpdateRange( start, count ) {
  17633. this.updateRanges.push( { start, count } );
  17634. }
  17635. /**
  17636. * Clears the update ranges.
  17637. */
  17638. clearUpdateRanges() {
  17639. this.updateRanges.length = 0;
  17640. }
  17641. /**
  17642. * Copies the values of the given interleaved buffer to this instance.
  17643. *
  17644. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17645. * @return {InterleavedBuffer} A reference to this instance.
  17646. */
  17647. copy( source ) {
  17648. this.array = new source.array.constructor( source.array );
  17649. this.count = source.count;
  17650. this.stride = source.stride;
  17651. this.usage = source.usage;
  17652. return this;
  17653. }
  17654. /**
  17655. * Copies a vector from the given interleaved buffer to this one. The start
  17656. * and destination position in the attribute buffers are represented by the
  17657. * given indices.
  17658. *
  17659. * @param {number} index1 - The destination index into this interleaved buffer.
  17660. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17661. * @param {number} index2 - The source index into the given interleaved buffer.
  17662. * @return {InterleavedBuffer} A reference to this instance.
  17663. */
  17664. copyAt( index1, interleavedBuffer, index2 ) {
  17665. index1 *= this.stride;
  17666. index2 *= interleavedBuffer.stride;
  17667. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17668. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17669. }
  17670. return this;
  17671. }
  17672. /**
  17673. * Sets the given array data in the interleaved buffer.
  17674. *
  17675. * @param {(TypedArray|Array)} value - The array data to set.
  17676. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17677. * @return {InterleavedBuffer} A reference to this instance.
  17678. */
  17679. set( value, offset = 0 ) {
  17680. this.array.set( value, offset );
  17681. return this;
  17682. }
  17683. /**
  17684. * Returns a new interleaved buffer with copied values from this instance.
  17685. *
  17686. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17687. * @return {InterleavedBuffer} A clone of this instance.
  17688. */
  17689. clone( data ) {
  17690. if ( data.arrayBuffers === undefined ) {
  17691. data.arrayBuffers = {};
  17692. }
  17693. if ( this.array.buffer._uuid === undefined ) {
  17694. this.array.buffer._uuid = generateUUID();
  17695. }
  17696. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17697. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17698. }
  17699. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17700. const ib = new this.constructor( array, this.stride );
  17701. ib.setUsage( this.usage );
  17702. return ib;
  17703. }
  17704. /**
  17705. * Sets the given callback function that is executed after the Renderer has transferred
  17706. * the array data to the GPU. Can be used to perform clean-up operations after
  17707. * the upload when data are not needed anymore on the CPU side.
  17708. *
  17709. * @param {Function} callback - The `onUpload()` callback.
  17710. * @return {InterleavedBuffer} A reference to this instance.
  17711. */
  17712. onUpload( callback ) {
  17713. this.onUploadCallback = callback;
  17714. return this;
  17715. }
  17716. /**
  17717. * Serializes the interleaved buffer into JSON.
  17718. *
  17719. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17720. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17721. */
  17722. toJSON( data ) {
  17723. if ( data.arrayBuffers === undefined ) {
  17724. data.arrayBuffers = {};
  17725. }
  17726. // generate UUID for array buffer if necessary
  17727. if ( this.array.buffer._uuid === undefined ) {
  17728. this.array.buffer._uuid = generateUUID();
  17729. }
  17730. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17731. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17732. }
  17733. //
  17734. return {
  17735. uuid: this.uuid,
  17736. buffer: this.array.buffer._uuid,
  17737. type: this.array.constructor.name,
  17738. stride: this.stride
  17739. };
  17740. }
  17741. }
  17742. const _vector$7 = /*@__PURE__*/ new Vector3();
  17743. /**
  17744. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17745. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17746. * different offsets into the buffer.
  17747. */
  17748. class InterleavedBufferAttribute {
  17749. /**
  17750. * Constructs a new interleaved buffer attribute.
  17751. *
  17752. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17753. * @param {number} itemSize - The item size.
  17754. * @param {number} offset - The attribute offset into the buffer.
  17755. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17756. */
  17757. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17758. /**
  17759. * This flag can be used for type testing.
  17760. *
  17761. * @type {boolean}
  17762. * @readonly
  17763. * @default true
  17764. */
  17765. this.isInterleavedBufferAttribute = true;
  17766. /**
  17767. * The name of the buffer attribute.
  17768. *
  17769. * @type {string}
  17770. */
  17771. this.name = '';
  17772. /**
  17773. * The buffer holding the interleaved data.
  17774. *
  17775. * @type {InterleavedBuffer}
  17776. */
  17777. this.data = interleavedBuffer;
  17778. /**
  17779. * The item size, see {@link BufferAttribute#itemSize}.
  17780. *
  17781. * @type {number}
  17782. */
  17783. this.itemSize = itemSize;
  17784. /**
  17785. * The attribute offset into the buffer.
  17786. *
  17787. * @type {number}
  17788. */
  17789. this.offset = offset;
  17790. /**
  17791. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17792. *
  17793. * @type {InterleavedBuffer}
  17794. */
  17795. this.normalized = normalized;
  17796. }
  17797. /**
  17798. * The item count of this buffer attribute.
  17799. *
  17800. * @type {number}
  17801. * @readonly
  17802. */
  17803. get count() {
  17804. return this.data.count;
  17805. }
  17806. /**
  17807. * The array holding the interleaved buffer attribute data.
  17808. *
  17809. * @type {TypedArray}
  17810. */
  17811. get array() {
  17812. return this.data.array;
  17813. }
  17814. /**
  17815. * Flag to indicate that this attribute has changed and should be re-sent to
  17816. * the GPU. Set this to `true` when you modify the value of the array.
  17817. *
  17818. * @type {number}
  17819. * @default false
  17820. * @param {boolean} value
  17821. */
  17822. set needsUpdate( value ) {
  17823. this.data.needsUpdate = value;
  17824. }
  17825. /**
  17826. * Applies the given 4x4 matrix to the given attribute. Only works with
  17827. * item size `3`.
  17828. *
  17829. * @param {Matrix4} m - The matrix to apply.
  17830. * @return {InterleavedBufferAttribute} A reference to this instance.
  17831. */
  17832. applyMatrix4( m ) {
  17833. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17834. _vector$7.fromBufferAttribute( this, i );
  17835. _vector$7.applyMatrix4( m );
  17836. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17837. }
  17838. return this;
  17839. }
  17840. /**
  17841. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17842. * item size `3`.
  17843. *
  17844. * @param {Matrix3} m - The normal matrix to apply.
  17845. * @return {InterleavedBufferAttribute} A reference to this instance.
  17846. */
  17847. applyNormalMatrix( m ) {
  17848. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17849. _vector$7.fromBufferAttribute( this, i );
  17850. _vector$7.applyNormalMatrix( m );
  17851. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17852. }
  17853. return this;
  17854. }
  17855. /**
  17856. * Applies the given 4x4 matrix to the given attribute. Only works with
  17857. * item size `3` and with direction vectors.
  17858. *
  17859. * @param {Matrix4} m - The matrix to apply.
  17860. * @return {InterleavedBufferAttribute} A reference to this instance.
  17861. */
  17862. transformDirection( m ) {
  17863. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17864. _vector$7.fromBufferAttribute( this, i );
  17865. _vector$7.transformDirection( m );
  17866. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17867. }
  17868. return this;
  17869. }
  17870. /**
  17871. * Returns the given component of the vector at the given index.
  17872. *
  17873. * @param {number} index - The index into the buffer attribute.
  17874. * @param {number} component - The component index.
  17875. * @return {number} The returned value.
  17876. */
  17877. getComponent( index, component ) {
  17878. let value = this.array[ index * this.data.stride + this.offset + component ];
  17879. if ( this.normalized ) value = denormalize( value, this.array );
  17880. return value;
  17881. }
  17882. /**
  17883. * Sets the given value to the given component of the vector at the given index.
  17884. *
  17885. * @param {number} index - The index into the buffer attribute.
  17886. * @param {number} component - The component index.
  17887. * @param {number} value - The value to set.
  17888. * @return {InterleavedBufferAttribute} A reference to this instance.
  17889. */
  17890. setComponent( index, component, value ) {
  17891. if ( this.normalized ) value = normalize( value, this.array );
  17892. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17893. return this;
  17894. }
  17895. /**
  17896. * Sets the x component of the vector at the given index.
  17897. *
  17898. * @param {number} index - The index into the buffer attribute.
  17899. * @param {number} x - The value to set.
  17900. * @return {InterleavedBufferAttribute} A reference to this instance.
  17901. */
  17902. setX( index, x ) {
  17903. if ( this.normalized ) x = normalize( x, this.array );
  17904. this.data.array[ index * this.data.stride + this.offset ] = x;
  17905. return this;
  17906. }
  17907. /**
  17908. * Sets the y component of the vector at the given index.
  17909. *
  17910. * @param {number} index - The index into the buffer attribute.
  17911. * @param {number} y - The value to set.
  17912. * @return {InterleavedBufferAttribute} A reference to this instance.
  17913. */
  17914. setY( index, y ) {
  17915. if ( this.normalized ) y = normalize( y, this.array );
  17916. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17917. return this;
  17918. }
  17919. /**
  17920. * Sets the z component of the vector at the given index.
  17921. *
  17922. * @param {number} index - The index into the buffer attribute.
  17923. * @param {number} z - The value to set.
  17924. * @return {InterleavedBufferAttribute} A reference to this instance.
  17925. */
  17926. setZ( index, z ) {
  17927. if ( this.normalized ) z = normalize( z, this.array );
  17928. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17929. return this;
  17930. }
  17931. /**
  17932. * Sets the w component of the vector at the given index.
  17933. *
  17934. * @param {number} index - The index into the buffer attribute.
  17935. * @param {number} w - The value to set.
  17936. * @return {InterleavedBufferAttribute} A reference to this instance.
  17937. */
  17938. setW( index, w ) {
  17939. if ( this.normalized ) w = normalize( w, this.array );
  17940. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17941. return this;
  17942. }
  17943. /**
  17944. * Returns the x component of the vector at the given index.
  17945. *
  17946. * @param {number} index - The index into the buffer attribute.
  17947. * @return {number} The x component.
  17948. */
  17949. getX( index ) {
  17950. let x = this.data.array[ index * this.data.stride + this.offset ];
  17951. if ( this.normalized ) x = denormalize( x, this.array );
  17952. return x;
  17953. }
  17954. /**
  17955. * Returns the y component of the vector at the given index.
  17956. *
  17957. * @param {number} index - The index into the buffer attribute.
  17958. * @return {number} The y component.
  17959. */
  17960. getY( index ) {
  17961. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17962. if ( this.normalized ) y = denormalize( y, this.array );
  17963. return y;
  17964. }
  17965. /**
  17966. * Returns the z component of the vector at the given index.
  17967. *
  17968. * @param {number} index - The index into the buffer attribute.
  17969. * @return {number} The z component.
  17970. */
  17971. getZ( index ) {
  17972. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17973. if ( this.normalized ) z = denormalize( z, this.array );
  17974. return z;
  17975. }
  17976. /**
  17977. * Returns the w component of the vector at the given index.
  17978. *
  17979. * @param {number} index - The index into the buffer attribute.
  17980. * @return {number} The w component.
  17981. */
  17982. getW( index ) {
  17983. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17984. if ( this.normalized ) w = denormalize( w, this.array );
  17985. return w;
  17986. }
  17987. /**
  17988. * Sets the x and y component of the vector at the given index.
  17989. *
  17990. * @param {number} index - The index into the buffer attribute.
  17991. * @param {number} x - The value for the x component to set.
  17992. * @param {number} y - The value for the y component to set.
  17993. * @return {InterleavedBufferAttribute} A reference to this instance.
  17994. */
  17995. setXY( index, x, y ) {
  17996. index = index * this.data.stride + this.offset;
  17997. if ( this.normalized ) {
  17998. x = normalize( x, this.array );
  17999. y = normalize( y, this.array );
  18000. }
  18001. this.data.array[ index + 0 ] = x;
  18002. this.data.array[ index + 1 ] = y;
  18003. return this;
  18004. }
  18005. /**
  18006. * Sets the x, y and z component of the vector at the given index.
  18007. *
  18008. * @param {number} index - The index into the buffer attribute.
  18009. * @param {number} x - The value for the x component to set.
  18010. * @param {number} y - The value for the y component to set.
  18011. * @param {number} z - The value for the z component to set.
  18012. * @return {InterleavedBufferAttribute} A reference to this instance.
  18013. */
  18014. setXYZ( index, x, y, z ) {
  18015. index = index * this.data.stride + this.offset;
  18016. if ( this.normalized ) {
  18017. x = normalize( x, this.array );
  18018. y = normalize( y, this.array );
  18019. z = normalize( z, this.array );
  18020. }
  18021. this.data.array[ index + 0 ] = x;
  18022. this.data.array[ index + 1 ] = y;
  18023. this.data.array[ index + 2 ] = z;
  18024. return this;
  18025. }
  18026. /**
  18027. * Sets the x, y, z and w component of the vector at the given index.
  18028. *
  18029. * @param {number} index - The index into the buffer attribute.
  18030. * @param {number} x - The value for the x component to set.
  18031. * @param {number} y - The value for the y component to set.
  18032. * @param {number} z - The value for the z component to set.
  18033. * @param {number} w - The value for the w component to set.
  18034. * @return {InterleavedBufferAttribute} A reference to this instance.
  18035. */
  18036. setXYZW( index, x, y, z, w ) {
  18037. index = index * this.data.stride + this.offset;
  18038. if ( this.normalized ) {
  18039. x = normalize( x, this.array );
  18040. y = normalize( y, this.array );
  18041. z = normalize( z, this.array );
  18042. w = normalize( w, this.array );
  18043. }
  18044. this.data.array[ index + 0 ] = x;
  18045. this.data.array[ index + 1 ] = y;
  18046. this.data.array[ index + 2 ] = z;
  18047. this.data.array[ index + 3 ] = w;
  18048. return this;
  18049. }
  18050. /**
  18051. * Returns a new buffer attribute with copied values from this instance.
  18052. *
  18053. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18054. *
  18055. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  18056. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  18057. */
  18058. clone( data ) {
  18059. if ( data === undefined ) {
  18060. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18061. const array = [];
  18062. for ( let i = 0; i < this.count; i ++ ) {
  18063. const index = i * this.data.stride + this.offset;
  18064. for ( let j = 0; j < this.itemSize; j ++ ) {
  18065. array.push( this.data.array[ index + j ] );
  18066. }
  18067. }
  18068. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18069. } else {
  18070. if ( data.interleavedBuffers === undefined ) {
  18071. data.interleavedBuffers = {};
  18072. }
  18073. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18074. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18075. }
  18076. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18077. }
  18078. }
  18079. /**
  18080. * Serializes the buffer attribute into JSON.
  18081. *
  18082. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  18083. *
  18084. * @param {Object} [data] - An optional value holding meta information about the serialization.
  18085. * @return {Object} A JSON object representing the serialized buffer attribute.
  18086. */
  18087. toJSON( data ) {
  18088. if ( data === undefined ) {
  18089. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18090. const array = [];
  18091. for ( let i = 0; i < this.count; i ++ ) {
  18092. const index = i * this.data.stride + this.offset;
  18093. for ( let j = 0; j < this.itemSize; j ++ ) {
  18094. array.push( this.data.array[ index + j ] );
  18095. }
  18096. }
  18097. // de-interleave data and save it as an ordinary buffer attribute for now
  18098. return {
  18099. itemSize: this.itemSize,
  18100. type: this.array.constructor.name,
  18101. array: array,
  18102. normalized: this.normalized
  18103. };
  18104. } else {
  18105. // save as true interleaved attribute
  18106. if ( data.interleavedBuffers === undefined ) {
  18107. data.interleavedBuffers = {};
  18108. }
  18109. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18110. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18111. }
  18112. return {
  18113. isInterleavedBufferAttribute: true,
  18114. itemSize: this.itemSize,
  18115. data: this.data.uuid,
  18116. offset: this.offset,
  18117. normalized: this.normalized
  18118. };
  18119. }
  18120. }
  18121. }
  18122. /**
  18123. * A material for rendering instances of {@link Sprite}.
  18124. *
  18125. * ```js
  18126. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  18127. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  18128. *
  18129. * const sprite = new THREE.Sprite( material );
  18130. * sprite.scale.set(200, 200, 1)
  18131. * scene.add( sprite );
  18132. * ```
  18133. *
  18134. * @augments Material
  18135. */
  18136. class SpriteMaterial extends Material {
  18137. /**
  18138. * Constructs a new sprite material.
  18139. *
  18140. * @param {Object} [parameters] - An object with one or more properties
  18141. * defining the material's appearance. Any property of the material
  18142. * (including any property from inherited materials) can be passed
  18143. * in here. Color values can be passed any type of value accepted
  18144. * by {@link Color#set}.
  18145. */
  18146. constructor( parameters ) {
  18147. super();
  18148. /**
  18149. * This flag can be used for type testing.
  18150. *
  18151. * @type {boolean}
  18152. * @readonly
  18153. * @default true
  18154. */
  18155. this.isSpriteMaterial = true;
  18156. this.type = 'SpriteMaterial';
  18157. /**
  18158. * Color of the material.
  18159. *
  18160. * @type {Color}
  18161. * @default (1,1,1)
  18162. */
  18163. this.color = new Color( 0xffffff );
  18164. /**
  18165. * The color map. May optionally include an alpha channel, typically combined
  18166. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  18167. * color is modulated by the diffuse `color`.
  18168. *
  18169. * @type {?Texture}
  18170. * @default null
  18171. */
  18172. this.map = null;
  18173. /**
  18174. * The alpha map is a grayscale texture that controls the opacity across the
  18175. * surface (black: fully transparent; white: fully opaque).
  18176. *
  18177. * Only the color of the texture is used, ignoring the alpha channel if one
  18178. * exists. For RGB and RGBA textures, the renderer will use the green channel
  18179. * when sampling this texture due to the extra bit of precision provided for
  18180. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  18181. * luminance/alpha textures will also still work as expected.
  18182. *
  18183. * @type {?Texture}
  18184. * @default null
  18185. */
  18186. this.alphaMap = null;
  18187. /**
  18188. * The rotation of the sprite in radians.
  18189. *
  18190. * @type {number}
  18191. * @default 0
  18192. */
  18193. this.rotation = 0;
  18194. /**
  18195. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18196. *
  18197. * @type {boolean}
  18198. * @default true
  18199. */
  18200. this.sizeAttenuation = true;
  18201. /**
  18202. * Overwritten since sprite materials are transparent
  18203. * by default.
  18204. *
  18205. * @type {boolean}
  18206. * @default true
  18207. */
  18208. this.transparent = true;
  18209. /**
  18210. * Whether the material is affected by fog or not.
  18211. *
  18212. * @type {boolean}
  18213. * @default true
  18214. */
  18215. this.fog = true;
  18216. this.setValues( parameters );
  18217. }
  18218. copy( source ) {
  18219. super.copy( source );
  18220. this.color.copy( source.color );
  18221. this.map = source.map;
  18222. this.alphaMap = source.alphaMap;
  18223. this.rotation = source.rotation;
  18224. this.sizeAttenuation = source.sizeAttenuation;
  18225. this.fog = source.fog;
  18226. return this;
  18227. }
  18228. }
  18229. let _geometry;
  18230. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18231. const _worldScale = /*@__PURE__*/ new Vector3();
  18232. const _mvPosition = /*@__PURE__*/ new Vector3();
  18233. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18234. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18235. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18236. const _vA = /*@__PURE__*/ new Vector3();
  18237. const _vB = /*@__PURE__*/ new Vector3();
  18238. const _vC = /*@__PURE__*/ new Vector3();
  18239. const _uvA = /*@__PURE__*/ new Vector2();
  18240. const _uvB = /*@__PURE__*/ new Vector2();
  18241. const _uvC = /*@__PURE__*/ new Vector2();
  18242. /**
  18243. * A sprite is a plane that always faces towards the camera, generally with a
  18244. * partially transparent texture applied.
  18245. *
  18246. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18247. * have no effect.
  18248. *
  18249. * ```js
  18250. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18251. * const material = new THREE.SpriteMaterial( { map: map } );
  18252. *
  18253. * const sprite = new THREE.Sprite( material );
  18254. * scene.add( sprite );
  18255. * ```
  18256. *
  18257. * @augments Object3D
  18258. */
  18259. class Sprite extends Object3D {
  18260. /**
  18261. * Constructs a new sprite.
  18262. *
  18263. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18264. */
  18265. constructor( material = new SpriteMaterial() ) {
  18266. super();
  18267. /**
  18268. * This flag can be used for type testing.
  18269. *
  18270. * @type {boolean}
  18271. * @readonly
  18272. * @default true
  18273. */
  18274. this.isSprite = true;
  18275. this.type = 'Sprite';
  18276. if ( _geometry === undefined ) {
  18277. _geometry = new BufferGeometry();
  18278. const float32Array = new Float32Array( [
  18279. -0.5, -0.5, 0, 0, 0,
  18280. 0.5, -0.5, 0, 1, 0,
  18281. 0.5, 0.5, 0, 1, 1,
  18282. -0.5, 0.5, 0, 0, 1
  18283. ] );
  18284. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18285. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18286. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18287. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18288. }
  18289. /**
  18290. * The sprite geometry.
  18291. *
  18292. * @type {BufferGeometry}
  18293. */
  18294. this.geometry = _geometry;
  18295. /**
  18296. * The sprite material.
  18297. *
  18298. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18299. */
  18300. this.material = material;
  18301. /**
  18302. * The sprite's anchor point, and the point around which the sprite rotates.
  18303. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18304. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18305. *
  18306. * @type {Vector2}
  18307. * @default (0.5,0.5)
  18308. */
  18309. this.center = new Vector2( 0.5, 0.5 );
  18310. /**
  18311. * The number of instances of this sprite.
  18312. * Can only be used with {@link WebGPURenderer}.
  18313. *
  18314. * @type {number}
  18315. * @default 1
  18316. */
  18317. this.count = 1;
  18318. }
  18319. /**
  18320. * Computes intersection points between a casted ray and this sprite.
  18321. *
  18322. * @param {Raycaster} raycaster - The raycaster.
  18323. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18324. */
  18325. raycast( raycaster, intersects ) {
  18326. if ( raycaster.camera === null ) {
  18327. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18328. }
  18329. _worldScale.setFromMatrixScale( this.matrixWorld );
  18330. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18331. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18332. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18333. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18334. _worldScale.multiplyScalar( - _mvPosition.z );
  18335. }
  18336. const rotation = this.material.rotation;
  18337. let sin, cos;
  18338. if ( rotation !== 0 ) {
  18339. cos = Math.cos( rotation );
  18340. sin = Math.sin( rotation );
  18341. }
  18342. const center = this.center;
  18343. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18344. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18345. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18346. _uvA.set( 0, 0 );
  18347. _uvB.set( 1, 0 );
  18348. _uvC.set( 1, 1 );
  18349. // check first triangle
  18350. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18351. if ( intersect === null ) {
  18352. // check second triangle
  18353. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18354. _uvB.set( 0, 1 );
  18355. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18356. if ( intersect === null ) {
  18357. return;
  18358. }
  18359. }
  18360. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18361. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18362. intersects.push( {
  18363. distance: distance,
  18364. point: _intersectPoint.clone(),
  18365. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18366. face: null,
  18367. object: this
  18368. } );
  18369. }
  18370. copy( source, recursive ) {
  18371. super.copy( source, recursive );
  18372. if ( source.center !== undefined ) this.center.copy( source.center );
  18373. this.material = source.material;
  18374. return this;
  18375. }
  18376. }
  18377. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18378. // compute position in camera space
  18379. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18380. // to check if rotation is not zero
  18381. if ( sin !== undefined ) {
  18382. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18383. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18384. } else {
  18385. _rotatedPosition.copy( _alignedPosition );
  18386. }
  18387. vertexPosition.copy( mvPosition );
  18388. vertexPosition.x += _rotatedPosition.x;
  18389. vertexPosition.y += _rotatedPosition.y;
  18390. // transform to world space
  18391. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18392. }
  18393. const _v1$2 = /*@__PURE__*/ new Vector3();
  18394. const _v2$1 = /*@__PURE__*/ new Vector3();
  18395. /**
  18396. * A component for providing a basic Level of Detail (LOD) mechanism.
  18397. *
  18398. * Every LOD level is associated with an object, and rendering can be switched
  18399. * between them at the distances specified. Typically you would create, say,
  18400. * three meshes, one for far away (low detail), one for mid range (medium
  18401. * detail) and one for close up (high detail).
  18402. *
  18403. * ```js
  18404. * const lod = new THREE.LOD();
  18405. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18406. *
  18407. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18408. * for( let i = 0; i < 3; i++ ) {
  18409. *
  18410. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18411. * const mesh = new THREE.Mesh( geometry, material );
  18412. * lod.addLevel( mesh, i * 75 );
  18413. *
  18414. * }
  18415. *
  18416. * scene.add( lod );
  18417. * ```
  18418. *
  18419. * @augments Object3D
  18420. */
  18421. class LOD extends Object3D {
  18422. /**
  18423. * Constructs a new LOD.
  18424. */
  18425. constructor() {
  18426. super();
  18427. /**
  18428. * This flag can be used for type testing.
  18429. *
  18430. * @type {boolean}
  18431. * @readonly
  18432. * @default true
  18433. */
  18434. this.isLOD = true;
  18435. /**
  18436. * The current LOD index.
  18437. *
  18438. * @private
  18439. * @type {number}
  18440. * @default 0
  18441. */
  18442. this._currentLevel = 0;
  18443. this.type = 'LOD';
  18444. Object.defineProperties( this, {
  18445. /**
  18446. * This array holds the LOD levels.
  18447. *
  18448. * @name LOD#levels
  18449. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18450. */
  18451. levels: {
  18452. enumerable: true,
  18453. value: []
  18454. }
  18455. } );
  18456. /**
  18457. * Whether the LOD object is updated automatically by the renderer per frame
  18458. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18459. * render loop by yourself.
  18460. *
  18461. * @type {boolean}
  18462. * @default true
  18463. */
  18464. this.autoUpdate = true;
  18465. }
  18466. copy( source ) {
  18467. super.copy( source, false );
  18468. const levels = source.levels;
  18469. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18470. const level = levels[ i ];
  18471. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18472. }
  18473. this.autoUpdate = source.autoUpdate;
  18474. return this;
  18475. }
  18476. /**
  18477. * Adds a mesh that will display at a certain distance and greater. Typically
  18478. * the further away the distance, the lower the detail on the mesh.
  18479. *
  18480. * @param {Object3D} object - The 3D object to display at this level.
  18481. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18482. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18483. * @return {LOD} A reference to this instance.
  18484. */
  18485. addLevel( object, distance = 0, hysteresis = 0 ) {
  18486. distance = Math.abs( distance );
  18487. const levels = this.levels;
  18488. let l;
  18489. for ( l = 0; l < levels.length; l ++ ) {
  18490. if ( distance < levels[ l ].distance ) {
  18491. break;
  18492. }
  18493. }
  18494. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18495. this.add( object );
  18496. return this;
  18497. }
  18498. /**
  18499. * Removes an existing level, based on the distance from the camera.
  18500. * Returns `true` when the level has been removed. Otherwise `false`.
  18501. *
  18502. * @param {number} distance - Distance of the level to remove.
  18503. * @return {boolean} Whether the level has been removed or not.
  18504. */
  18505. removeLevel( distance ) {
  18506. const levels = this.levels;
  18507. for ( let i = 0; i < levels.length; i ++ ) {
  18508. if ( levels[ i ].distance === distance ) {
  18509. const removedElements = levels.splice( i, 1 );
  18510. this.remove( removedElements[ 0 ].object );
  18511. return true;
  18512. }
  18513. }
  18514. return false;
  18515. }
  18516. /**
  18517. * Returns the currently active LOD level index.
  18518. *
  18519. * @return {number} The current active LOD level index.
  18520. */
  18521. getCurrentLevel() {
  18522. return this._currentLevel;
  18523. }
  18524. /**
  18525. * Returns a reference to the first 3D object that is greater than
  18526. * the given distance.
  18527. *
  18528. * @param {number} distance - The LOD distance.
  18529. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18530. */
  18531. getObjectForDistance( distance ) {
  18532. const levels = this.levels;
  18533. if ( levels.length > 0 ) {
  18534. let i, l;
  18535. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18536. let levelDistance = levels[ i ].distance;
  18537. if ( levels[ i ].object.visible ) {
  18538. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18539. }
  18540. if ( distance < levelDistance ) {
  18541. break;
  18542. }
  18543. }
  18544. return levels[ i - 1 ].object;
  18545. }
  18546. return null;
  18547. }
  18548. /**
  18549. * Computes intersection points between a casted ray and this LOD.
  18550. *
  18551. * @param {Raycaster} raycaster - The raycaster.
  18552. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18553. */
  18554. raycast( raycaster, intersects ) {
  18555. const levels = this.levels;
  18556. if ( levels.length > 0 ) {
  18557. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18558. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18559. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18560. }
  18561. }
  18562. /**
  18563. * Updates the LOD by computing which LOD level should be visible according
  18564. * to the current distance of the given camera.
  18565. *
  18566. * @param {Camera} camera - The camera the scene is rendered with.
  18567. */
  18568. update( camera ) {
  18569. const levels = this.levels;
  18570. if ( levels.length > 1 ) {
  18571. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18572. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18573. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18574. levels[ 0 ].object.visible = true;
  18575. let i, l;
  18576. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18577. let levelDistance = levels[ i ].distance;
  18578. if ( levels[ i ].object.visible ) {
  18579. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18580. }
  18581. if ( distance >= levelDistance ) {
  18582. levels[ i - 1 ].object.visible = false;
  18583. levels[ i ].object.visible = true;
  18584. } else {
  18585. break;
  18586. }
  18587. }
  18588. this._currentLevel = i - 1;
  18589. for ( ; i < l; i ++ ) {
  18590. levels[ i ].object.visible = false;
  18591. }
  18592. }
  18593. }
  18594. toJSON( meta ) {
  18595. const data = super.toJSON( meta );
  18596. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18597. data.object.levels = [];
  18598. const levels = this.levels;
  18599. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18600. const level = levels[ i ];
  18601. data.object.levels.push( {
  18602. object: level.object.uuid,
  18603. distance: level.distance,
  18604. hysteresis: level.hysteresis
  18605. } );
  18606. }
  18607. return data;
  18608. }
  18609. }
  18610. const _basePosition = /*@__PURE__*/ new Vector3();
  18611. const _skinIndex = /*@__PURE__*/ new Vector4();
  18612. const _skinWeight = /*@__PURE__*/ new Vector4();
  18613. const _vector3 = /*@__PURE__*/ new Vector3();
  18614. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18615. const _vertex = /*@__PURE__*/ new Vector3();
  18616. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18617. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18618. const _ray$2 = /*@__PURE__*/ new Ray();
  18619. /**
  18620. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18621. * vertices of the geometry with skinning/skeleton animation.
  18622. *
  18623. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18624. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18625. * vertex to a certain extend.
  18626. *
  18627. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18628. * or {@link FBXLoader } import respective models.
  18629. *
  18630. * @augments Mesh
  18631. * @demo scenes/bones-browser.html
  18632. */
  18633. class SkinnedMesh extends Mesh {
  18634. /**
  18635. * Constructs a new skinned mesh.
  18636. *
  18637. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18638. * @param {Material|Array<Material>} [material] - The mesh material.
  18639. */
  18640. constructor( geometry, material ) {
  18641. super( geometry, material );
  18642. /**
  18643. * This flag can be used for type testing.
  18644. *
  18645. * @type {boolean}
  18646. * @readonly
  18647. * @default true
  18648. */
  18649. this.isSkinnedMesh = true;
  18650. this.type = 'SkinnedMesh';
  18651. /**
  18652. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18653. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18654. * across multiple skinned meshes.
  18655. *
  18656. * @type {(AttachedBindMode|DetachedBindMode)}
  18657. * @default AttachedBindMode
  18658. */
  18659. this.bindMode = AttachedBindMode;
  18660. /**
  18661. * The base matrix that is used for the bound bone transforms.
  18662. *
  18663. * @type {Matrix4}
  18664. */
  18665. this.bindMatrix = new Matrix4();
  18666. /**
  18667. * The base matrix that is used for resetting the bound bone transforms.
  18668. *
  18669. * @type {Matrix4}
  18670. */
  18671. this.bindMatrixInverse = new Matrix4();
  18672. /**
  18673. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18674. *
  18675. * @type {?Box3}
  18676. * @default null
  18677. */
  18678. this.boundingBox = null;
  18679. /**
  18680. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18681. *
  18682. * @type {?Sphere}
  18683. * @default null
  18684. */
  18685. this.boundingSphere = null;
  18686. }
  18687. /**
  18688. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18689. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18690. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18691. * the current animation state.
  18692. */
  18693. computeBoundingBox() {
  18694. const geometry = this.geometry;
  18695. if ( this.boundingBox === null ) {
  18696. this.boundingBox = new Box3();
  18697. }
  18698. this.boundingBox.makeEmpty();
  18699. const positionAttribute = geometry.getAttribute( 'position' );
  18700. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18701. this.getVertexPosition( i, _vertex );
  18702. this.boundingBox.expandByPoint( _vertex );
  18703. }
  18704. }
  18705. /**
  18706. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18707. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18708. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18709. * per frame in order to reflect the current animation state.
  18710. */
  18711. computeBoundingSphere() {
  18712. const geometry = this.geometry;
  18713. if ( this.boundingSphere === null ) {
  18714. this.boundingSphere = new Sphere();
  18715. }
  18716. this.boundingSphere.makeEmpty();
  18717. const positionAttribute = geometry.getAttribute( 'position' );
  18718. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18719. this.getVertexPosition( i, _vertex );
  18720. this.boundingSphere.expandByPoint( _vertex );
  18721. }
  18722. }
  18723. copy( source, recursive ) {
  18724. super.copy( source, recursive );
  18725. this.bindMode = source.bindMode;
  18726. this.bindMatrix.copy( source.bindMatrix );
  18727. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18728. this.skeleton = source.skeleton;
  18729. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18730. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18731. return this;
  18732. }
  18733. raycast( raycaster, intersects ) {
  18734. const material = this.material;
  18735. const matrixWorld = this.matrixWorld;
  18736. if ( material === undefined ) return;
  18737. // test with bounding sphere in world space
  18738. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18739. _sphere$5.copy( this.boundingSphere );
  18740. _sphere$5.applyMatrix4( matrixWorld );
  18741. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18742. // convert ray to local space of skinned mesh
  18743. _inverseMatrix$2.copy( matrixWorld ).invert();
  18744. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18745. // test with bounding box in local space
  18746. if ( this.boundingBox !== null ) {
  18747. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18748. }
  18749. // test for intersections with geometry
  18750. this._computeIntersections( raycaster, intersects, _ray$2 );
  18751. }
  18752. getVertexPosition( index, target ) {
  18753. super.getVertexPosition( index, target );
  18754. this.applyBoneTransform( index, target );
  18755. return target;
  18756. }
  18757. /**
  18758. * Binds the given skeleton to the skinned mesh.
  18759. *
  18760. * @param {Skeleton} skeleton - The skeleton to bind.
  18761. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18762. * the skinned mesh's world matrix will be used instead.
  18763. */
  18764. bind( skeleton, bindMatrix ) {
  18765. this.skeleton = skeleton;
  18766. if ( bindMatrix === undefined ) {
  18767. this.updateMatrixWorld( true );
  18768. this.skeleton.calculateInverses();
  18769. bindMatrix = this.matrixWorld;
  18770. }
  18771. this.bindMatrix.copy( bindMatrix );
  18772. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18773. }
  18774. /**
  18775. * This method sets the skinned mesh in the rest pose).
  18776. */
  18777. pose() {
  18778. this.skeleton.pose();
  18779. }
  18780. /**
  18781. * Normalizes the skin weights which are defined as a buffer attribute
  18782. * in the skinned mesh's geometry.
  18783. */
  18784. normalizeSkinWeights() {
  18785. const vector = new Vector4();
  18786. const skinWeight = this.geometry.attributes.skinWeight;
  18787. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18788. vector.fromBufferAttribute( skinWeight, i );
  18789. const scale = 1.0 / vector.manhattanLength();
  18790. if ( scale !== Infinity ) {
  18791. vector.multiplyScalar( scale );
  18792. } else {
  18793. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18794. }
  18795. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18796. }
  18797. }
  18798. updateMatrixWorld( force ) {
  18799. super.updateMatrixWorld( force );
  18800. if ( this.bindMode === AttachedBindMode ) {
  18801. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18802. } else if ( this.bindMode === DetachedBindMode ) {
  18803. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18804. } else {
  18805. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18806. }
  18807. }
  18808. /**
  18809. * Applies the bone transform associated with the given index to the given
  18810. * vertex position. Returns the updated vector.
  18811. *
  18812. * @param {number} index - The vertex index.
  18813. * @param {Vector3} target - The target object that is used to store the method's result.
  18814. * the skinned mesh's world matrix will be used instead.
  18815. * @return {Vector3} The updated vertex position.
  18816. */
  18817. applyBoneTransform( index, target ) {
  18818. const skeleton = this.skeleton;
  18819. const geometry = this.geometry;
  18820. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18821. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18822. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18823. target.set( 0, 0, 0 );
  18824. for ( let i = 0; i < 4; i ++ ) {
  18825. const weight = _skinWeight.getComponent( i );
  18826. if ( weight !== 0 ) {
  18827. const boneIndex = _skinIndex.getComponent( i );
  18828. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18829. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18830. }
  18831. }
  18832. return target.applyMatrix4( this.bindMatrixInverse );
  18833. }
  18834. }
  18835. /**
  18836. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18837. * the {@link SkinnedMesh}.
  18838. *
  18839. * ```js
  18840. * const root = new THREE.Bone();
  18841. * const child = new THREE.Bone();
  18842. *
  18843. * root.add( child );
  18844. * child.position.y = 5;
  18845. * ```
  18846. *
  18847. * @augments Object3D
  18848. */
  18849. class Bone extends Object3D {
  18850. /**
  18851. * Constructs a new bone.
  18852. */
  18853. constructor() {
  18854. super();
  18855. /**
  18856. * This flag can be used for type testing.
  18857. *
  18858. * @type {boolean}
  18859. * @readonly
  18860. * @default true
  18861. */
  18862. this.isBone = true;
  18863. this.type = 'Bone';
  18864. }
  18865. }
  18866. /**
  18867. * Creates a texture directly from raw buffer data.
  18868. *
  18869. * The interpretation of the data depends on type and format: If the type is
  18870. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18871. * texel data. If the format is `RGBAFormat`, data needs four values for
  18872. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18873. *
  18874. * @augments Texture
  18875. */
  18876. class DataTexture extends Texture {
  18877. /**
  18878. * Constructs a new data texture.
  18879. *
  18880. * @param {?TypedArray} [data=null] - The buffer data.
  18881. * @param {number} [width=1] - The width of the texture.
  18882. * @param {number} [height=1] - The height of the texture.
  18883. * @param {number} [format=RGBAFormat] - The texture format.
  18884. * @param {number} [type=UnsignedByteType] - The texture type.
  18885. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18886. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18887. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18888. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18889. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18890. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18891. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18892. */
  18893. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18894. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18895. /**
  18896. * This flag can be used for type testing.
  18897. *
  18898. * @type {boolean}
  18899. * @readonly
  18900. * @default true
  18901. */
  18902. this.isDataTexture = true;
  18903. /**
  18904. * The image definition of a data texture.
  18905. *
  18906. * @type {{data:TypedArray,width:number,height:number}}
  18907. */
  18908. this.image = { data: data, width: width, height: height };
  18909. /**
  18910. * Whether to generate mipmaps (if possible) for a texture.
  18911. *
  18912. * Overwritten and set to `false` by default.
  18913. *
  18914. * @type {boolean}
  18915. * @default false
  18916. */
  18917. this.generateMipmaps = false;
  18918. /**
  18919. * If set to `true`, the texture is flipped along the vertical axis when
  18920. * uploaded to the GPU.
  18921. *
  18922. * Overwritten and set to `false` by default.
  18923. *
  18924. * @type {boolean}
  18925. * @default false
  18926. */
  18927. this.flipY = false;
  18928. /**
  18929. * Specifies the alignment requirements for the start of each pixel row in memory.
  18930. *
  18931. * Overwritten and set to `1` by default.
  18932. *
  18933. * @type {boolean}
  18934. * @default 1
  18935. */
  18936. this.unpackAlignment = 1;
  18937. }
  18938. }
  18939. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18940. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18941. /**
  18942. * Class for representing the armatures in `three.js`. The skeleton
  18943. * is defined by a hierarchy of bones.
  18944. *
  18945. * ```js
  18946. * const bones = [];
  18947. *
  18948. * const shoulder = new THREE.Bone();
  18949. * const elbow = new THREE.Bone();
  18950. * const hand = new THREE.Bone();
  18951. *
  18952. * shoulder.add( elbow );
  18953. * elbow.add( hand );
  18954. *
  18955. * bones.push( shoulder , elbow, hand);
  18956. *
  18957. * shoulder.position.y = -5;
  18958. * elbow.position.y = 0;
  18959. * hand.position.y = 5;
  18960. *
  18961. * const armSkeleton = new THREE.Skeleton( bones );
  18962. * ```
  18963. */
  18964. class Skeleton {
  18965. /**
  18966. * Constructs a new skeleton.
  18967. *
  18968. * @param {Array<Bone>} [bones] - An array of bones.
  18969. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18970. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18971. */
  18972. constructor( bones = [], boneInverses = [] ) {
  18973. this.uuid = generateUUID();
  18974. /**
  18975. * An array of bones defining the skeleton.
  18976. *
  18977. * @type {Array<Bone>}
  18978. */
  18979. this.bones = bones.slice( 0 );
  18980. /**
  18981. * An array of bone inverse matrices.
  18982. *
  18983. * @type {Array<Matrix4>}
  18984. */
  18985. this.boneInverses = boneInverses;
  18986. /**
  18987. * An array buffer holding the bone data.
  18988. * Input data for {@link Skeleton#boneTexture}.
  18989. *
  18990. * @type {?Float32Array}
  18991. * @default null
  18992. */
  18993. this.boneMatrices = null;
  18994. /**
  18995. * An array buffer holding the bone data of the previous frame.
  18996. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18997. *
  18998. * @type {?Float32Array}
  18999. * @default null
  19000. */
  19001. this.previousBoneMatrices = null;
  19002. /**
  19003. * A texture holding the bone data for use
  19004. * in the vertex shader.
  19005. *
  19006. * @type {?DataTexture}
  19007. * @default null
  19008. */
  19009. this.boneTexture = null;
  19010. this.init();
  19011. }
  19012. /**
  19013. * Initializes the skeleton. This method gets automatically called by the constructor
  19014. * but depending on how the skeleton is created it might be necessary to call this method
  19015. * manually.
  19016. */
  19017. init() {
  19018. const bones = this.bones;
  19019. const boneInverses = this.boneInverses;
  19020. this.boneMatrices = new Float32Array( bones.length * 16 );
  19021. // calculate inverse bone matrices if necessary
  19022. if ( boneInverses.length === 0 ) {
  19023. this.calculateInverses();
  19024. } else {
  19025. // handle special case
  19026. if ( bones.length !== boneInverses.length ) {
  19027. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  19028. this.boneInverses = [];
  19029. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19030. this.boneInverses.push( new Matrix4() );
  19031. }
  19032. }
  19033. }
  19034. }
  19035. /**
  19036. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  19037. * and fills it with new matrices.
  19038. */
  19039. calculateInverses() {
  19040. this.boneInverses.length = 0;
  19041. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19042. const inverse = new Matrix4();
  19043. if ( this.bones[ i ] ) {
  19044. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  19045. }
  19046. this.boneInverses.push( inverse );
  19047. }
  19048. }
  19049. /**
  19050. * Resets the skeleton to the base pose.
  19051. */
  19052. pose() {
  19053. // recover the bind-time world matrices
  19054. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19055. const bone = this.bones[ i ];
  19056. if ( bone ) {
  19057. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  19058. }
  19059. }
  19060. // compute the local matrices, positions, rotations and scales
  19061. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19062. const bone = this.bones[ i ];
  19063. if ( bone ) {
  19064. if ( bone.parent && bone.parent.isBone ) {
  19065. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  19066. bone.matrix.multiply( bone.matrixWorld );
  19067. } else {
  19068. bone.matrix.copy( bone.matrixWorld );
  19069. }
  19070. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  19071. }
  19072. }
  19073. }
  19074. /**
  19075. * Resets the skeleton to the base pose.
  19076. */
  19077. update() {
  19078. const bones = this.bones;
  19079. const boneInverses = this.boneInverses;
  19080. const boneMatrices = this.boneMatrices;
  19081. const boneTexture = this.boneTexture;
  19082. // flatten bone matrices to array
  19083. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  19084. // compute the offset between the current and the original transform
  19085. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  19086. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  19087. _offsetMatrix.toArray( boneMatrices, i * 16 );
  19088. }
  19089. if ( boneTexture !== null ) {
  19090. boneTexture.needsUpdate = true;
  19091. }
  19092. }
  19093. /**
  19094. * Returns a new skeleton with copied values from this instance.
  19095. *
  19096. * @return {Skeleton} A clone of this instance.
  19097. */
  19098. clone() {
  19099. return new Skeleton( this.bones, this.boneInverses );
  19100. }
  19101. /**
  19102. * Computes a data texture for passing bone data to the vertex shader.
  19103. *
  19104. * @return {Skeleton} A reference of this instance.
  19105. */
  19106. computeBoneTexture() {
  19107. // layout (1 matrix = 4 pixels)
  19108. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  19109. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  19110. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  19111. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  19112. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  19113. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  19114. size = Math.ceil( size / 4 ) * 4;
  19115. size = Math.max( size, 4 );
  19116. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  19117. boneMatrices.set( this.boneMatrices ); // copy current values
  19118. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  19119. boneTexture.needsUpdate = true;
  19120. this.boneMatrices = boneMatrices;
  19121. this.boneTexture = boneTexture;
  19122. return this;
  19123. }
  19124. /**
  19125. * Searches through the skeleton's bone array and returns the first with a
  19126. * matching name.
  19127. *
  19128. * @param {string} name - The name of the bone.
  19129. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  19130. */
  19131. getBoneByName( name ) {
  19132. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  19133. const bone = this.bones[ i ];
  19134. if ( bone.name === name ) {
  19135. return bone;
  19136. }
  19137. }
  19138. return undefined;
  19139. }
  19140. /**
  19141. * Frees the GPU-related resources allocated by this instance. Call this
  19142. * method whenever this instance is no longer used in your app.
  19143. */
  19144. dispose( ) {
  19145. if ( this.boneTexture !== null ) {
  19146. this.boneTexture.dispose();
  19147. this.boneTexture = null;
  19148. }
  19149. }
  19150. /**
  19151. * Setups the skeleton by the given JSON and bones.
  19152. *
  19153. * @param {Object} json - The skeleton as serialized JSON.
  19154. * @param {Object<string, Bone>} bones - An array of bones.
  19155. * @return {Skeleton} A reference of this instance.
  19156. */
  19157. fromJSON( json, bones ) {
  19158. this.uuid = json.uuid;
  19159. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  19160. const uuid = json.bones[ i ];
  19161. let bone = bones[ uuid ];
  19162. if ( bone === undefined ) {
  19163. warn( 'Skeleton: No bone found with UUID:', uuid );
  19164. bone = new Bone();
  19165. }
  19166. this.bones.push( bone );
  19167. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  19168. }
  19169. this.init();
  19170. return this;
  19171. }
  19172. /**
  19173. * Serializes the skeleton into JSON.
  19174. *
  19175. * @return {Object} A JSON object representing the serialized skeleton.
  19176. * @see {@link ObjectLoader#parse}
  19177. */
  19178. toJSON() {
  19179. const data = {
  19180. metadata: {
  19181. version: 4.7,
  19182. type: 'Skeleton',
  19183. generator: 'Skeleton.toJSON'
  19184. },
  19185. bones: [],
  19186. boneInverses: []
  19187. };
  19188. data.uuid = this.uuid;
  19189. const bones = this.bones;
  19190. const boneInverses = this.boneInverses;
  19191. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  19192. const bone = bones[ i ];
  19193. data.bones.push( bone.uuid );
  19194. const boneInverse = boneInverses[ i ];
  19195. data.boneInverses.push( boneInverse.toArray() );
  19196. }
  19197. return data;
  19198. }
  19199. }
  19200. /**
  19201. * An instanced version of a buffer attribute.
  19202. *
  19203. * @augments BufferAttribute
  19204. */
  19205. class InstancedBufferAttribute extends BufferAttribute {
  19206. /**
  19207. * Constructs a new instanced buffer attribute.
  19208. *
  19209. * @param {TypedArray} array - The array holding the attribute data.
  19210. * @param {number} itemSize - The item size.
  19211. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19212. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19213. */
  19214. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19215. super( array, itemSize, normalized );
  19216. /**
  19217. * This flag can be used for type testing.
  19218. *
  19219. * @type {boolean}
  19220. * @readonly
  19221. * @default true
  19222. */
  19223. this.isInstancedBufferAttribute = true;
  19224. /**
  19225. * Defines how often a value of this buffer attribute should be repeated. A
  19226. * value of one means that each value of the instanced attribute is used for
  19227. * a single instance. A value of two means that each value is used for two
  19228. * consecutive instances (and so on).
  19229. *
  19230. * @type {number}
  19231. * @default 1
  19232. */
  19233. this.meshPerAttribute = meshPerAttribute;
  19234. }
  19235. copy( source ) {
  19236. super.copy( source );
  19237. this.meshPerAttribute = source.meshPerAttribute;
  19238. return this;
  19239. }
  19240. toJSON() {
  19241. const data = super.toJSON();
  19242. data.meshPerAttribute = this.meshPerAttribute;
  19243. data.isInstancedBufferAttribute = true;
  19244. return data;
  19245. }
  19246. }
  19247. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19248. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19249. const _instanceIntersects = [];
  19250. const _box3 = /*@__PURE__*/ new Box3();
  19251. const _identity = /*@__PURE__*/ new Matrix4();
  19252. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19253. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19254. /**
  19255. * A special version of a mesh with instanced rendering support. Use
  19256. * this class if you have to render a large number of objects with the same
  19257. * geometry and material(s) but with different world transformations. The usage
  19258. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19259. * improve the overall rendering performance in your application.
  19260. *
  19261. * @augments Mesh
  19262. */
  19263. class InstancedMesh extends Mesh {
  19264. /**
  19265. * Constructs a new instanced mesh.
  19266. *
  19267. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19268. * @param {Material|Array<Material>} [material] - The mesh material.
  19269. * @param {number} count - The number of instances.
  19270. */
  19271. constructor( geometry, material, count ) {
  19272. super( geometry, material );
  19273. /**
  19274. * This flag can be used for type testing.
  19275. *
  19276. * @type {boolean}
  19277. * @readonly
  19278. * @default true
  19279. */
  19280. this.isInstancedMesh = true;
  19281. /**
  19282. * Represents the local transformation of all instances. You have to set its
  19283. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19284. * via {@link InstancedMesh#setMatrixAt}.
  19285. *
  19286. * @type {InstancedBufferAttribute}
  19287. */
  19288. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19289. /**
  19290. * Represents the local transformation of all instances of the previous frame.
  19291. * Required for computing velocity. Maintained in {@link InstanceNode}.
  19292. *
  19293. * @type {?InstancedBufferAttribute}
  19294. * @default null
  19295. */
  19296. this.previousInstanceMatrix = null;
  19297. /**
  19298. * Represents the color of all instances. You have to set its
  19299. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19300. * via {@link InstancedMesh#setColorAt}.
  19301. *
  19302. * @type {?InstancedBufferAttribute}
  19303. * @default null
  19304. */
  19305. this.instanceColor = null;
  19306. /**
  19307. * Represents the morph target weights of all instances. You have to set its
  19308. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19309. * via {@link InstancedMesh#setMorphAt}.
  19310. *
  19311. * @type {?DataTexture}
  19312. * @default null
  19313. */
  19314. this.morphTexture = null;
  19315. /**
  19316. * The number of instances.
  19317. *
  19318. * @type {number}
  19319. */
  19320. this.count = count;
  19321. /**
  19322. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19323. *
  19324. * @type {?Box3}
  19325. * @default null
  19326. */
  19327. this.boundingBox = null;
  19328. /**
  19329. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19330. *
  19331. * @type {?Sphere}
  19332. * @default null
  19333. */
  19334. this.boundingSphere = null;
  19335. for ( let i = 0; i < count; i ++ ) {
  19336. this.setMatrixAt( i, _identity );
  19337. }
  19338. }
  19339. /**
  19340. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19341. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19342. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19343. */
  19344. computeBoundingBox() {
  19345. const geometry = this.geometry;
  19346. const count = this.count;
  19347. if ( this.boundingBox === null ) {
  19348. this.boundingBox = new Box3();
  19349. }
  19350. if ( geometry.boundingBox === null ) {
  19351. geometry.computeBoundingBox();
  19352. }
  19353. this.boundingBox.makeEmpty();
  19354. for ( let i = 0; i < count; i ++ ) {
  19355. this.getMatrixAt( i, _instanceLocalMatrix );
  19356. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19357. this.boundingBox.union( _box3 );
  19358. }
  19359. }
  19360. /**
  19361. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19362. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19363. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19364. */
  19365. computeBoundingSphere() {
  19366. const geometry = this.geometry;
  19367. const count = this.count;
  19368. if ( this.boundingSphere === null ) {
  19369. this.boundingSphere = new Sphere();
  19370. }
  19371. if ( geometry.boundingSphere === null ) {
  19372. geometry.computeBoundingSphere();
  19373. }
  19374. this.boundingSphere.makeEmpty();
  19375. for ( let i = 0; i < count; i ++ ) {
  19376. this.getMatrixAt( i, _instanceLocalMatrix );
  19377. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19378. this.boundingSphere.union( _sphere$4 );
  19379. }
  19380. }
  19381. copy( source, recursive ) {
  19382. super.copy( source, recursive );
  19383. this.instanceMatrix.copy( source.instanceMatrix );
  19384. if ( source.previousInstanceMatrix !== null ) this.previousInstanceMatrix = source.previousInstanceMatrix.clone();
  19385. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19386. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19387. this.count = source.count;
  19388. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19389. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19390. return this;
  19391. }
  19392. /**
  19393. * Gets the color of the defined instance.
  19394. *
  19395. * @param {number} index - The instance index.
  19396. * @param {Color} color - The target object that is used to store the method's result.
  19397. */
  19398. getColorAt( index, color ) {
  19399. color.fromArray( this.instanceColor.array, index * 3 );
  19400. }
  19401. /**
  19402. * Gets the local transformation matrix of the defined instance.
  19403. *
  19404. * @param {number} index - The instance index.
  19405. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19406. */
  19407. getMatrixAt( index, matrix ) {
  19408. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19409. }
  19410. /**
  19411. * Gets the morph target weights of the defined instance.
  19412. *
  19413. * @param {number} index - The instance index.
  19414. * @param {Mesh} object - The target object that is used to store the method's result.
  19415. */
  19416. getMorphAt( index, object ) {
  19417. const objectInfluences = object.morphTargetInfluences;
  19418. const array = this.morphTexture.source.data.data;
  19419. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19420. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19421. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19422. objectInfluences[ i ] = array[ dataIndex + i ];
  19423. }
  19424. }
  19425. raycast( raycaster, intersects ) {
  19426. const matrixWorld = this.matrixWorld;
  19427. const raycastTimes = this.count;
  19428. _mesh$1.geometry = this.geometry;
  19429. _mesh$1.material = this.material;
  19430. if ( _mesh$1.material === undefined ) return;
  19431. // test with bounding sphere first
  19432. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19433. _sphere$4.copy( this.boundingSphere );
  19434. _sphere$4.applyMatrix4( matrixWorld );
  19435. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19436. // now test each instance
  19437. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19438. // calculate the world matrix for each instance
  19439. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19440. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19441. // the mesh represents this single instance
  19442. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19443. _mesh$1.raycast( raycaster, _instanceIntersects );
  19444. // process the result of raycast
  19445. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19446. const intersect = _instanceIntersects[ i ];
  19447. intersect.instanceId = instanceId;
  19448. intersect.object = this;
  19449. intersects.push( intersect );
  19450. }
  19451. _instanceIntersects.length = 0;
  19452. }
  19453. }
  19454. /**
  19455. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19456. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19457. *
  19458. * @param {number} index - The instance index.
  19459. * @param {Color} color - The instance color.
  19460. */
  19461. setColorAt( index, color ) {
  19462. if ( this.instanceColor === null ) {
  19463. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19464. }
  19465. color.toArray( this.instanceColor.array, index * 3 );
  19466. }
  19467. /**
  19468. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19469. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19470. *
  19471. * @param {number} index - The instance index.
  19472. * @param {Matrix4} matrix - The local transformation.
  19473. */
  19474. setMatrixAt( index, matrix ) {
  19475. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19476. }
  19477. /**
  19478. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19479. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19480. *
  19481. * @param {number} index - The instance index.
  19482. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19483. * of a single instance.
  19484. */
  19485. setMorphAt( index, object ) {
  19486. const objectInfluences = object.morphTargetInfluences;
  19487. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19488. if ( this.morphTexture === null ) {
  19489. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19490. }
  19491. const array = this.morphTexture.source.data.data;
  19492. let morphInfluencesSum = 0;
  19493. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19494. morphInfluencesSum += objectInfluences[ i ];
  19495. }
  19496. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19497. const dataIndex = len * index;
  19498. array[ dataIndex ] = morphBaseInfluence;
  19499. array.set( objectInfluences, dataIndex + 1 );
  19500. }
  19501. updateMorphTargets() {
  19502. }
  19503. /**
  19504. * Frees the GPU-related resources allocated by this instance. Call this
  19505. * method whenever this instance is no longer used in your app.
  19506. */
  19507. dispose() {
  19508. this.dispatchEvent( { type: 'dispose' } );
  19509. if ( this.morphTexture !== null ) {
  19510. this.morphTexture.dispose();
  19511. this.morphTexture = null;
  19512. }
  19513. }
  19514. }
  19515. const _vector1 = /*@__PURE__*/ new Vector3();
  19516. const _vector2 = /*@__PURE__*/ new Vector3();
  19517. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19518. /**
  19519. * A two dimensional surface that extends infinitely in 3D space, represented
  19520. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19521. * by a unit length normal vector and a constant.
  19522. */
  19523. class Plane {
  19524. /**
  19525. * Constructs a new plane.
  19526. *
  19527. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19528. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19529. */
  19530. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19531. /**
  19532. * This flag can be used for type testing.
  19533. *
  19534. * @type {boolean}
  19535. * @readonly
  19536. * @default true
  19537. */
  19538. this.isPlane = true;
  19539. /**
  19540. * A unit length vector defining the normal of the plane.
  19541. *
  19542. * @type {Vector3}
  19543. */
  19544. this.normal = normal;
  19545. /**
  19546. * The signed distance from the origin to the plane.
  19547. *
  19548. * @type {number}
  19549. * @default 0
  19550. */
  19551. this.constant = constant;
  19552. }
  19553. /**
  19554. * Sets the plane components by copying the given values.
  19555. *
  19556. * @param {Vector3} normal - The normal.
  19557. * @param {number} constant - The constant.
  19558. * @return {Plane} A reference to this plane.
  19559. */
  19560. set( normal, constant ) {
  19561. this.normal.copy( normal );
  19562. this.constant = constant;
  19563. return this;
  19564. }
  19565. /**
  19566. * Sets the plane components by defining `x`, `y`, `z` as the
  19567. * plane normal and `w` as the constant.
  19568. *
  19569. * @param {number} x - The value for the normal's x component.
  19570. * @param {number} y - The value for the normal's y component.
  19571. * @param {number} z - The value for the normal's z component.
  19572. * @param {number} w - The constant value.
  19573. * @return {Plane} A reference to this plane.
  19574. */
  19575. setComponents( x, y, z, w ) {
  19576. this.normal.set( x, y, z );
  19577. this.constant = w;
  19578. return this;
  19579. }
  19580. /**
  19581. * Sets the plane from the given normal and coplanar point (that is a point
  19582. * that lies onto the plane).
  19583. *
  19584. * @param {Vector3} normal - The normal.
  19585. * @param {Vector3} point - A coplanar point.
  19586. * @return {Plane} A reference to this plane.
  19587. */
  19588. setFromNormalAndCoplanarPoint( normal, point ) {
  19589. this.normal.copy( normal );
  19590. this.constant = - point.dot( this.normal );
  19591. return this;
  19592. }
  19593. /**
  19594. * Sets the plane from three coplanar points. The winding order is
  19595. * assumed to be counter-clockwise, and determines the direction of
  19596. * the plane normal.
  19597. *
  19598. * @param {Vector3} a - The first coplanar point.
  19599. * @param {Vector3} b - The second coplanar point.
  19600. * @param {Vector3} c - The third coplanar point.
  19601. * @return {Plane} A reference to this plane.
  19602. */
  19603. setFromCoplanarPoints( a, b, c ) {
  19604. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19605. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19606. this.setFromNormalAndCoplanarPoint( normal, a );
  19607. return this;
  19608. }
  19609. /**
  19610. * Copies the values of the given plane to this instance.
  19611. *
  19612. * @param {Plane} plane - The plane to copy.
  19613. * @return {Plane} A reference to this plane.
  19614. */
  19615. copy( plane ) {
  19616. this.normal.copy( plane.normal );
  19617. this.constant = plane.constant;
  19618. return this;
  19619. }
  19620. /**
  19621. * Normalizes the plane normal and adjusts the constant accordingly.
  19622. *
  19623. * @return {Plane} A reference to this plane.
  19624. */
  19625. normalize() {
  19626. // Note: will lead to a divide by zero if the plane is invalid.
  19627. const inverseNormalLength = 1.0 / this.normal.length();
  19628. this.normal.multiplyScalar( inverseNormalLength );
  19629. this.constant *= inverseNormalLength;
  19630. return this;
  19631. }
  19632. /**
  19633. * Negates both the plane normal and the constant.
  19634. *
  19635. * @return {Plane} A reference to this plane.
  19636. */
  19637. negate() {
  19638. this.constant *= -1;
  19639. this.normal.negate();
  19640. return this;
  19641. }
  19642. /**
  19643. * Returns the signed distance from the given point to this plane.
  19644. *
  19645. * @param {Vector3} point - The point to compute the distance for.
  19646. * @return {number} The signed distance.
  19647. */
  19648. distanceToPoint( point ) {
  19649. return this.normal.dot( point ) + this.constant;
  19650. }
  19651. /**
  19652. * Returns the signed distance from the given sphere to this plane.
  19653. *
  19654. * @param {Sphere} sphere - The sphere to compute the distance for.
  19655. * @return {number} The signed distance.
  19656. */
  19657. distanceToSphere( sphere ) {
  19658. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19659. }
  19660. /**
  19661. * Projects a the given point onto the plane.
  19662. *
  19663. * @param {Vector3} point - The point to project.
  19664. * @param {Vector3} target - The target vector that is used to store the method's result.
  19665. * @return {Vector3} The projected point on the plane.
  19666. */
  19667. projectPoint( point, target ) {
  19668. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19669. }
  19670. /**
  19671. * Returns the intersection point of the passed line and the plane. Returns
  19672. * `null` if the line does not intersect. Returns the line's starting point if
  19673. * the line is coplanar with the plane.
  19674. *
  19675. * @param {Line3} line - The line to compute the intersection for.
  19676. * @param {Vector3} target - The target vector that is used to store the method's result.
  19677. * @return {?Vector3} The intersection point.
  19678. */
  19679. intersectLine( line, target ) {
  19680. const direction = line.delta( _vector1 );
  19681. const denominator = this.normal.dot( direction );
  19682. if ( denominator === 0 ) {
  19683. // line is coplanar, return origin
  19684. if ( this.distanceToPoint( line.start ) === 0 ) {
  19685. return target.copy( line.start );
  19686. }
  19687. // Unsure if this is the correct method to handle this case.
  19688. return null;
  19689. }
  19690. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19691. if ( t < 0 || t > 1 ) {
  19692. return null;
  19693. }
  19694. return target.copy( line.start ).addScaledVector( direction, t );
  19695. }
  19696. /**
  19697. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19698. *
  19699. * @param {Line3} line - The line to test.
  19700. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19701. */
  19702. intersectsLine( line ) {
  19703. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19704. const startSign = this.distanceToPoint( line.start );
  19705. const endSign = this.distanceToPoint( line.end );
  19706. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19707. }
  19708. /**
  19709. * Returns `true` if the given bounding box intersects with the plane.
  19710. *
  19711. * @param {Box3} box - The bounding box to test.
  19712. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19713. */
  19714. intersectsBox( box ) {
  19715. return box.intersectsPlane( this );
  19716. }
  19717. /**
  19718. * Returns `true` if the given bounding sphere intersects with the plane.
  19719. *
  19720. * @param {Sphere} sphere - The bounding sphere to test.
  19721. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19722. */
  19723. intersectsSphere( sphere ) {
  19724. return sphere.intersectsPlane( this );
  19725. }
  19726. /**
  19727. * Returns a coplanar vector to the plane, by calculating the
  19728. * projection of the normal at the origin onto the plane.
  19729. *
  19730. * @param {Vector3} target - The target vector that is used to store the method's result.
  19731. * @return {Vector3} The coplanar point.
  19732. */
  19733. coplanarPoint( target ) {
  19734. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19735. }
  19736. /**
  19737. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19738. *
  19739. * The optional normal matrix can be pre-computed like so:
  19740. * ```js
  19741. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19742. * ```
  19743. *
  19744. * @param {Matrix4} matrix - The transformation matrix.
  19745. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19746. * @return {Plane} A reference to this plane.
  19747. */
  19748. applyMatrix4( matrix, optionalNormalMatrix ) {
  19749. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19750. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19751. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19752. this.constant = - referencePoint.dot( normal );
  19753. return this;
  19754. }
  19755. /**
  19756. * Translates the plane by the distance defined by the given offset vector.
  19757. * Note that this only affects the plane constant and will not affect the normal vector.
  19758. *
  19759. * @param {Vector3} offset - The offset vector.
  19760. * @return {Plane} A reference to this plane.
  19761. */
  19762. translate( offset ) {
  19763. this.constant -= offset.dot( this.normal );
  19764. return this;
  19765. }
  19766. /**
  19767. * Returns `true` if this plane is equal with the given one.
  19768. *
  19769. * @param {Plane} plane - The plane to test for equality.
  19770. * @return {boolean} Whether this plane is equal with the given one.
  19771. */
  19772. equals( plane ) {
  19773. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19774. }
  19775. /**
  19776. * Returns a new plane with copied values from this instance.
  19777. *
  19778. * @return {Plane} A clone of this instance.
  19779. */
  19780. clone() {
  19781. return new this.constructor().copy( this );
  19782. }
  19783. }
  19784. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19785. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19786. const _vector$6 = /*@__PURE__*/ new Vector3();
  19787. /**
  19788. * Frustums are used to determine what is inside the camera's field of view.
  19789. * They help speed up the rendering process - objects which lie outside a camera's
  19790. * frustum can safely be excluded from rendering.
  19791. *
  19792. * This class is mainly intended for use internally by a renderer.
  19793. */
  19794. class Frustum {
  19795. /**
  19796. * Constructs a new frustum.
  19797. *
  19798. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19799. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19800. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19801. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19802. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19803. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19804. */
  19805. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19806. /**
  19807. * This array holds the planes that enclose the frustum.
  19808. *
  19809. * @type {Array<Plane>}
  19810. */
  19811. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19812. }
  19813. /**
  19814. * Sets the frustum planes by copying the given planes.
  19815. *
  19816. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19817. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19818. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19819. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19820. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19821. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19822. * @return {Frustum} A reference to this frustum.
  19823. */
  19824. set( p0, p1, p2, p3, p4, p5 ) {
  19825. const planes = this.planes;
  19826. planes[ 0 ].copy( p0 );
  19827. planes[ 1 ].copy( p1 );
  19828. planes[ 2 ].copy( p2 );
  19829. planes[ 3 ].copy( p3 );
  19830. planes[ 4 ].copy( p4 );
  19831. planes[ 5 ].copy( p5 );
  19832. return this;
  19833. }
  19834. /**
  19835. * Copies the values of the given frustum to this instance.
  19836. *
  19837. * @param {Frustum} frustum - The frustum to copy.
  19838. * @return {Frustum} A reference to this frustum.
  19839. */
  19840. copy( frustum ) {
  19841. const planes = this.planes;
  19842. for ( let i = 0; i < 6; i ++ ) {
  19843. planes[ i ].copy( frustum.planes[ i ] );
  19844. }
  19845. return this;
  19846. }
  19847. /**
  19848. * Sets the frustum planes from the given projection matrix.
  19849. *
  19850. * @param {Matrix4} m - The projection matrix.
  19851. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19852. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19853. * @return {Frustum} A reference to this frustum.
  19854. */
  19855. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19856. const planes = this.planes;
  19857. const me = m.elements;
  19858. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19859. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19860. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19861. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19862. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19863. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19864. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19865. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19866. if ( reversedDepth ) {
  19867. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19868. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19869. } else {
  19870. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19871. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19872. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19873. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19874. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19875. } else {
  19876. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19877. }
  19878. }
  19879. return this;
  19880. }
  19881. /**
  19882. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19883. *
  19884. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19885. *
  19886. * @param {Object3D} object - The 3D object to test.
  19887. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19888. */
  19889. intersectsObject( object ) {
  19890. if ( object.boundingSphere !== undefined ) {
  19891. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19892. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19893. } else {
  19894. const geometry = object.geometry;
  19895. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19896. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19897. }
  19898. return this.intersectsSphere( _sphere$3 );
  19899. }
  19900. /**
  19901. * Returns `true` if the given sprite is intersecting this frustum.
  19902. *
  19903. * @param {Sprite} sprite - The sprite to test.
  19904. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19905. */
  19906. intersectsSprite( sprite ) {
  19907. _sphere$3.center.set( 0, 0, 0 );
  19908. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19909. _sphere$3.radius = 0.7071067811865476 + offset;
  19910. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19911. return this.intersectsSphere( _sphere$3 );
  19912. }
  19913. /**
  19914. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19915. *
  19916. * @param {Sphere} sphere - The bounding sphere to test.
  19917. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19918. */
  19919. intersectsSphere( sphere ) {
  19920. const planes = this.planes;
  19921. const center = sphere.center;
  19922. const negRadius = - sphere.radius;
  19923. for ( let i = 0; i < 6; i ++ ) {
  19924. const distance = planes[ i ].distanceToPoint( center );
  19925. if ( distance < negRadius ) {
  19926. return false;
  19927. }
  19928. }
  19929. return true;
  19930. }
  19931. /**
  19932. * Returns `true` if the given bounding box is intersecting this frustum.
  19933. *
  19934. * @param {Box3} box - The bounding box to test.
  19935. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19936. */
  19937. intersectsBox( box ) {
  19938. const planes = this.planes;
  19939. for ( let i = 0; i < 6; i ++ ) {
  19940. const plane = planes[ i ];
  19941. // corner at max distance
  19942. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19943. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19944. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19945. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19946. return false;
  19947. }
  19948. }
  19949. return true;
  19950. }
  19951. /**
  19952. * Returns `true` if the given point lies within the frustum.
  19953. *
  19954. * @param {Vector3} point - The point to test.
  19955. * @return {boolean} Whether the point lies within this frustum or not.
  19956. */
  19957. containsPoint( point ) {
  19958. const planes = this.planes;
  19959. for ( let i = 0; i < 6; i ++ ) {
  19960. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19961. return false;
  19962. }
  19963. }
  19964. return true;
  19965. }
  19966. /**
  19967. * Returns a new frustum with copied values from this instance.
  19968. *
  19969. * @return {Frustum} A clone of this instance.
  19970. */
  19971. clone() {
  19972. return new this.constructor().copy( this );
  19973. }
  19974. }
  19975. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19976. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19977. /**
  19978. * FrustumArray is used to determine if an object is visible in at least one camera
  19979. * from an array of cameras. This is particularly useful for multi-view renderers.
  19980. */
  19981. class FrustumArray {
  19982. /**
  19983. * Constructs a new frustum array.
  19984. *
  19985. */
  19986. constructor() {
  19987. /**
  19988. * The coordinate system to use.
  19989. *
  19990. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19991. * @default WebGLCoordinateSystem
  19992. */
  19993. this.coordinateSystem = WebGLCoordinateSystem;
  19994. }
  19995. /**
  19996. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19997. * from the camera array.
  19998. *
  19999. * @param {Object3D} object - The 3D object to test.
  20000. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20001. * @return {boolean} Whether the 3D object is visible in any camera.
  20002. */
  20003. intersectsObject( object, cameraArray ) {
  20004. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  20005. return false;
  20006. }
  20007. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20008. const camera = cameraArray.cameras[ i ];
  20009. _projScreenMatrix$2.multiplyMatrices(
  20010. camera.projectionMatrix,
  20011. camera.matrixWorldInverse
  20012. );
  20013. _frustum$1.setFromProjectionMatrix(
  20014. _projScreenMatrix$2,
  20015. camera.coordinateSystem,
  20016. camera.reversedDepth
  20017. );
  20018. if ( _frustum$1.intersectsObject( object ) ) {
  20019. return true; // Object is visible in at least one camera
  20020. }
  20021. }
  20022. return false; // Not visible in any camera
  20023. }
  20024. /**
  20025. * Returns `true` if the given sprite is intersecting any frustum
  20026. * from the camera array.
  20027. *
  20028. * @param {Sprite} sprite - The sprite to test.
  20029. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20030. * @return {boolean} Whether the sprite is visible in any camera.
  20031. */
  20032. intersectsSprite( sprite, cameraArray ) {
  20033. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20034. return false;
  20035. }
  20036. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20037. const camera = cameraArray.cameras[ i ];
  20038. _projScreenMatrix$2.multiplyMatrices(
  20039. camera.projectionMatrix,
  20040. camera.matrixWorldInverse
  20041. );
  20042. _frustum$1.setFromProjectionMatrix(
  20043. _projScreenMatrix$2,
  20044. camera.coordinateSystem,
  20045. camera.reversedDepth
  20046. );
  20047. if ( _frustum$1.intersectsSprite( sprite ) ) {
  20048. return true; // Sprite is visible in at least one camera
  20049. }
  20050. }
  20051. return false; // Not visible in any camera
  20052. }
  20053. /**
  20054. * Returns `true` if the given bounding sphere is intersecting any frustum
  20055. * from the camera array.
  20056. *
  20057. * @param {Sphere} sphere - The bounding sphere to test.
  20058. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20059. * @return {boolean} Whether the sphere is visible in any camera.
  20060. */
  20061. intersectsSphere( sphere, cameraArray ) {
  20062. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20063. return false;
  20064. }
  20065. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20066. const camera = cameraArray.cameras[ i ];
  20067. _projScreenMatrix$2.multiplyMatrices(
  20068. camera.projectionMatrix,
  20069. camera.matrixWorldInverse
  20070. );
  20071. _frustum$1.setFromProjectionMatrix(
  20072. _projScreenMatrix$2,
  20073. camera.coordinateSystem,
  20074. camera.reversedDepth
  20075. );
  20076. if ( _frustum$1.intersectsSphere( sphere ) ) {
  20077. return true; // Sphere is visible in at least one camera
  20078. }
  20079. }
  20080. return false; // Not visible in any camera
  20081. }
  20082. /**
  20083. * Returns `true` if the given bounding box is intersecting any frustum
  20084. * from the camera array.
  20085. *
  20086. * @param {Box3} box - The bounding box to test.
  20087. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20088. * @return {boolean} Whether the box is visible in any camera.
  20089. */
  20090. intersectsBox( box, cameraArray ) {
  20091. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20092. return false;
  20093. }
  20094. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20095. const camera = cameraArray.cameras[ i ];
  20096. _projScreenMatrix$2.multiplyMatrices(
  20097. camera.projectionMatrix,
  20098. camera.matrixWorldInverse
  20099. );
  20100. _frustum$1.setFromProjectionMatrix(
  20101. _projScreenMatrix$2,
  20102. camera.coordinateSystem,
  20103. camera.reversedDepth
  20104. );
  20105. if ( _frustum$1.intersectsBox( box ) ) {
  20106. return true; // Box is visible in at least one camera
  20107. }
  20108. }
  20109. return false; // Not visible in any camera
  20110. }
  20111. /**
  20112. * Returns `true` if the given point lies within any frustum
  20113. * from the camera array.
  20114. *
  20115. * @param {Vector3} point - The point to test.
  20116. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  20117. * @return {boolean} Whether the point is visible in any camera.
  20118. */
  20119. containsPoint( point, cameraArray ) {
  20120. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  20121. return false;
  20122. }
  20123. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  20124. const camera = cameraArray.cameras[ i ];
  20125. _projScreenMatrix$2.multiplyMatrices(
  20126. camera.projectionMatrix,
  20127. camera.matrixWorldInverse
  20128. );
  20129. _frustum$1.setFromProjectionMatrix(
  20130. _projScreenMatrix$2,
  20131. camera.coordinateSystem,
  20132. camera.reversedDepth
  20133. );
  20134. if ( _frustum$1.containsPoint( point ) ) {
  20135. return true; // Point is visible in at least one camera
  20136. }
  20137. }
  20138. return false; // Not visible in any camera
  20139. }
  20140. /**
  20141. * Returns a new frustum array with copied values from this instance.
  20142. *
  20143. * @return {FrustumArray} A clone of this instance.
  20144. */
  20145. clone() {
  20146. return new FrustumArray();
  20147. }
  20148. }
  20149. function ascIdSort( a, b ) {
  20150. return a - b;
  20151. }
  20152. function sortOpaque( a, b ) {
  20153. return a.z - b.z;
  20154. }
  20155. function sortTransparent( a, b ) {
  20156. return b.z - a.z;
  20157. }
  20158. class MultiDrawRenderList {
  20159. constructor() {
  20160. this.index = 0;
  20161. this.pool = [];
  20162. this.list = [];
  20163. }
  20164. push( start, count, z, index ) {
  20165. const pool = this.pool;
  20166. const list = this.list;
  20167. if ( this.index >= pool.length ) {
  20168. pool.push( {
  20169. start: -1,
  20170. count: -1,
  20171. z: -1,
  20172. index: -1,
  20173. } );
  20174. }
  20175. const item = pool[ this.index ];
  20176. list.push( item );
  20177. this.index ++;
  20178. item.start = start;
  20179. item.count = count;
  20180. item.z = z;
  20181. item.index = index;
  20182. }
  20183. reset() {
  20184. this.list.length = 0;
  20185. this.index = 0;
  20186. }
  20187. }
  20188. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  20189. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  20190. const _frustum = /*@__PURE__*/ new Frustum();
  20191. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  20192. const _box$1 = /*@__PURE__*/ new Box3();
  20193. const _sphere$2 = /*@__PURE__*/ new Sphere();
  20194. const _vector$5 = /*@__PURE__*/ new Vector3();
  20195. const _forward$1 = /*@__PURE__*/ new Vector3();
  20196. const _temp = /*@__PURE__*/ new Vector3();
  20197. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  20198. const _mesh = /*@__PURE__*/ new Mesh();
  20199. const _batchIntersects = [];
  20200. // copies data from attribute "src" into "target" starting at "targetOffset"
  20201. function copyAttributeData( src, target, targetOffset = 0 ) {
  20202. const itemSize = target.itemSize;
  20203. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20204. // use the component getters and setters if the array data cannot
  20205. // be copied directly
  20206. const vertexCount = src.count;
  20207. for ( let i = 0; i < vertexCount; i ++ ) {
  20208. for ( let c = 0; c < itemSize; c ++ ) {
  20209. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20210. }
  20211. }
  20212. } else {
  20213. // faster copy approach using typed array set function
  20214. target.array.set( src.array, targetOffset * itemSize );
  20215. }
  20216. target.needsUpdate = true;
  20217. }
  20218. // safely copies array contents to a potentially smaller array
  20219. function copyArrayContents( src, target ) {
  20220. if ( src.constructor !== target.constructor ) {
  20221. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20222. const len = Math.min( src.length, target.length );
  20223. for ( let i = 0; i < len; i ++ ) {
  20224. target[ i ] = src[ i ];
  20225. }
  20226. } else {
  20227. // if the arrays use the same data layout we can use a fast block copy
  20228. const len = Math.min( src.length, target.length );
  20229. target.set( new src.constructor( src.buffer, 0, len ) );
  20230. }
  20231. }
  20232. /**
  20233. * A special version of a mesh with multi draw batch rendering support. Use
  20234. * this class if you have to render a large number of objects with the same
  20235. * material but with different geometries or world transformations. The usage of
  20236. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20237. * rendering performance in your application.
  20238. *
  20239. * ```js
  20240. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20241. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20242. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20243. *
  20244. * // initialize and add geometries into the batched mesh
  20245. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20246. * const boxGeometryId = batchedMesh.addGeometry( box );
  20247. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20248. *
  20249. * // create instances of those geometries
  20250. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20251. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20252. *
  20253. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20254. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20255. *
  20256. * // position the geometries
  20257. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20258. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20259. *
  20260. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20261. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20262. *
  20263. * scene.add( batchedMesh );
  20264. * ```
  20265. *
  20266. * @augments Mesh
  20267. */
  20268. class BatchedMesh extends Mesh {
  20269. /**
  20270. * Constructs a new batched mesh.
  20271. *
  20272. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20273. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20274. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20275. * @param {Material|Array<Material>} [material] - The mesh material.
  20276. */
  20277. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20278. super( new BufferGeometry(), material );
  20279. /**
  20280. * This flag can be used for type testing.
  20281. *
  20282. * @type {boolean}
  20283. * @readonly
  20284. * @default true
  20285. */
  20286. this.isBatchedMesh = true;
  20287. /**
  20288. * When set ot `true`, the individual objects of a batch are frustum culled.
  20289. *
  20290. * @type {boolean}
  20291. * @default true
  20292. */
  20293. this.perObjectFrustumCulled = true;
  20294. /**
  20295. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20296. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20297. * rendered front to back.
  20298. *
  20299. * @type {boolean}
  20300. * @default true
  20301. */
  20302. this.sortObjects = true;
  20303. /**
  20304. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20305. *
  20306. * @type {?Box3}
  20307. * @default null
  20308. */
  20309. this.boundingBox = null;
  20310. /**
  20311. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20312. *
  20313. * @type {?Sphere}
  20314. * @default null
  20315. */
  20316. this.boundingSphere = null;
  20317. /**
  20318. * Takes a sort a function that is run before render. The function takes a list of instances to
  20319. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20320. * sort with.
  20321. *
  20322. * @type {?Function}
  20323. * @default null
  20324. */
  20325. this.customSort = null;
  20326. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20327. this._instanceInfo = [];
  20328. this._geometryInfo = [];
  20329. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20330. this._availableInstanceIds = [];
  20331. this._availableGeometryIds = [];
  20332. // used to track where the next point is that geometry should be inserted
  20333. this._nextIndexStart = 0;
  20334. this._nextVertexStart = 0;
  20335. this._geometryCount = 0;
  20336. // flags
  20337. this._visibilityChanged = true;
  20338. this._geometryInitialized = false;
  20339. // cached user options
  20340. this._maxInstanceCount = maxInstanceCount;
  20341. this._maxVertexCount = maxVertexCount;
  20342. this._maxIndexCount = maxIndexCount;
  20343. // buffers for multi draw
  20344. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20345. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20346. this._multiDrawCount = 0;
  20347. this._multiDrawInstances = null;
  20348. // Local matrix per geometry by using data texture
  20349. this._matricesTexture = null;
  20350. this._indirectTexture = null;
  20351. this._colorsTexture = null;
  20352. this._initMatricesTexture();
  20353. this._initIndirectTexture();
  20354. }
  20355. /**
  20356. * The maximum number of individual instances that can be stored in the batch.
  20357. *
  20358. * @type {number}
  20359. * @readonly
  20360. */
  20361. get maxInstanceCount() {
  20362. return this._maxInstanceCount;
  20363. }
  20364. /**
  20365. * The instance count.
  20366. *
  20367. * @type {number}
  20368. * @readonly
  20369. */
  20370. get instanceCount() {
  20371. return this._instanceInfo.length - this._availableInstanceIds.length;
  20372. }
  20373. /**
  20374. * The number of unused vertices.
  20375. *
  20376. * @type {number}
  20377. * @readonly
  20378. */
  20379. get unusedVertexCount() {
  20380. return this._maxVertexCount - this._nextVertexStart;
  20381. }
  20382. /**
  20383. * The number of unused indices.
  20384. *
  20385. * @type {number}
  20386. * @readonly
  20387. */
  20388. get unusedIndexCount() {
  20389. return this._maxIndexCount - this._nextIndexStart;
  20390. }
  20391. _initMatricesTexture() {
  20392. // layout (1 matrix = 4 pixels)
  20393. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20394. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20395. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20396. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20397. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20398. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20399. size = Math.ceil( size / 4 ) * 4;
  20400. size = Math.max( size, 4 );
  20401. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20402. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20403. this._matricesTexture = matricesTexture;
  20404. }
  20405. _initIndirectTexture() {
  20406. let size = Math.sqrt( this._maxInstanceCount );
  20407. size = Math.ceil( size );
  20408. const indirectArray = new Uint32Array( size * size );
  20409. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20410. this._indirectTexture = indirectTexture;
  20411. }
  20412. _initColorsTexture() {
  20413. let size = Math.sqrt( this._maxInstanceCount );
  20414. size = Math.ceil( size );
  20415. // 4 floats per RGBA pixel initialized to white
  20416. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20417. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20418. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20419. this._colorsTexture = colorsTexture;
  20420. }
  20421. _initializeGeometry( reference ) {
  20422. const geometry = this.geometry;
  20423. const maxVertexCount = this._maxVertexCount;
  20424. const maxIndexCount = this._maxIndexCount;
  20425. if ( this._geometryInitialized === false ) {
  20426. for ( const attributeName in reference.attributes ) {
  20427. const srcAttribute = reference.getAttribute( attributeName );
  20428. const { array, itemSize, normalized } = srcAttribute;
  20429. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20430. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20431. geometry.setAttribute( attributeName, dstAttribute );
  20432. }
  20433. if ( reference.getIndex() !== null ) {
  20434. // Reserve last u16 index for primitive restart.
  20435. const indexArray = maxVertexCount > 65535
  20436. ? new Uint32Array( maxIndexCount )
  20437. : new Uint16Array( maxIndexCount );
  20438. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20439. }
  20440. this._geometryInitialized = true;
  20441. }
  20442. }
  20443. // Make sure the geometry is compatible with the existing combined geometry attributes
  20444. _validateGeometry( geometry ) {
  20445. // check to ensure the geometries are using consistent attributes and indices
  20446. const batchGeometry = this.geometry;
  20447. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20448. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20449. }
  20450. for ( const attributeName in batchGeometry.attributes ) {
  20451. if ( ! geometry.hasAttribute( attributeName ) ) {
  20452. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20453. }
  20454. const srcAttribute = geometry.getAttribute( attributeName );
  20455. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20456. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20457. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20458. }
  20459. }
  20460. }
  20461. /**
  20462. * Validates the instance defined by the given ID.
  20463. *
  20464. * @param {number} instanceId - The instance to validate.
  20465. */
  20466. validateInstanceId( instanceId ) {
  20467. const instanceInfo = this._instanceInfo;
  20468. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20469. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20470. }
  20471. }
  20472. /**
  20473. * Validates the geometry defined by the given ID.
  20474. *
  20475. * @param {number} geometryId - The geometry to validate.
  20476. */
  20477. validateGeometryId( geometryId ) {
  20478. const geometryInfoList = this._geometryInfo;
  20479. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20480. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20481. }
  20482. }
  20483. /**
  20484. * Takes a sort a function that is run before render. The function takes a list of instances to
  20485. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20486. *
  20487. * @param {Function} func - The custom sort function.
  20488. * @return {BatchedMesh} A reference to this batched mesh.
  20489. */
  20490. setCustomSort( func ) {
  20491. this.customSort = func;
  20492. return this;
  20493. }
  20494. /**
  20495. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20496. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20497. * otherwise they are `null`.
  20498. */
  20499. computeBoundingBox() {
  20500. if ( this.boundingBox === null ) {
  20501. this.boundingBox = new Box3();
  20502. }
  20503. const boundingBox = this.boundingBox;
  20504. const instanceInfo = this._instanceInfo;
  20505. boundingBox.makeEmpty();
  20506. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20507. if ( instanceInfo[ i ].active === false ) continue;
  20508. const geometryId = instanceInfo[ i ].geometryIndex;
  20509. this.getMatrixAt( i, _matrix$1 );
  20510. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20511. boundingBox.union( _box$1 );
  20512. }
  20513. }
  20514. /**
  20515. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20516. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20517. * otherwise they are `null`.
  20518. */
  20519. computeBoundingSphere() {
  20520. if ( this.boundingSphere === null ) {
  20521. this.boundingSphere = new Sphere();
  20522. }
  20523. const boundingSphere = this.boundingSphere;
  20524. const instanceInfo = this._instanceInfo;
  20525. boundingSphere.makeEmpty();
  20526. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20527. if ( instanceInfo[ i ].active === false ) continue;
  20528. const geometryId = instanceInfo[ i ].geometryIndex;
  20529. this.getMatrixAt( i, _matrix$1 );
  20530. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20531. boundingSphere.union( _sphere$2 );
  20532. }
  20533. }
  20534. /**
  20535. * Adds a new instance to the batch using the geometry of the given ID and returns
  20536. * a new id referring to the new instance to be used by other functions.
  20537. *
  20538. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20539. * @return {number} The instance ID.
  20540. */
  20541. addInstance( geometryId ) {
  20542. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20543. // ensure we're not over geometry
  20544. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20545. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20546. }
  20547. const instanceInfo = {
  20548. visible: true,
  20549. active: true,
  20550. geometryIndex: geometryId,
  20551. };
  20552. let drawId = null;
  20553. // Prioritize using previously freed instance ids
  20554. if ( this._availableInstanceIds.length > 0 ) {
  20555. this._availableInstanceIds.sort( ascIdSort );
  20556. drawId = this._availableInstanceIds.shift();
  20557. this._instanceInfo[ drawId ] = instanceInfo;
  20558. } else {
  20559. drawId = this._instanceInfo.length;
  20560. this._instanceInfo.push( instanceInfo );
  20561. }
  20562. const matricesTexture = this._matricesTexture;
  20563. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20564. matricesTexture.needsUpdate = true;
  20565. const colorsTexture = this._colorsTexture;
  20566. if ( colorsTexture ) {
  20567. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20568. colorsTexture.needsUpdate = true;
  20569. }
  20570. this._visibilityChanged = true;
  20571. return drawId;
  20572. }
  20573. /**
  20574. * Adds the given geometry to the batch and returns the associated
  20575. * geometry id referring to it to be used in other functions.
  20576. *
  20577. * @param {BufferGeometry} geometry - The geometry to add.
  20578. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20579. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20580. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20581. * Defaults to the length of the given geometry vertex buffer.
  20582. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20583. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20584. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20585. * the length of the given geometry index buffer.
  20586. * @return {number} The geometry ID.
  20587. */
  20588. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20589. this._initializeGeometry( geometry );
  20590. this._validateGeometry( geometry );
  20591. const geometryInfo = {
  20592. // geometry information
  20593. vertexStart: -1,
  20594. vertexCount: -1,
  20595. reservedVertexCount: -1,
  20596. indexStart: -1,
  20597. indexCount: -1,
  20598. reservedIndexCount: -1,
  20599. // draw range information
  20600. start: -1,
  20601. count: -1,
  20602. // state
  20603. boundingBox: null,
  20604. boundingSphere: null,
  20605. active: true,
  20606. };
  20607. const geometryInfoList = this._geometryInfo;
  20608. geometryInfo.vertexStart = this._nextVertexStart;
  20609. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20610. const index = geometry.getIndex();
  20611. const hasIndex = index !== null;
  20612. if ( hasIndex ) {
  20613. geometryInfo.indexStart = this._nextIndexStart;
  20614. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20615. }
  20616. if (
  20617. geometryInfo.indexStart !== -1 &&
  20618. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20619. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20620. ) {
  20621. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20622. }
  20623. // update id
  20624. let geometryId;
  20625. if ( this._availableGeometryIds.length > 0 ) {
  20626. this._availableGeometryIds.sort( ascIdSort );
  20627. geometryId = this._availableGeometryIds.shift();
  20628. geometryInfoList[ geometryId ] = geometryInfo;
  20629. } else {
  20630. geometryId = this._geometryCount;
  20631. this._geometryCount ++;
  20632. geometryInfoList.push( geometryInfo );
  20633. }
  20634. // update the geometry
  20635. this.setGeometryAt( geometryId, geometry );
  20636. // increment the next geometry position
  20637. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20638. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20639. return geometryId;
  20640. }
  20641. /**
  20642. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20643. * is not enough space reserved for geometry. Calling this will change all instances that are
  20644. * rendering that geometry.
  20645. *
  20646. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20647. * @param {BufferGeometry} geometry - The new geometry.
  20648. * @return {number} The geometry ID.
  20649. */
  20650. setGeometryAt( geometryId, geometry ) {
  20651. if ( geometryId >= this._geometryCount ) {
  20652. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20653. }
  20654. this._validateGeometry( geometry );
  20655. const batchGeometry = this.geometry;
  20656. const hasIndex = batchGeometry.getIndex() !== null;
  20657. const dstIndex = batchGeometry.getIndex();
  20658. const srcIndex = geometry.getIndex();
  20659. const geometryInfo = this._geometryInfo[ geometryId ];
  20660. if (
  20661. hasIndex &&
  20662. srcIndex.count > geometryInfo.reservedIndexCount ||
  20663. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20664. ) {
  20665. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20666. }
  20667. // copy geometry buffer data over
  20668. const vertexStart = geometryInfo.vertexStart;
  20669. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20670. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20671. for ( const attributeName in batchGeometry.attributes ) {
  20672. // copy attribute data
  20673. const srcAttribute = geometry.getAttribute( attributeName );
  20674. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20675. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20676. // fill the rest in with zeroes
  20677. const itemSize = srcAttribute.itemSize;
  20678. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20679. const index = vertexStart + i;
  20680. for ( let c = 0; c < itemSize; c ++ ) {
  20681. dstAttribute.setComponent( index, c, 0 );
  20682. }
  20683. }
  20684. dstAttribute.needsUpdate = true;
  20685. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20686. }
  20687. // copy index
  20688. if ( hasIndex ) {
  20689. const indexStart = geometryInfo.indexStart;
  20690. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20691. geometryInfo.indexCount = geometry.getIndex().count;
  20692. // copy index data over
  20693. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20694. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20695. }
  20696. // fill the rest in with zeroes
  20697. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20698. dstIndex.setX( indexStart + i, vertexStart );
  20699. }
  20700. dstIndex.needsUpdate = true;
  20701. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20702. }
  20703. // update the draw range
  20704. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20705. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20706. // store the bounding boxes
  20707. geometryInfo.boundingBox = null;
  20708. if ( geometry.boundingBox !== null ) {
  20709. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20710. }
  20711. geometryInfo.boundingSphere = null;
  20712. if ( geometry.boundingSphere !== null ) {
  20713. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20714. }
  20715. this._visibilityChanged = true;
  20716. return geometryId;
  20717. }
  20718. /**
  20719. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20720. * this geometry will also be removed as a side effect.
  20721. *
  20722. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20723. * @return {BatchedMesh} A reference to this batched mesh.
  20724. */
  20725. deleteGeometry( geometryId ) {
  20726. const geometryInfoList = this._geometryInfo;
  20727. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20728. return this;
  20729. }
  20730. // delete any instances associated with this geometry
  20731. const instanceInfo = this._instanceInfo;
  20732. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20733. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20734. this.deleteInstance( i );
  20735. }
  20736. }
  20737. geometryInfoList[ geometryId ].active = false;
  20738. this._availableGeometryIds.push( geometryId );
  20739. this._visibilityChanged = true;
  20740. return this;
  20741. }
  20742. /**
  20743. * Deletes an existing instance from the batch using the given ID.
  20744. *
  20745. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20746. * @return {BatchedMesh} A reference to this batched mesh.
  20747. */
  20748. deleteInstance( instanceId ) {
  20749. this.validateInstanceId( instanceId );
  20750. this._instanceInfo[ instanceId ].active = false;
  20751. this._availableInstanceIds.push( instanceId );
  20752. this._visibilityChanged = true;
  20753. return this;
  20754. }
  20755. /**
  20756. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20757. * previously deleted geometry, freeing up space to add new geometry.
  20758. *
  20759. * @return {BatchedMesh} A reference to this batched mesh.
  20760. */
  20761. optimize() {
  20762. // track the next indices to copy data to
  20763. let nextVertexStart = 0;
  20764. let nextIndexStart = 0;
  20765. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20766. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20767. const geometryInfoList = this._geometryInfo;
  20768. const indices = geometryInfoList
  20769. .map( ( e, i ) => i )
  20770. .sort( ( a, b ) => {
  20771. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20772. } );
  20773. const geometry = this.geometry;
  20774. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20775. // if a geometry range is inactive then don't copy anything
  20776. const index = indices[ i ];
  20777. const geometryInfo = geometryInfoList[ index ];
  20778. if ( geometryInfo.active === false ) {
  20779. continue;
  20780. }
  20781. // if a geometry contains an index buffer then shift it, as well
  20782. if ( geometry.index !== null ) {
  20783. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20784. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20785. const index = geometry.index;
  20786. const array = index.array;
  20787. // shift the index pointers based on how the vertex data will shift
  20788. // adjusting the index must happen first so the original vertex start value is available
  20789. const elementDelta = nextVertexStart - vertexStart;
  20790. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20791. array[ j ] = array[ j ] + elementDelta;
  20792. }
  20793. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20794. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20795. index.needsUpdate = true;
  20796. geometryInfo.indexStart = nextIndexStart;
  20797. }
  20798. nextIndexStart += geometryInfo.reservedIndexCount;
  20799. }
  20800. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20801. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20802. const { vertexStart, reservedVertexCount } = geometryInfo;
  20803. const attributes = geometry.attributes;
  20804. for ( const key in attributes ) {
  20805. const attribute = attributes[ key ];
  20806. const { array, itemSize } = attribute;
  20807. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20808. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20809. attribute.needsUpdate = true;
  20810. }
  20811. geometryInfo.vertexStart = nextVertexStart;
  20812. }
  20813. nextVertexStart += geometryInfo.reservedVertexCount;
  20814. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20815. }
  20816. this._nextIndexStart = nextIndexStart;
  20817. this._nextVertexStart = nextVertexStart;
  20818. this._visibilityChanged = true;
  20819. return this;
  20820. }
  20821. /**
  20822. * Returns the bounding box for the given geometry.
  20823. *
  20824. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20825. * @param {Box3} target - The target object that is used to store the method's result.
  20826. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20827. */
  20828. getBoundingBoxAt( geometryId, target ) {
  20829. if ( geometryId >= this._geometryCount ) {
  20830. return null;
  20831. }
  20832. // compute bounding box
  20833. const geometry = this.geometry;
  20834. const geometryInfo = this._geometryInfo[ geometryId ];
  20835. if ( geometryInfo.boundingBox === null ) {
  20836. const box = new Box3();
  20837. const index = geometry.index;
  20838. const position = geometry.attributes.position;
  20839. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20840. let iv = i;
  20841. if ( index ) {
  20842. iv = index.getX( iv );
  20843. }
  20844. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20845. }
  20846. geometryInfo.boundingBox = box;
  20847. }
  20848. target.copy( geometryInfo.boundingBox );
  20849. return target;
  20850. }
  20851. /**
  20852. * Returns the bounding sphere for the given geometry.
  20853. *
  20854. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20855. * @param {Sphere} target - The target object that is used to store the method's result.
  20856. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20857. */
  20858. getBoundingSphereAt( geometryId, target ) {
  20859. if ( geometryId >= this._geometryCount ) {
  20860. return null;
  20861. }
  20862. // compute bounding sphere
  20863. const geometry = this.geometry;
  20864. const geometryInfo = this._geometryInfo[ geometryId ];
  20865. if ( geometryInfo.boundingSphere === null ) {
  20866. const sphere = new Sphere();
  20867. this.getBoundingBoxAt( geometryId, _box$1 );
  20868. _box$1.getCenter( sphere.center );
  20869. const index = geometry.index;
  20870. const position = geometry.attributes.position;
  20871. let maxRadiusSq = 0;
  20872. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20873. let iv = i;
  20874. if ( index ) {
  20875. iv = index.getX( iv );
  20876. }
  20877. _vector$5.fromBufferAttribute( position, iv );
  20878. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20879. }
  20880. sphere.radius = Math.sqrt( maxRadiusSq );
  20881. geometryInfo.boundingSphere = sphere;
  20882. }
  20883. target.copy( geometryInfo.boundingSphere );
  20884. return target;
  20885. }
  20886. /**
  20887. * Sets the given local transformation matrix to the defined instance.
  20888. * Negatively scaled matrices are not supported.
  20889. *
  20890. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20891. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20892. * @return {BatchedMesh} A reference to this batched mesh.
  20893. */
  20894. setMatrixAt( instanceId, matrix ) {
  20895. this.validateInstanceId( instanceId );
  20896. const matricesTexture = this._matricesTexture;
  20897. const matricesArray = this._matricesTexture.image.data;
  20898. matrix.toArray( matricesArray, instanceId * 16 );
  20899. matricesTexture.needsUpdate = true;
  20900. return this;
  20901. }
  20902. /**
  20903. * Returns the local transformation matrix of the defined instance.
  20904. *
  20905. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20906. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20907. * @return {Matrix4} The instance's local transformation matrix.
  20908. */
  20909. getMatrixAt( instanceId, matrix ) {
  20910. this.validateInstanceId( instanceId );
  20911. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20912. }
  20913. /**
  20914. * Sets the given color to the defined instance.
  20915. *
  20916. * @param {number} instanceId - The ID of an instance to set the color of.
  20917. * @param {Color} color - The color to set the instance to.
  20918. * @return {BatchedMesh} A reference to this batched mesh.
  20919. */
  20920. setColorAt( instanceId, color ) {
  20921. this.validateInstanceId( instanceId );
  20922. if ( this._colorsTexture === null ) {
  20923. this._initColorsTexture();
  20924. }
  20925. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20926. this._colorsTexture.needsUpdate = true;
  20927. return this;
  20928. }
  20929. /**
  20930. * Returns the color of the defined instance.
  20931. *
  20932. * @param {number} instanceId - The ID of an instance to get the color of.
  20933. * @param {Color} color - The target object that is used to store the method's result.
  20934. * @return {Color} The instance's color.
  20935. */
  20936. getColorAt( instanceId, color ) {
  20937. this.validateInstanceId( instanceId );
  20938. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20939. }
  20940. /**
  20941. * Sets the visibility of the instance.
  20942. *
  20943. * @param {number} instanceId - The id of the instance to set the visibility of.
  20944. * @param {boolean} visible - Whether the instance is visible or not.
  20945. * @return {BatchedMesh} A reference to this batched mesh.
  20946. */
  20947. setVisibleAt( instanceId, visible ) {
  20948. this.validateInstanceId( instanceId );
  20949. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20950. return this;
  20951. }
  20952. this._instanceInfo[ instanceId ].visible = visible;
  20953. this._visibilityChanged = true;
  20954. return this;
  20955. }
  20956. /**
  20957. * Returns the visibility state of the defined instance.
  20958. *
  20959. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20960. * @return {boolean} Whether the instance is visible or not.
  20961. */
  20962. getVisibleAt( instanceId ) {
  20963. this.validateInstanceId( instanceId );
  20964. return this._instanceInfo[ instanceId ].visible;
  20965. }
  20966. /**
  20967. * Sets the geometry ID of the instance at the given index.
  20968. *
  20969. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20970. * @param {number} geometryId - The geometry ID to be use by the instance.
  20971. * @return {BatchedMesh} A reference to this batched mesh.
  20972. */
  20973. setGeometryIdAt( instanceId, geometryId ) {
  20974. this.validateInstanceId( instanceId );
  20975. this.validateGeometryId( geometryId );
  20976. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20977. return this;
  20978. }
  20979. /**
  20980. * Returns the geometry ID of the defined instance.
  20981. *
  20982. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20983. * @return {number} The instance's geometry ID.
  20984. */
  20985. getGeometryIdAt( instanceId ) {
  20986. this.validateInstanceId( instanceId );
  20987. return this._instanceInfo[ instanceId ].geometryIndex;
  20988. }
  20989. /**
  20990. * Get the range representing the subset of triangles related to the attached geometry,
  20991. * indicating the starting offset and count, or `null` if invalid.
  20992. *
  20993. * @param {number} geometryId - The id of the geometry to get the range of.
  20994. * @param {Object} [target] - The target object that is used to store the method's result.
  20995. * @return {{
  20996. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20997. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20998. * start:number,count:number
  20999. * }} The result object with range data.
  21000. */
  21001. getGeometryRangeAt( geometryId, target = {} ) {
  21002. this.validateGeometryId( geometryId );
  21003. const geometryInfo = this._geometryInfo[ geometryId ];
  21004. target.vertexStart = geometryInfo.vertexStart;
  21005. target.vertexCount = geometryInfo.vertexCount;
  21006. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  21007. target.indexStart = geometryInfo.indexStart;
  21008. target.indexCount = geometryInfo.indexCount;
  21009. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  21010. target.start = geometryInfo.start;
  21011. target.count = geometryInfo.count;
  21012. return target;
  21013. }
  21014. /**
  21015. * Resizes the necessary buffers to support the provided number of instances.
  21016. * If the provided arguments shrink the number of instances but there are not enough
  21017. * unused Ids at the end of the list then an error is thrown.
  21018. *
  21019. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  21020. */
  21021. setInstanceCount( maxInstanceCount ) {
  21022. // shrink the available instances as much as possible
  21023. const availableInstanceIds = this._availableInstanceIds;
  21024. const instanceInfo = this._instanceInfo;
  21025. availableInstanceIds.sort( ascIdSort );
  21026. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  21027. instanceInfo.pop();
  21028. availableInstanceIds.pop();
  21029. }
  21030. // throw an error if it can't be shrunk to the desired size
  21031. if ( maxInstanceCount < instanceInfo.length ) {
  21032. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  21033. }
  21034. // copy the multi draw counts
  21035. const multiDrawCounts = new Int32Array( maxInstanceCount );
  21036. const multiDrawStarts = new Int32Array( maxInstanceCount );
  21037. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  21038. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  21039. this._multiDrawCounts = multiDrawCounts;
  21040. this._multiDrawStarts = multiDrawStarts;
  21041. this._maxInstanceCount = maxInstanceCount;
  21042. // update texture data for instance sampling
  21043. const indirectTexture = this._indirectTexture;
  21044. const matricesTexture = this._matricesTexture;
  21045. const colorsTexture = this._colorsTexture;
  21046. indirectTexture.dispose();
  21047. this._initIndirectTexture();
  21048. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  21049. matricesTexture.dispose();
  21050. this._initMatricesTexture();
  21051. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  21052. if ( colorsTexture ) {
  21053. colorsTexture.dispose();
  21054. this._initColorsTexture();
  21055. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  21056. }
  21057. }
  21058. /**
  21059. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  21060. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  21061. * end of the geometry attributes then an error is thrown.
  21062. *
  21063. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  21064. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  21065. */
  21066. setGeometrySize( maxVertexCount, maxIndexCount ) {
  21067. // Check if we can shrink to the requested vertex attribute size
  21068. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  21069. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  21070. if ( requiredVertexLength > maxVertexCount ) {
  21071. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21072. }
  21073. // Check if we can shrink to the requested index attribute size
  21074. if ( this.geometry.index ) {
  21075. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  21076. if ( requiredIndexLength > maxIndexCount ) {
  21077. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  21078. }
  21079. }
  21080. //
  21081. // dispose of the previous geometry
  21082. const oldGeometry = this.geometry;
  21083. oldGeometry.dispose();
  21084. // recreate the geometry needed based on the previous variant
  21085. this._maxVertexCount = maxVertexCount;
  21086. this._maxIndexCount = maxIndexCount;
  21087. if ( this._geometryInitialized ) {
  21088. this._geometryInitialized = false;
  21089. this.geometry = new BufferGeometry();
  21090. this._initializeGeometry( oldGeometry );
  21091. }
  21092. // copy data from the previous geometry
  21093. const geometry = this.geometry;
  21094. if ( oldGeometry.index ) {
  21095. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  21096. }
  21097. for ( const key in oldGeometry.attributes ) {
  21098. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  21099. }
  21100. }
  21101. raycast( raycaster, intersects ) {
  21102. const instanceInfo = this._instanceInfo;
  21103. const geometryInfoList = this._geometryInfo;
  21104. const matrixWorld = this.matrixWorld;
  21105. const batchGeometry = this.geometry;
  21106. // iterate over each geometry
  21107. _mesh.material = this.material;
  21108. _mesh.geometry.index = batchGeometry.index;
  21109. _mesh.geometry.attributes = batchGeometry.attributes;
  21110. if ( _mesh.geometry.boundingBox === null ) {
  21111. _mesh.geometry.boundingBox = new Box3();
  21112. }
  21113. if ( _mesh.geometry.boundingSphere === null ) {
  21114. _mesh.geometry.boundingSphere = new Sphere();
  21115. }
  21116. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21117. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  21118. continue;
  21119. }
  21120. const geometryId = instanceInfo[ i ].geometryIndex;
  21121. const geometryInfo = geometryInfoList[ geometryId ];
  21122. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  21123. // get the intersects
  21124. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  21125. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  21126. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  21127. _mesh.raycast( raycaster, _batchIntersects );
  21128. // add batch id to the intersects
  21129. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  21130. const intersect = _batchIntersects[ j ];
  21131. intersect.object = this;
  21132. intersect.batchId = i;
  21133. intersects.push( intersect );
  21134. }
  21135. _batchIntersects.length = 0;
  21136. }
  21137. _mesh.material = null;
  21138. _mesh.geometry.index = null;
  21139. _mesh.geometry.attributes = {};
  21140. _mesh.geometry.setDrawRange( 0, Infinity );
  21141. }
  21142. copy( source ) {
  21143. super.copy( source );
  21144. this.geometry = source.geometry.clone();
  21145. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  21146. this.sortObjects = source.sortObjects;
  21147. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  21148. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  21149. this._geometryInfo = source._geometryInfo.map( info => ( {
  21150. ...info,
  21151. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  21152. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  21153. } ) );
  21154. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  21155. this._availableInstanceIds = source._availableInstanceIds.slice();
  21156. this._availableGeometryIds = source._availableGeometryIds.slice();
  21157. this._nextIndexStart = source._nextIndexStart;
  21158. this._nextVertexStart = source._nextVertexStart;
  21159. this._geometryCount = source._geometryCount;
  21160. this._maxInstanceCount = source._maxInstanceCount;
  21161. this._maxVertexCount = source._maxVertexCount;
  21162. this._maxIndexCount = source._maxIndexCount;
  21163. this._geometryInitialized = source._geometryInitialized;
  21164. this._multiDrawCounts = source._multiDrawCounts.slice();
  21165. this._multiDrawStarts = source._multiDrawStarts.slice();
  21166. this._indirectTexture = source._indirectTexture.clone();
  21167. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  21168. this._matricesTexture = source._matricesTexture.clone();
  21169. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  21170. if ( this._colorsTexture !== null ) {
  21171. this._colorsTexture = source._colorsTexture.clone();
  21172. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  21173. }
  21174. return this;
  21175. }
  21176. /**
  21177. * Frees the GPU-related resources allocated by this instance. Call this
  21178. * method whenever this instance is no longer used in your app.
  21179. */
  21180. dispose() {
  21181. // Assuming the geometry is not shared with other meshes
  21182. this.geometry.dispose();
  21183. this._matricesTexture.dispose();
  21184. this._matricesTexture = null;
  21185. this._indirectTexture.dispose();
  21186. this._indirectTexture = null;
  21187. if ( this._colorsTexture !== null ) {
  21188. this._colorsTexture.dispose();
  21189. this._colorsTexture = null;
  21190. }
  21191. }
  21192. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  21193. // if visibility has not changed and frustum culling and object sorting is not required
  21194. // then skip iterating over all items
  21195. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  21196. return;
  21197. }
  21198. // the indexed version of the multi draw function requires specifying the start
  21199. // offset in bytes.
  21200. const index = geometry.getIndex();
  21201. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21202. const instanceInfo = this._instanceInfo;
  21203. const multiDrawStarts = this._multiDrawStarts;
  21204. const multiDrawCounts = this._multiDrawCounts;
  21205. const geometryInfoList = this._geometryInfo;
  21206. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21207. const indirectTexture = this._indirectTexture;
  21208. const indirectArray = indirectTexture.image.data;
  21209. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21210. // prepare the frustum in the local frame
  21211. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21212. _matrix$1
  21213. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21214. .multiply( this.matrixWorld );
  21215. _frustum.setFromProjectionMatrix(
  21216. _matrix$1,
  21217. camera.coordinateSystem,
  21218. camera.reversedDepth
  21219. );
  21220. }
  21221. let multiDrawCount = 0;
  21222. if ( this.sortObjects ) {
  21223. // get the camera position in the local frame
  21224. _matrix$1.copy( this.matrixWorld ).invert();
  21225. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21226. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21227. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21228. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21229. const geometryId = instanceInfo[ i ].geometryIndex;
  21230. // get the bounds in world space
  21231. this.getMatrixAt( i, _matrix$1 );
  21232. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21233. // determine whether the batched geometry is within the frustum
  21234. let culled = false;
  21235. if ( perObjectFrustumCulled ) {
  21236. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21237. }
  21238. if ( ! culled ) {
  21239. // get the distance from camera used for sorting
  21240. const geometryInfo = geometryInfoList[ geometryId ];
  21241. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21242. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21243. }
  21244. }
  21245. }
  21246. // Sort the draw ranges and prep for rendering
  21247. const list = _renderList.list;
  21248. const customSort = this.customSort;
  21249. if ( customSort === null ) {
  21250. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21251. } else {
  21252. customSort.call( this, list, camera );
  21253. }
  21254. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21255. const item = list[ i ];
  21256. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21257. multiDrawCounts[ multiDrawCount ] = item.count;
  21258. indirectArray[ multiDrawCount ] = item.index;
  21259. multiDrawCount ++;
  21260. }
  21261. _renderList.reset();
  21262. } else {
  21263. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21264. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21265. const geometryId = instanceInfo[ i ].geometryIndex;
  21266. // determine whether the batched geometry is within the frustum
  21267. let culled = false;
  21268. if ( perObjectFrustumCulled ) {
  21269. // get the bounds in world space
  21270. this.getMatrixAt( i, _matrix$1 );
  21271. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21272. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21273. }
  21274. if ( ! culled ) {
  21275. const geometryInfo = geometryInfoList[ geometryId ];
  21276. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21277. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21278. indirectArray[ multiDrawCount ] = i;
  21279. multiDrawCount ++;
  21280. }
  21281. }
  21282. }
  21283. }
  21284. indirectTexture.needsUpdate = true;
  21285. this._multiDrawCount = multiDrawCount;
  21286. this._visibilityChanged = false;
  21287. }
  21288. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21289. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21290. }
  21291. }
  21292. /**
  21293. * A material for rendering line primitives.
  21294. *
  21295. * Materials define the appearance of renderable 3D objects.
  21296. *
  21297. * ```js
  21298. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21299. * ```
  21300. *
  21301. * @augments Material
  21302. */
  21303. class LineBasicMaterial extends Material {
  21304. /**
  21305. * Constructs a new line basic material.
  21306. *
  21307. * @param {Object} [parameters] - An object with one or more properties
  21308. * defining the material's appearance. Any property of the material
  21309. * (including any property from inherited materials) can be passed
  21310. * in here. Color values can be passed any type of value accepted
  21311. * by {@link Color#set}.
  21312. */
  21313. constructor( parameters ) {
  21314. super();
  21315. /**
  21316. * This flag can be used for type testing.
  21317. *
  21318. * @type {boolean}
  21319. * @readonly
  21320. * @default true
  21321. */
  21322. this.isLineBasicMaterial = true;
  21323. this.type = 'LineBasicMaterial';
  21324. /**
  21325. * Color of the material.
  21326. *
  21327. * @type {Color}
  21328. * @default (1,1,1)
  21329. */
  21330. this.color = new Color( 0xffffff );
  21331. /**
  21332. * Sets the color of the lines using data from a texture. The texture map
  21333. * color is modulated by the diffuse `color`.
  21334. *
  21335. * @type {?Texture}
  21336. * @default null
  21337. */
  21338. this.map = null;
  21339. /**
  21340. * Controls line thickness or lines.
  21341. *
  21342. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21343. * ignore this setting and always render line primitives with a
  21344. * width of one pixel.
  21345. *
  21346. * @type {number}
  21347. * @default 1
  21348. */
  21349. this.linewidth = 1;
  21350. /**
  21351. * Defines appearance of line ends.
  21352. *
  21353. * Can only be used with {@link SVGRenderer}.
  21354. *
  21355. * @type {('butt'|'round'|'square')}
  21356. * @default 'round'
  21357. */
  21358. this.linecap = 'round';
  21359. /**
  21360. * Defines appearance of line joints.
  21361. *
  21362. * Can only be used with {@link SVGRenderer}.
  21363. *
  21364. * @type {('round'|'bevel'|'miter')}
  21365. * @default 'round'
  21366. */
  21367. this.linejoin = 'round';
  21368. /**
  21369. * Whether the material is affected by fog or not.
  21370. *
  21371. * @type {boolean}
  21372. * @default true
  21373. */
  21374. this.fog = true;
  21375. this.setValues( parameters );
  21376. }
  21377. copy( source ) {
  21378. super.copy( source );
  21379. this.color.copy( source.color );
  21380. this.map = source.map;
  21381. this.linewidth = source.linewidth;
  21382. this.linecap = source.linecap;
  21383. this.linejoin = source.linejoin;
  21384. this.fog = source.fog;
  21385. return this;
  21386. }
  21387. }
  21388. const _vStart = /*@__PURE__*/ new Vector3();
  21389. const _vEnd = /*@__PURE__*/ new Vector3();
  21390. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21391. const _ray$1 = /*@__PURE__*/ new Ray();
  21392. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21393. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21394. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21395. /**
  21396. * A continuous line. The line are rendered by connecting consecutive
  21397. * vertices with straight lines.
  21398. *
  21399. * ```js
  21400. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21401. *
  21402. * const points = [];
  21403. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21404. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21405. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21406. *
  21407. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21408. *
  21409. * const line = new THREE.Line( geometry, material );
  21410. * scene.add( line );
  21411. * ```
  21412. *
  21413. * @augments Object3D
  21414. */
  21415. class Line extends Object3D {
  21416. /**
  21417. * Constructs a new line.
  21418. *
  21419. * @param {BufferGeometry} [geometry] - The line geometry.
  21420. * @param {Material|Array<Material>} [material] - The line material.
  21421. */
  21422. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21423. super();
  21424. /**
  21425. * This flag can be used for type testing.
  21426. *
  21427. * @type {boolean}
  21428. * @readonly
  21429. * @default true
  21430. */
  21431. this.isLine = true;
  21432. this.type = 'Line';
  21433. /**
  21434. * The line geometry.
  21435. *
  21436. * @type {BufferGeometry}
  21437. */
  21438. this.geometry = geometry;
  21439. /**
  21440. * The line material.
  21441. *
  21442. * @type {Material|Array<Material>}
  21443. * @default LineBasicMaterial
  21444. */
  21445. this.material = material;
  21446. /**
  21447. * A dictionary representing the morph targets in the geometry. The key is the
  21448. * morph targets name, the value its attribute index. This member is `undefined`
  21449. * by default and only set when morph targets are detected in the geometry.
  21450. *
  21451. * @type {Object<string,number>|undefined}
  21452. * @default undefined
  21453. */
  21454. this.morphTargetDictionary = undefined;
  21455. /**
  21456. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21457. * is applied. This member is `undefined` by default and only set when morph targets are
  21458. * detected in the geometry.
  21459. *
  21460. * @type {Array<number>|undefined}
  21461. * @default undefined
  21462. */
  21463. this.morphTargetInfluences = undefined;
  21464. this.updateMorphTargets();
  21465. }
  21466. copy( source, recursive ) {
  21467. super.copy( source, recursive );
  21468. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21469. this.geometry = source.geometry;
  21470. return this;
  21471. }
  21472. /**
  21473. * Computes an array of distance values which are necessary for rendering dashed lines.
  21474. * For each vertex in the geometry, the method calculates the cumulative length from the
  21475. * current point to the very beginning of the line.
  21476. *
  21477. * @return {Line} A reference to this line.
  21478. */
  21479. computeLineDistances() {
  21480. const geometry = this.geometry;
  21481. // we assume non-indexed geometry
  21482. if ( geometry.index === null ) {
  21483. const positionAttribute = geometry.attributes.position;
  21484. const lineDistances = [ 0 ];
  21485. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21486. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21487. _vEnd.fromBufferAttribute( positionAttribute, i );
  21488. lineDistances[ i ] = lineDistances[ i - 1 ];
  21489. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21490. }
  21491. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21492. } else {
  21493. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21494. }
  21495. return this;
  21496. }
  21497. /**
  21498. * Computes intersection points between a casted ray and this line.
  21499. *
  21500. * @param {Raycaster} raycaster - The raycaster.
  21501. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21502. */
  21503. raycast( raycaster, intersects ) {
  21504. const geometry = this.geometry;
  21505. const matrixWorld = this.matrixWorld;
  21506. const threshold = raycaster.params.Line.threshold;
  21507. const drawRange = geometry.drawRange;
  21508. // Checking boundingSphere distance to ray
  21509. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21510. _sphere$1.copy( geometry.boundingSphere );
  21511. _sphere$1.applyMatrix4( matrixWorld );
  21512. _sphere$1.radius += threshold;
  21513. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21514. //
  21515. _inverseMatrix$1.copy( matrixWorld ).invert();
  21516. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21517. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21518. const localThresholdSq = localThreshold * localThreshold;
  21519. const step = this.isLineSegments ? 2 : 1;
  21520. const index = geometry.index;
  21521. const attributes = geometry.attributes;
  21522. const positionAttribute = attributes.position;
  21523. if ( index !== null ) {
  21524. const start = Math.max( 0, drawRange.start );
  21525. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21526. for ( let i = start, l = end - 1; i < l; i += step ) {
  21527. const a = index.getX( i );
  21528. const b = index.getX( i + 1 );
  21529. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21530. if ( intersect ) {
  21531. intersects.push( intersect );
  21532. }
  21533. }
  21534. if ( this.isLineLoop ) {
  21535. const a = index.getX( end - 1 );
  21536. const b = index.getX( start );
  21537. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21538. if ( intersect ) {
  21539. intersects.push( intersect );
  21540. }
  21541. }
  21542. } else {
  21543. const start = Math.max( 0, drawRange.start );
  21544. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21545. for ( let i = start, l = end - 1; i < l; i += step ) {
  21546. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21547. if ( intersect ) {
  21548. intersects.push( intersect );
  21549. }
  21550. }
  21551. if ( this.isLineLoop ) {
  21552. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21553. if ( intersect ) {
  21554. intersects.push( intersect );
  21555. }
  21556. }
  21557. }
  21558. }
  21559. /**
  21560. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21561. * to make sure existing morph targets can influence this 3D object.
  21562. */
  21563. updateMorphTargets() {
  21564. const geometry = this.geometry;
  21565. const morphAttributes = geometry.morphAttributes;
  21566. const keys = Object.keys( morphAttributes );
  21567. if ( keys.length > 0 ) {
  21568. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21569. if ( morphAttribute !== undefined ) {
  21570. this.morphTargetInfluences = [];
  21571. this.morphTargetDictionary = {};
  21572. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21573. const name = morphAttribute[ m ].name || String( m );
  21574. this.morphTargetInfluences.push( 0 );
  21575. this.morphTargetDictionary[ name ] = m;
  21576. }
  21577. }
  21578. }
  21579. }
  21580. }
  21581. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21582. const positionAttribute = object.geometry.attributes.position;
  21583. _vStart.fromBufferAttribute( positionAttribute, a );
  21584. _vEnd.fromBufferAttribute( positionAttribute, b );
  21585. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21586. if ( distSq > thresholdSq ) return;
  21587. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21588. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21589. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21590. return {
  21591. distance: distance,
  21592. // What do we want? intersection point on the ray or on the segment??
  21593. // point: raycaster.ray.at( distance ),
  21594. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21595. index: i,
  21596. face: null,
  21597. faceIndex: null,
  21598. barycoord: null,
  21599. object: object
  21600. };
  21601. }
  21602. const _start = /*@__PURE__*/ new Vector3();
  21603. const _end = /*@__PURE__*/ new Vector3();
  21604. /**
  21605. * A series of lines drawn between pairs of vertices.
  21606. *
  21607. * @augments Line
  21608. */
  21609. class LineSegments extends Line {
  21610. /**
  21611. * Constructs a new line segments.
  21612. *
  21613. * @param {BufferGeometry} [geometry] - The line geometry.
  21614. * @param {Material|Array<Material>} [material] - The line material.
  21615. */
  21616. constructor( geometry, material ) {
  21617. super( geometry, material );
  21618. /**
  21619. * This flag can be used for type testing.
  21620. *
  21621. * @type {boolean}
  21622. * @readonly
  21623. * @default true
  21624. */
  21625. this.isLineSegments = true;
  21626. this.type = 'LineSegments';
  21627. }
  21628. computeLineDistances() {
  21629. const geometry = this.geometry;
  21630. // we assume non-indexed geometry
  21631. if ( geometry.index === null ) {
  21632. const positionAttribute = geometry.attributes.position;
  21633. const lineDistances = [];
  21634. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21635. _start.fromBufferAttribute( positionAttribute, i );
  21636. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21637. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21638. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21639. }
  21640. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21641. } else {
  21642. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21643. }
  21644. return this;
  21645. }
  21646. }
  21647. /**
  21648. * A continuous line. This is nearly the same as {@link Line} the only difference
  21649. * is that the last vertex is connected with the first vertex in order to close
  21650. * the line to form a loop.
  21651. *
  21652. * @augments Line
  21653. */
  21654. class LineLoop extends Line {
  21655. /**
  21656. * Constructs a new line loop.
  21657. *
  21658. * @param {BufferGeometry} [geometry] - The line geometry.
  21659. * @param {Material|Array<Material>} [material] - The line material.
  21660. */
  21661. constructor( geometry, material ) {
  21662. super( geometry, material );
  21663. /**
  21664. * This flag can be used for type testing.
  21665. *
  21666. * @type {boolean}
  21667. * @readonly
  21668. * @default true
  21669. */
  21670. this.isLineLoop = true;
  21671. this.type = 'LineLoop';
  21672. }
  21673. }
  21674. /**
  21675. * A material for rendering point primitives.
  21676. *
  21677. * Materials define the appearance of renderable 3D objects.
  21678. *
  21679. * ```js
  21680. * const vertices = [];
  21681. *
  21682. * for ( let i = 0; i < 10000; i ++ ) {
  21683. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21684. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21685. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21686. *
  21687. * vertices.push( x, y, z );
  21688. * }
  21689. *
  21690. * const geometry = new THREE.BufferGeometry();
  21691. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21692. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21693. * const points = new THREE.Points( geometry, material );
  21694. * scene.add( points );
  21695. * ```
  21696. *
  21697. * @augments Material
  21698. */
  21699. class PointsMaterial extends Material {
  21700. /**
  21701. * Constructs a new points material.
  21702. *
  21703. * @param {Object} [parameters] - An object with one or more properties
  21704. * defining the material's appearance. Any property of the material
  21705. * (including any property from inherited materials) can be passed
  21706. * in here. Color values can be passed any type of value accepted
  21707. * by {@link Color#set}.
  21708. */
  21709. constructor( parameters ) {
  21710. super();
  21711. /**
  21712. * This flag can be used for type testing.
  21713. *
  21714. * @type {boolean}
  21715. * @readonly
  21716. * @default true
  21717. */
  21718. this.isPointsMaterial = true;
  21719. this.type = 'PointsMaterial';
  21720. /**
  21721. * Color of the material.
  21722. *
  21723. * @type {Color}
  21724. * @default (1,1,1)
  21725. */
  21726. this.color = new Color( 0xffffff );
  21727. /**
  21728. * The color map. May optionally include an alpha channel, typically combined
  21729. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21730. * color is modulated by the diffuse `color`.
  21731. *
  21732. * @type {?Texture}
  21733. * @default null
  21734. */
  21735. this.map = null;
  21736. /**
  21737. * The alpha map is a grayscale texture that controls the opacity across the
  21738. * surface (black: fully transparent; white: fully opaque).
  21739. *
  21740. * Only the color of the texture is used, ignoring the alpha channel if one
  21741. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21742. * when sampling this texture due to the extra bit of precision provided for
  21743. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21744. * luminance/alpha textures will also still work as expected.
  21745. *
  21746. * @type {?Texture}
  21747. * @default null
  21748. */
  21749. this.alphaMap = null;
  21750. /**
  21751. * Defines the size of the points in pixels.
  21752. *
  21753. * 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).
  21754. *
  21755. * @type {number}
  21756. * @default 1
  21757. */
  21758. this.size = 1;
  21759. /**
  21760. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21761. *
  21762. * @type {boolean}
  21763. * @default true
  21764. */
  21765. this.sizeAttenuation = true;
  21766. /**
  21767. * Whether the material is affected by fog or not.
  21768. *
  21769. * @type {boolean}
  21770. * @default true
  21771. */
  21772. this.fog = true;
  21773. this.setValues( parameters );
  21774. }
  21775. copy( source ) {
  21776. super.copy( source );
  21777. this.color.copy( source.color );
  21778. this.map = source.map;
  21779. this.alphaMap = source.alphaMap;
  21780. this.size = source.size;
  21781. this.sizeAttenuation = source.sizeAttenuation;
  21782. this.fog = source.fog;
  21783. return this;
  21784. }
  21785. }
  21786. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21787. const _ray = /*@__PURE__*/ new Ray();
  21788. const _sphere = /*@__PURE__*/ new Sphere();
  21789. const _position$2 = /*@__PURE__*/ new Vector3();
  21790. /**
  21791. * A class for displaying points or point clouds.
  21792. *
  21793. * @augments Object3D
  21794. */
  21795. class Points extends Object3D {
  21796. /**
  21797. * Constructs a new point cloud.
  21798. *
  21799. * @param {BufferGeometry} [geometry] - The points geometry.
  21800. * @param {Material|Array<Material>} [material] - The points material.
  21801. */
  21802. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21803. super();
  21804. /**
  21805. * This flag can be used for type testing.
  21806. *
  21807. * @type {boolean}
  21808. * @readonly
  21809. * @default true
  21810. */
  21811. this.isPoints = true;
  21812. this.type = 'Points';
  21813. /**
  21814. * The points geometry.
  21815. *
  21816. * @type {BufferGeometry}
  21817. */
  21818. this.geometry = geometry;
  21819. /**
  21820. * The line material.
  21821. *
  21822. * @type {Material|Array<Material>}
  21823. * @default PointsMaterial
  21824. */
  21825. this.material = material;
  21826. /**
  21827. * A dictionary representing the morph targets in the geometry. The key is the
  21828. * morph targets name, the value its attribute index. This member is `undefined`
  21829. * by default and only set when morph targets are detected in the geometry.
  21830. *
  21831. * @type {Object<string,number>|undefined}
  21832. * @default undefined
  21833. */
  21834. this.morphTargetDictionary = undefined;
  21835. /**
  21836. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21837. * is applied. This member is `undefined` by default and only set when morph targets are
  21838. * detected in the geometry.
  21839. *
  21840. * @type {Array<number>|undefined}
  21841. * @default undefined
  21842. */
  21843. this.morphTargetInfluences = undefined;
  21844. this.updateMorphTargets();
  21845. }
  21846. copy( source, recursive ) {
  21847. super.copy( source, recursive );
  21848. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21849. this.geometry = source.geometry;
  21850. return this;
  21851. }
  21852. /**
  21853. * Computes intersection points between a casted ray and this point cloud.
  21854. *
  21855. * @param {Raycaster} raycaster - The raycaster.
  21856. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21857. */
  21858. raycast( raycaster, intersects ) {
  21859. const geometry = this.geometry;
  21860. const matrixWorld = this.matrixWorld;
  21861. const threshold = raycaster.params.Points.threshold;
  21862. const drawRange = geometry.drawRange;
  21863. // Checking boundingSphere distance to ray
  21864. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21865. _sphere.copy( geometry.boundingSphere );
  21866. _sphere.applyMatrix4( matrixWorld );
  21867. _sphere.radius += threshold;
  21868. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21869. //
  21870. _inverseMatrix.copy( matrixWorld ).invert();
  21871. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21872. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21873. const localThresholdSq = localThreshold * localThreshold;
  21874. const index = geometry.index;
  21875. const attributes = geometry.attributes;
  21876. const positionAttribute = attributes.position;
  21877. if ( index !== null ) {
  21878. const start = Math.max( 0, drawRange.start );
  21879. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21880. for ( let i = start, il = end; i < il; i ++ ) {
  21881. const a = index.getX( i );
  21882. _position$2.fromBufferAttribute( positionAttribute, a );
  21883. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21884. }
  21885. } else {
  21886. const start = Math.max( 0, drawRange.start );
  21887. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21888. for ( let i = start, l = end; i < l; i ++ ) {
  21889. _position$2.fromBufferAttribute( positionAttribute, i );
  21890. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21891. }
  21892. }
  21893. }
  21894. /**
  21895. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21896. * to make sure existing morph targets can influence this 3D object.
  21897. */
  21898. updateMorphTargets() {
  21899. const geometry = this.geometry;
  21900. const morphAttributes = geometry.morphAttributes;
  21901. const keys = Object.keys( morphAttributes );
  21902. if ( keys.length > 0 ) {
  21903. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21904. if ( morphAttribute !== undefined ) {
  21905. this.morphTargetInfluences = [];
  21906. this.morphTargetDictionary = {};
  21907. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21908. const name = morphAttribute[ m ].name || String( m );
  21909. this.morphTargetInfluences.push( 0 );
  21910. this.morphTargetDictionary[ name ] = m;
  21911. }
  21912. }
  21913. }
  21914. }
  21915. }
  21916. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21917. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21918. if ( rayPointDistanceSq < localThresholdSq ) {
  21919. const intersectPoint = new Vector3();
  21920. _ray.closestPointToPoint( point, intersectPoint );
  21921. intersectPoint.applyMatrix4( matrixWorld );
  21922. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21923. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21924. intersects.push( {
  21925. distance: distance,
  21926. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21927. point: intersectPoint,
  21928. index: index,
  21929. face: null,
  21930. faceIndex: null,
  21931. barycoord: null,
  21932. object: object
  21933. } );
  21934. }
  21935. }
  21936. /**
  21937. * A texture for use with a video.
  21938. *
  21939. * ```js
  21940. * // assuming you have created a HTML video element with id="video"
  21941. * const video = document.getElementById( 'video' );
  21942. * const texture = new THREE.VideoTexture( video );
  21943. * ```
  21944. *
  21945. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21946. * set to THREE.SRGBColorSpace.
  21947. *
  21948. * Note: After the initial use of a texture, its dimensions, format, and type
  21949. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21950. *
  21951. * @augments Texture
  21952. */
  21953. class VideoTexture extends Texture {
  21954. /**
  21955. * Constructs a new video texture.
  21956. *
  21957. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21958. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21959. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21960. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21961. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21962. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21963. * @param {number} [format=RGBAFormat] - The texture format.
  21964. * @param {number} [type=UnsignedByteType] - The texture type.
  21965. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21966. */
  21967. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21968. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21969. /**
  21970. * This flag can be used for type testing.
  21971. *
  21972. * @type {boolean}
  21973. * @readonly
  21974. * @default true
  21975. */
  21976. this.isVideoTexture = true;
  21977. /**
  21978. * Whether to generate mipmaps (if possible) for a texture.
  21979. *
  21980. * Overwritten and set to `false` by default.
  21981. *
  21982. * @type {boolean}
  21983. * @default false
  21984. */
  21985. this.generateMipmaps = false;
  21986. /**
  21987. * The video frame request callback identifier, which is a positive integer.
  21988. *
  21989. * Value of 0 represents no scheduled rVFC.
  21990. *
  21991. * @private
  21992. * @type {number}
  21993. */
  21994. this._requestVideoFrameCallbackId = 0;
  21995. const scope = this;
  21996. function updateVideo() {
  21997. scope.needsUpdate = true;
  21998. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21999. }
  22000. if ( 'requestVideoFrameCallback' in video ) {
  22001. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  22002. }
  22003. }
  22004. clone() {
  22005. return new this.constructor( this.image ).copy( this );
  22006. }
  22007. /**
  22008. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  22009. * to `true` every time a new frame is available.
  22010. *
  22011. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  22012. */
  22013. update() {
  22014. const video = this.image;
  22015. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  22016. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  22017. this.needsUpdate = true;
  22018. }
  22019. }
  22020. dispose() {
  22021. if ( this._requestVideoFrameCallbackId !== 0 ) {
  22022. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  22023. this._requestVideoFrameCallbackId = 0;
  22024. }
  22025. super.dispose();
  22026. }
  22027. }
  22028. /**
  22029. * This class can be used as an alternative way to define video data. Instead of using
  22030. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  22031. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  22032. * video frames are decoded with the WebCodecs API.
  22033. *
  22034. * ```js
  22035. * const texture = new THREE.VideoFrameTexture();
  22036. * texture.setFrame( frame );
  22037. * ```
  22038. *
  22039. * @augments VideoTexture
  22040. */
  22041. class VideoFrameTexture extends VideoTexture {
  22042. /**
  22043. * Constructs a new video frame texture.
  22044. *
  22045. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22046. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22047. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22048. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22049. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22050. * @param {number} [format=RGBAFormat] - The texture format.
  22051. * @param {number} [type=UnsignedByteType] - The texture type.
  22052. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22053. */
  22054. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22055. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22056. /**
  22057. * This flag can be used for type testing.
  22058. *
  22059. * @type {boolean}
  22060. * @readonly
  22061. * @default true
  22062. */
  22063. this.isVideoFrameTexture = true;
  22064. }
  22065. /**
  22066. * This method overwritten with an empty implementation since
  22067. * this type of texture is updated via `setFrame()`.
  22068. */
  22069. update() {}
  22070. clone() {
  22071. return new this.constructor().copy( this ); // restoring Texture.clone()
  22072. }
  22073. /**
  22074. * Sets the current frame of the video. This will automatically update the texture
  22075. * so the data can be used for rendering.
  22076. *
  22077. * @param {VideoFrame} frame - The video frame.
  22078. */
  22079. setFrame( frame ) {
  22080. this.image = frame;
  22081. this.needsUpdate = true;
  22082. }
  22083. }
  22084. /**
  22085. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  22086. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  22087. * as a texture for further usage.
  22088. *
  22089. * ```js
  22090. * const pixelRatio = window.devicePixelRatio;
  22091. * const textureSize = 128 * pixelRatio;
  22092. *
  22093. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  22094. *
  22095. * // calculate start position for copying part of the frame data
  22096. * const vector = new Vector2();
  22097. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  22098. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  22099. *
  22100. * renderer.render( scene, camera );
  22101. *
  22102. * // copy part of the rendered frame into the framebuffer texture
  22103. * renderer.copyFramebufferToTexture( frameTexture, vector );
  22104. * ```
  22105. *
  22106. * @augments Texture
  22107. */
  22108. class FramebufferTexture extends Texture {
  22109. /**
  22110. * Constructs a new framebuffer texture.
  22111. *
  22112. * @param {number} [width] - The width of the texture.
  22113. * @param {number} [height] - The height of the texture.
  22114. */
  22115. constructor( width, height ) {
  22116. super( { width, height } );
  22117. /**
  22118. * This flag can be used for type testing.
  22119. *
  22120. * @type {boolean}
  22121. * @readonly
  22122. * @default true
  22123. */
  22124. this.isFramebufferTexture = true;
  22125. /**
  22126. * How the texture is sampled when a texel covers more than one pixel.
  22127. *
  22128. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22129. *
  22130. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22131. * @default NearestFilter
  22132. */
  22133. this.magFilter = NearestFilter;
  22134. /**
  22135. * How the texture is sampled when a texel covers less than one pixel.
  22136. *
  22137. * Overwritten and set to `NearestFilter` by default to disable filtering.
  22138. *
  22139. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  22140. * @default NearestFilter
  22141. */
  22142. this.minFilter = NearestFilter;
  22143. /**
  22144. * Whether to generate mipmaps (if possible) for a texture.
  22145. *
  22146. * Overwritten and set to `false` by default.
  22147. *
  22148. * @type {boolean}
  22149. * @default false
  22150. */
  22151. this.generateMipmaps = false;
  22152. this.needsUpdate = true;
  22153. }
  22154. }
  22155. /**
  22156. * Creates a texture based on data in compressed form.
  22157. *
  22158. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22159. *
  22160. * @augments Texture
  22161. */
  22162. class CompressedTexture extends Texture {
  22163. /**
  22164. * Constructs a new compressed texture.
  22165. *
  22166. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22167. * the data and dimensions.
  22168. * @param {number} width - The width of the texture.
  22169. * @param {number} height - The height of the texture.
  22170. * @param {number} [format=RGBAFormat] - The texture format.
  22171. * @param {number} [type=UnsignedByteType] - 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=LinearMipmapLinearFilter] - The min filter value.
  22177. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22178. * @param {string} [colorSpace=NoColorSpace] - The color space.
  22179. */
  22180. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  22181. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  22182. /**
  22183. * This flag can be used for type testing.
  22184. *
  22185. * @type {boolean}
  22186. * @readonly
  22187. * @default true
  22188. */
  22189. this.isCompressedTexture = true;
  22190. /**
  22191. * The image property of a compressed texture just defines its dimensions.
  22192. *
  22193. * @type {{width:number,height:number}}
  22194. */
  22195. this.image = { width: width, height: height };
  22196. /**
  22197. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  22198. *
  22199. * @type {Array<Object>}
  22200. */
  22201. this.mipmaps = mipmaps;
  22202. /**
  22203. * If set to `true`, the texture is flipped along the vertical axis when
  22204. * uploaded to the GPU.
  22205. *
  22206. * Overwritten and set to `false` by default since it is not possible to
  22207. * flip compressed textures.
  22208. *
  22209. * @type {boolean}
  22210. * @default false
  22211. * @readonly
  22212. */
  22213. this.flipY = false;
  22214. /**
  22215. * Whether to generate mipmaps (if possible) for a texture.
  22216. *
  22217. * Overwritten and set to `false` by default since it is not
  22218. * possible to generate mipmaps for compressed data. Mipmaps
  22219. * must be embedded in the compressed texture file.
  22220. *
  22221. * @type {boolean}
  22222. * @default false
  22223. * @readonly
  22224. */
  22225. this.generateMipmaps = false;
  22226. }
  22227. }
  22228. /**
  22229. * Creates a texture 2D array based on data in compressed form.
  22230. *
  22231. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22232. *
  22233. * @augments CompressedTexture
  22234. */
  22235. class CompressedArrayTexture extends CompressedTexture {
  22236. /**
  22237. * Constructs a new compressed array texture.
  22238. *
  22239. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22240. * the data and dimensions.
  22241. * @param {number} width - The width of the texture.
  22242. * @param {number} height - The height of the texture.
  22243. * @param {number} depth - The depth of the texture.
  22244. * @param {number} [format=RGBAFormat] - The min filter value.
  22245. * @param {number} [type=UnsignedByteType] - The min filter value.
  22246. */
  22247. constructor( mipmaps, width, height, depth, format, type ) {
  22248. super( mipmaps, width, height, format, type );
  22249. /**
  22250. * This flag can be used for type testing.
  22251. *
  22252. * @type {boolean}
  22253. * @readonly
  22254. * @default true
  22255. */
  22256. this.isCompressedArrayTexture = true;
  22257. /**
  22258. * The image property of a compressed texture just defines its dimensions.
  22259. *
  22260. * @name CompressedArrayTexture#image
  22261. * @type {{width:number,height:number,depth:number}}
  22262. */
  22263. this.image.depth = depth;
  22264. /**
  22265. * This defines how the texture is wrapped in the depth and corresponds to
  22266. * *W* in UVW mapping.
  22267. *
  22268. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22269. * @default ClampToEdgeWrapping
  22270. */
  22271. this.wrapR = ClampToEdgeWrapping;
  22272. /**
  22273. * A set of all layers which need to be updated in the texture.
  22274. *
  22275. * @type {Set<number>}
  22276. */
  22277. this.layerUpdates = new Set();
  22278. }
  22279. /**
  22280. * Describes that a specific layer of the texture needs to be updated.
  22281. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22282. * entire compressed texture array is sent to the GPU. Marking specific
  22283. * layers will only transmit subsets of all mipmaps associated with a
  22284. * specific depth in the array which is often much more performant.
  22285. *
  22286. * @param {number} layerIndex - The layer index that should be updated.
  22287. */
  22288. addLayerUpdate( layerIndex ) {
  22289. this.layerUpdates.add( layerIndex );
  22290. }
  22291. /**
  22292. * Resets the layer updates registry.
  22293. */
  22294. clearLayerUpdates() {
  22295. this.layerUpdates.clear();
  22296. }
  22297. }
  22298. /**
  22299. * Creates a cube texture based on data in compressed form.
  22300. *
  22301. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22302. *
  22303. * @augments CompressedTexture
  22304. */
  22305. class CompressedCubeTexture extends CompressedTexture {
  22306. /**
  22307. * Constructs a new compressed texture.
  22308. *
  22309. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22310. * @param {number} [format=RGBAFormat] - The texture format.
  22311. * @param {number} [type=UnsignedByteType] - The texture type.
  22312. */
  22313. constructor( images, format, type ) {
  22314. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22315. /**
  22316. * This flag can be used for type testing.
  22317. *
  22318. * @type {boolean}
  22319. * @readonly
  22320. * @default true
  22321. */
  22322. this.isCompressedCubeTexture = true;
  22323. /**
  22324. * This flag can be used for type testing.
  22325. *
  22326. * @type {boolean}
  22327. * @readonly
  22328. * @default true
  22329. */
  22330. this.isCubeTexture = true;
  22331. this.image = images;
  22332. }
  22333. }
  22334. /**
  22335. * Creates a texture from a canvas element.
  22336. *
  22337. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22338. * to `true` immediately since a canvas can directly be used for rendering.
  22339. *
  22340. * @augments Texture
  22341. */
  22342. class CanvasTexture extends Texture {
  22343. /**
  22344. * Constructs a new texture.
  22345. *
  22346. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22347. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22348. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22349. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22350. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22351. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22352. * @param {number} [format=RGBAFormat] - The texture format.
  22353. * @param {number} [type=UnsignedByteType] - The texture type.
  22354. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22355. */
  22356. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22357. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22358. /**
  22359. * This flag can be used for type testing.
  22360. *
  22361. * @type {boolean}
  22362. * @readonly
  22363. * @default true
  22364. */
  22365. this.isCanvasTexture = true;
  22366. this.needsUpdate = true;
  22367. }
  22368. }
  22369. /**
  22370. * This class can be used to automatically save the depth information of a
  22371. * rendering into a texture.
  22372. *
  22373. * @augments Texture
  22374. */
  22375. class DepthTexture extends Texture {
  22376. /**
  22377. * Constructs a new depth texture.
  22378. *
  22379. * @param {number} width - The width of the texture.
  22380. * @param {number} height - The height of the texture.
  22381. * @param {number} [type=UnsignedIntType] - The texture type.
  22382. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22383. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22384. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22385. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22386. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22387. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22388. * @param {number} [format=DepthFormat] - The texture format.
  22389. * @param {number} [depth=1] - The depth of the texture.
  22390. */
  22391. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22392. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22393. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22394. }
  22395. const image = { width: width, height: height, depth: depth };
  22396. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22397. /**
  22398. * This flag can be used for type testing.
  22399. *
  22400. * @type {boolean}
  22401. * @readonly
  22402. * @default true
  22403. */
  22404. this.isDepthTexture = true;
  22405. /**
  22406. * If set to `true`, the texture is flipped along the vertical axis when
  22407. * uploaded to the GPU.
  22408. *
  22409. * Overwritten and set to `false` by default.
  22410. *
  22411. * @type {boolean}
  22412. * @default false
  22413. */
  22414. this.flipY = false;
  22415. /**
  22416. * Whether to generate mipmaps (if possible) for a texture.
  22417. *
  22418. * Overwritten and set to `false` by default.
  22419. *
  22420. * @type {boolean}
  22421. * @default false
  22422. */
  22423. this.generateMipmaps = false;
  22424. /**
  22425. * Code corresponding to the depth compare function.
  22426. *
  22427. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22428. * @default null
  22429. */
  22430. this.compareFunction = null;
  22431. }
  22432. copy( source ) {
  22433. super.copy( source );
  22434. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22435. this.compareFunction = source.compareFunction;
  22436. return this;
  22437. }
  22438. toJSON( meta ) {
  22439. const data = super.toJSON( meta );
  22440. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22441. return data;
  22442. }
  22443. }
  22444. /**
  22445. * This class can be used to automatically save the depth information of a
  22446. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22447. *
  22448. * @augments DepthTexture
  22449. */
  22450. class CubeDepthTexture extends DepthTexture {
  22451. /**
  22452. * Constructs a new cube depth texture.
  22453. *
  22454. * @param {number} size - The size (width and height) of each cube face.
  22455. * @param {number} [type=UnsignedIntType] - The texture type.
  22456. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22457. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22458. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22459. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22460. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22461. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22462. * @param {number} [format=DepthFormat] - The texture format.
  22463. */
  22464. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22465. // Create 6 identical image descriptors for the cube faces
  22466. const image = { width: size, height: size, depth: 1 };
  22467. const images = [ image, image, image, image, image, image ];
  22468. // Call DepthTexture constructor with width, height
  22469. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22470. // Replace the single image with the array of 6 images
  22471. this.image = images;
  22472. /**
  22473. * This flag can be used for type testing.
  22474. *
  22475. * @type {boolean}
  22476. * @readonly
  22477. * @default true
  22478. */
  22479. this.isCubeDepthTexture = true;
  22480. /**
  22481. * Set to true for cube texture handling in WebGLTextures.
  22482. *
  22483. * @type {boolean}
  22484. * @readonly
  22485. * @default true
  22486. */
  22487. this.isCubeTexture = true;
  22488. }
  22489. /**
  22490. * Alias for {@link CubeDepthTexture#image}.
  22491. *
  22492. * @type {Array<Image>}
  22493. */
  22494. get images() {
  22495. return this.image;
  22496. }
  22497. set images( value ) {
  22498. this.image = value;
  22499. }
  22500. }
  22501. /**
  22502. * Represents a texture created externally with the same renderer context.
  22503. *
  22504. * This may be a texture from a protected media stream, device camera feed,
  22505. * or other data feeds like a depth sensor.
  22506. *
  22507. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22508. * the {@link WebGPURenderer} WebGPU backend.
  22509. *
  22510. * @augments Texture
  22511. */
  22512. class ExternalTexture extends Texture {
  22513. /**
  22514. * Creates a new raw texture.
  22515. *
  22516. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22517. */
  22518. constructor( sourceTexture = null ) {
  22519. super();
  22520. /**
  22521. * The external source texture.
  22522. *
  22523. * @type {?(WebGLTexture|GPUTexture)}
  22524. * @default null
  22525. */
  22526. this.sourceTexture = sourceTexture;
  22527. /**
  22528. * This flag can be used for type testing.
  22529. *
  22530. * @type {boolean}
  22531. * @readonly
  22532. * @default true
  22533. */
  22534. this.isExternalTexture = true;
  22535. }
  22536. copy( source ) {
  22537. super.copy( source );
  22538. this.sourceTexture = source.sourceTexture;
  22539. return this;
  22540. }
  22541. }
  22542. /**
  22543. * A geometry class for representing a capsule.
  22544. *
  22545. * ```js
  22546. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22547. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22548. * const capsule = new THREE.Mesh( geometry, material );
  22549. * scene.add( capsule );
  22550. * ```
  22551. *
  22552. * @augments BufferGeometry
  22553. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22554. */
  22555. class CapsuleGeometry extends BufferGeometry {
  22556. /**
  22557. * Constructs a new capsule geometry.
  22558. *
  22559. * @param {number} [radius=1] - Radius of the capsule.
  22560. * @param {number} [height=1] - Height of the middle section.
  22561. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22562. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22563. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22564. */
  22565. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22566. super();
  22567. this.type = 'CapsuleGeometry';
  22568. /**
  22569. * Holds the constructor parameters that have been
  22570. * used to generate the geometry. Any modification
  22571. * after instantiation does not change the geometry.
  22572. *
  22573. * @type {Object}
  22574. */
  22575. this.parameters = {
  22576. radius: radius,
  22577. height: height,
  22578. capSegments: capSegments,
  22579. radialSegments: radialSegments,
  22580. heightSegments: heightSegments,
  22581. };
  22582. height = Math.max( 0, height );
  22583. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22584. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22585. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22586. // buffers
  22587. const indices = [];
  22588. const vertices = [];
  22589. const normals = [];
  22590. const uvs = [];
  22591. // helper variables
  22592. const halfHeight = height / 2;
  22593. const capArcLength = ( Math.PI / 2 ) * radius;
  22594. const cylinderPartLength = height;
  22595. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22596. const numVerticalSegments = capSegments * 2 + heightSegments;
  22597. const verticesPerRow = radialSegments + 1;
  22598. const normal = new Vector3();
  22599. const vertex = new Vector3();
  22600. // generate vertices, normals, and uvs
  22601. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22602. let currentArcLength = 0;
  22603. let profileY = 0;
  22604. let profileRadius = 0;
  22605. let normalYComponent = 0;
  22606. if ( iy <= capSegments ) {
  22607. // bottom cap
  22608. const segmentProgress = iy / capSegments;
  22609. const angle = ( segmentProgress * Math.PI ) / 2;
  22610. profileY = - halfHeight - radius * Math.cos( angle );
  22611. profileRadius = radius * Math.sin( angle );
  22612. normalYComponent = - radius * Math.cos( angle );
  22613. currentArcLength = segmentProgress * capArcLength;
  22614. } else if ( iy <= capSegments + heightSegments ) {
  22615. // middle section
  22616. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22617. profileY = - halfHeight + segmentProgress * height;
  22618. profileRadius = radius;
  22619. normalYComponent = 0;
  22620. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22621. } else {
  22622. // top cap
  22623. const segmentProgress =
  22624. ( iy - capSegments - heightSegments ) / capSegments;
  22625. const angle = ( segmentProgress * Math.PI ) / 2;
  22626. profileY = halfHeight + radius * Math.sin( angle );
  22627. profileRadius = radius * Math.cos( angle );
  22628. normalYComponent = radius * Math.sin( angle );
  22629. currentArcLength =
  22630. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22631. }
  22632. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22633. // special case for the poles
  22634. let uOffset = 0;
  22635. if ( iy === 0 ) {
  22636. uOffset = 0.5 / radialSegments;
  22637. } else if ( iy === numVerticalSegments ) {
  22638. uOffset = -0.5 / radialSegments;
  22639. }
  22640. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22641. const u = ix / radialSegments;
  22642. const theta = u * Math.PI * 2;
  22643. const sinTheta = Math.sin( theta );
  22644. const cosTheta = Math.cos( theta );
  22645. // vertex
  22646. vertex.x = - profileRadius * cosTheta;
  22647. vertex.y = profileY;
  22648. vertex.z = profileRadius * sinTheta;
  22649. vertices.push( vertex.x, vertex.y, vertex.z );
  22650. // normal
  22651. normal.set(
  22652. - profileRadius * cosTheta,
  22653. normalYComponent,
  22654. profileRadius * sinTheta
  22655. );
  22656. normal.normalize();
  22657. normals.push( normal.x, normal.y, normal.z );
  22658. // uv
  22659. uvs.push( u + uOffset, v );
  22660. }
  22661. if ( iy > 0 ) {
  22662. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22663. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22664. const i1 = prevIndexRow + ix;
  22665. const i2 = prevIndexRow + ix + 1;
  22666. const i3 = iy * verticesPerRow + ix;
  22667. const i4 = iy * verticesPerRow + ix + 1;
  22668. indices.push( i1, i2, i3 );
  22669. indices.push( i2, i4, i3 );
  22670. }
  22671. }
  22672. }
  22673. // build geometry
  22674. this.setIndex( indices );
  22675. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22676. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22677. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22678. }
  22679. copy( source ) {
  22680. super.copy( source );
  22681. this.parameters = Object.assign( {}, source.parameters );
  22682. return this;
  22683. }
  22684. /**
  22685. * Factory method for creating an instance of this class from the given
  22686. * JSON object.
  22687. *
  22688. * @param {Object} data - A JSON object representing the serialized geometry.
  22689. * @return {CapsuleGeometry} A new instance.
  22690. */
  22691. static fromJSON( data ) {
  22692. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22693. }
  22694. }
  22695. /**
  22696. * A simple shape of Euclidean geometry. It is constructed from a
  22697. * number of triangular segments that are oriented around a central point and
  22698. * extend as far out as a given radius. It is built counter-clockwise from a
  22699. * start angle and a given central angle. It can also be used to create
  22700. * regular polygons, where the number of segments determines the number of
  22701. * sides.
  22702. *
  22703. * ```js
  22704. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22705. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22706. * const circle = new THREE.Mesh( geometry, material );
  22707. * scene.add( circle )
  22708. * ```
  22709. *
  22710. * @augments BufferGeometry
  22711. * @demo scenes/geometry-browser.html#CircleGeometry
  22712. */
  22713. class CircleGeometry extends BufferGeometry {
  22714. /**
  22715. * Constructs a new circle geometry.
  22716. *
  22717. * @param {number} [radius=1] - Radius of the circle.
  22718. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22719. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22720. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22721. * of the circular sector in radians. The default value results in a complete circle.
  22722. */
  22723. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22724. super();
  22725. this.type = 'CircleGeometry';
  22726. /**
  22727. * Holds the constructor parameters that have been
  22728. * used to generate the geometry. Any modification
  22729. * after instantiation does not change the geometry.
  22730. *
  22731. * @type {Object}
  22732. */
  22733. this.parameters = {
  22734. radius: radius,
  22735. segments: segments,
  22736. thetaStart: thetaStart,
  22737. thetaLength: thetaLength
  22738. };
  22739. segments = Math.max( 3, segments );
  22740. // buffers
  22741. const indices = [];
  22742. const vertices = [];
  22743. const normals = [];
  22744. const uvs = [];
  22745. // helper variables
  22746. const vertex = new Vector3();
  22747. const uv = new Vector2();
  22748. // center point
  22749. vertices.push( 0, 0, 0 );
  22750. normals.push( 0, 0, 1 );
  22751. uvs.push( 0.5, 0.5 );
  22752. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22753. const segment = thetaStart + s / segments * thetaLength;
  22754. // vertex
  22755. vertex.x = radius * Math.cos( segment );
  22756. vertex.y = radius * Math.sin( segment );
  22757. vertices.push( vertex.x, vertex.y, vertex.z );
  22758. // normal
  22759. normals.push( 0, 0, 1 );
  22760. // uvs
  22761. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22762. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22763. uvs.push( uv.x, uv.y );
  22764. }
  22765. // indices
  22766. for ( let i = 1; i <= segments; i ++ ) {
  22767. indices.push( i, i + 1, 0 );
  22768. }
  22769. // build geometry
  22770. this.setIndex( indices );
  22771. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22772. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22773. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22774. }
  22775. copy( source ) {
  22776. super.copy( source );
  22777. this.parameters = Object.assign( {}, source.parameters );
  22778. return this;
  22779. }
  22780. /**
  22781. * Factory method for creating an instance of this class from the given
  22782. * JSON object.
  22783. *
  22784. * @param {Object} data - A JSON object representing the serialized geometry.
  22785. * @return {CircleGeometry} A new instance.
  22786. */
  22787. static fromJSON( data ) {
  22788. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22789. }
  22790. }
  22791. /**
  22792. * A geometry class for representing a cylinder.
  22793. *
  22794. * ```js
  22795. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22796. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22797. * const cylinder = new THREE.Mesh( geometry, material );
  22798. * scene.add( cylinder );
  22799. * ```
  22800. *
  22801. * @augments BufferGeometry
  22802. * @demo scenes/geometry-browser.html#CylinderGeometry
  22803. */
  22804. class CylinderGeometry extends BufferGeometry {
  22805. /**
  22806. * Constructs a new cylinder geometry.
  22807. *
  22808. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22809. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22810. * @param {number} [height=1] - Height of the cylinder.
  22811. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22812. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22813. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22814. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22815. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22816. * The default value results in a complete cylinder.
  22817. */
  22818. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22819. super();
  22820. this.type = 'CylinderGeometry';
  22821. /**
  22822. * Holds the constructor parameters that have been
  22823. * used to generate the geometry. Any modification
  22824. * after instantiation does not change the geometry.
  22825. *
  22826. * @type {Object}
  22827. */
  22828. this.parameters = {
  22829. radiusTop: radiusTop,
  22830. radiusBottom: radiusBottom,
  22831. height: height,
  22832. radialSegments: radialSegments,
  22833. heightSegments: heightSegments,
  22834. openEnded: openEnded,
  22835. thetaStart: thetaStart,
  22836. thetaLength: thetaLength
  22837. };
  22838. const scope = this;
  22839. radialSegments = Math.floor( radialSegments );
  22840. heightSegments = Math.floor( heightSegments );
  22841. // buffers
  22842. const indices = [];
  22843. const vertices = [];
  22844. const normals = [];
  22845. const uvs = [];
  22846. // helper variables
  22847. let index = 0;
  22848. const indexArray = [];
  22849. const halfHeight = height / 2;
  22850. let groupStart = 0;
  22851. // generate geometry
  22852. generateTorso();
  22853. if ( openEnded === false ) {
  22854. if ( radiusTop > 0 ) generateCap( true );
  22855. if ( radiusBottom > 0 ) generateCap( false );
  22856. }
  22857. // build geometry
  22858. this.setIndex( indices );
  22859. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22860. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22861. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22862. function generateTorso() {
  22863. const normal = new Vector3();
  22864. const vertex = new Vector3();
  22865. let groupCount = 0;
  22866. // this will be used to calculate the normal
  22867. const slope = ( radiusBottom - radiusTop ) / height;
  22868. // generate vertices, normals and uvs
  22869. for ( let y = 0; y <= heightSegments; y ++ ) {
  22870. const indexRow = [];
  22871. const v = y / heightSegments;
  22872. // calculate the radius of the current row
  22873. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22874. for ( let x = 0; x <= radialSegments; x ++ ) {
  22875. const u = x / radialSegments;
  22876. const theta = u * thetaLength + thetaStart;
  22877. const sinTheta = Math.sin( theta );
  22878. const cosTheta = Math.cos( theta );
  22879. // vertex
  22880. vertex.x = radius * sinTheta;
  22881. vertex.y = - v * height + halfHeight;
  22882. vertex.z = radius * cosTheta;
  22883. vertices.push( vertex.x, vertex.y, vertex.z );
  22884. // normal
  22885. normal.set( sinTheta, slope, cosTheta ).normalize();
  22886. normals.push( normal.x, normal.y, normal.z );
  22887. // uv
  22888. uvs.push( u, 1 - v );
  22889. // save index of vertex in respective row
  22890. indexRow.push( index ++ );
  22891. }
  22892. // now save vertices of the row in our index array
  22893. indexArray.push( indexRow );
  22894. }
  22895. // generate indices
  22896. for ( let x = 0; x < radialSegments; x ++ ) {
  22897. for ( let y = 0; y < heightSegments; y ++ ) {
  22898. // we use the index array to access the correct indices
  22899. const a = indexArray[ y ][ x ];
  22900. const b = indexArray[ y + 1 ][ x ];
  22901. const c = indexArray[ y + 1 ][ x + 1 ];
  22902. const d = indexArray[ y ][ x + 1 ];
  22903. // faces
  22904. if ( radiusTop > 0 || y !== 0 ) {
  22905. indices.push( a, b, d );
  22906. groupCount += 3;
  22907. }
  22908. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22909. indices.push( b, c, d );
  22910. groupCount += 3;
  22911. }
  22912. }
  22913. }
  22914. // add a group to the geometry. this will ensure multi material support
  22915. scope.addGroup( groupStart, groupCount, 0 );
  22916. // calculate new start value for groups
  22917. groupStart += groupCount;
  22918. }
  22919. function generateCap( top ) {
  22920. // save the index of the first center vertex
  22921. const centerIndexStart = index;
  22922. const uv = new Vector2();
  22923. const vertex = new Vector3();
  22924. let groupCount = 0;
  22925. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22926. const sign = ( top === true ) ? 1 : -1;
  22927. // first we generate the center vertex data of the cap.
  22928. // because the geometry needs one set of uvs per face,
  22929. // we must generate a center vertex per face/segment
  22930. for ( let x = 1; x <= radialSegments; x ++ ) {
  22931. // vertex
  22932. vertices.push( 0, halfHeight * sign, 0 );
  22933. // normal
  22934. normals.push( 0, sign, 0 );
  22935. // uv
  22936. uvs.push( 0.5, 0.5 );
  22937. // increase index
  22938. index ++;
  22939. }
  22940. // save the index of the last center vertex
  22941. const centerIndexEnd = index;
  22942. // now we generate the surrounding vertices, normals and uvs
  22943. for ( let x = 0; x <= radialSegments; x ++ ) {
  22944. const u = x / radialSegments;
  22945. const theta = u * thetaLength + thetaStart;
  22946. const cosTheta = Math.cos( theta );
  22947. const sinTheta = Math.sin( theta );
  22948. // vertex
  22949. vertex.x = radius * sinTheta;
  22950. vertex.y = halfHeight * sign;
  22951. vertex.z = radius * cosTheta;
  22952. vertices.push( vertex.x, vertex.y, vertex.z );
  22953. // normal
  22954. normals.push( 0, sign, 0 );
  22955. // uv
  22956. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22957. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22958. uvs.push( uv.x, uv.y );
  22959. // increase index
  22960. index ++;
  22961. }
  22962. // generate indices
  22963. for ( let x = 0; x < radialSegments; x ++ ) {
  22964. const c = centerIndexStart + x;
  22965. const i = centerIndexEnd + x;
  22966. if ( top === true ) {
  22967. // face top
  22968. indices.push( i, i + 1, c );
  22969. } else {
  22970. // face bottom
  22971. indices.push( i + 1, i, c );
  22972. }
  22973. groupCount += 3;
  22974. }
  22975. // add a group to the geometry. this will ensure multi material support
  22976. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22977. // calculate new start value for groups
  22978. groupStart += groupCount;
  22979. }
  22980. }
  22981. copy( source ) {
  22982. super.copy( source );
  22983. this.parameters = Object.assign( {}, source.parameters );
  22984. return this;
  22985. }
  22986. /**
  22987. * Factory method for creating an instance of this class from the given
  22988. * JSON object.
  22989. *
  22990. * @param {Object} data - A JSON object representing the serialized geometry.
  22991. * @return {CylinderGeometry} A new instance.
  22992. */
  22993. static fromJSON( data ) {
  22994. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22995. }
  22996. }
  22997. /**
  22998. * A geometry class for representing a cone.
  22999. *
  23000. * ```js
  23001. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  23002. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23003. * const cone = new THREE.Mesh(geometry, material );
  23004. * scene.add( cone );
  23005. * ```
  23006. *
  23007. * @augments CylinderGeometry
  23008. * @demo scenes/geometry-browser.html#ConeGeometry
  23009. */
  23010. class ConeGeometry extends CylinderGeometry {
  23011. /**
  23012. * Constructs a new cone geometry.
  23013. *
  23014. * @param {number} [radius=1] - Radius of the cone base.
  23015. * @param {number} [height=1] - Height of the cone.
  23016. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  23017. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  23018. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  23019. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  23020. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  23021. * The default value results in a complete cone.
  23022. */
  23023. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  23024. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  23025. this.type = 'ConeGeometry';
  23026. /**
  23027. * Holds the constructor parameters that have been
  23028. * used to generate the geometry. Any modification
  23029. * after instantiation does not change the geometry.
  23030. *
  23031. * @type {Object}
  23032. */
  23033. this.parameters = {
  23034. radius: radius,
  23035. height: height,
  23036. radialSegments: radialSegments,
  23037. heightSegments: heightSegments,
  23038. openEnded: openEnded,
  23039. thetaStart: thetaStart,
  23040. thetaLength: thetaLength
  23041. };
  23042. }
  23043. /**
  23044. * Factory method for creating an instance of this class from the given
  23045. * JSON object.
  23046. *
  23047. * @param {Object} data - A JSON object representing the serialized geometry.
  23048. * @return {ConeGeometry} A new instance.
  23049. */
  23050. static fromJSON( data ) {
  23051. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  23052. }
  23053. }
  23054. /**
  23055. * A polyhedron is a solid in three dimensions with flat faces. This class
  23056. * will take an array of vertices, project them onto a sphere, and then
  23057. * divide them up to the desired level of detail.
  23058. *
  23059. * @augments BufferGeometry
  23060. */
  23061. class PolyhedronGeometry extends BufferGeometry {
  23062. /**
  23063. * Constructs a new polyhedron geometry.
  23064. *
  23065. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  23066. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  23067. * @param {number} [radius=1] - The radius of the shape.
  23068. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  23069. */
  23070. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  23071. super();
  23072. this.type = 'PolyhedronGeometry';
  23073. /**
  23074. * Holds the constructor parameters that have been
  23075. * used to generate the geometry. Any modification
  23076. * after instantiation does not change the geometry.
  23077. *
  23078. * @type {Object}
  23079. */
  23080. this.parameters = {
  23081. vertices: vertices,
  23082. indices: indices,
  23083. radius: radius,
  23084. detail: detail
  23085. };
  23086. // default buffer data
  23087. const vertexBuffer = [];
  23088. const uvBuffer = [];
  23089. // the subdivision creates the vertex buffer data
  23090. subdivide( detail );
  23091. // all vertices should lie on a conceptual sphere with a given radius
  23092. applyRadius( radius );
  23093. // finally, create the uv data
  23094. generateUVs();
  23095. // build non-indexed geometry
  23096. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  23097. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  23098. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  23099. if ( detail === 0 ) {
  23100. this.computeVertexNormals(); // flat normals
  23101. } else {
  23102. this.normalizeNormals(); // smooth normals
  23103. }
  23104. // helper functions
  23105. function subdivide( detail ) {
  23106. const a = new Vector3();
  23107. const b = new Vector3();
  23108. const c = new Vector3();
  23109. // iterate over all faces and apply a subdivision with the given detail value
  23110. for ( let i = 0; i < indices.length; i += 3 ) {
  23111. // get the vertices of the face
  23112. getVertexByIndex( indices[ i + 0 ], a );
  23113. getVertexByIndex( indices[ i + 1 ], b );
  23114. getVertexByIndex( indices[ i + 2 ], c );
  23115. // perform subdivision
  23116. subdivideFace( a, b, c, detail );
  23117. }
  23118. }
  23119. function subdivideFace( a, b, c, detail ) {
  23120. const cols = detail + 1;
  23121. // we use this multidimensional array as a data structure for creating the subdivision
  23122. const v = [];
  23123. // construct all of the vertices for this subdivision
  23124. for ( let i = 0; i <= cols; i ++ ) {
  23125. v[ i ] = [];
  23126. const aj = a.clone().lerp( c, i / cols );
  23127. const bj = b.clone().lerp( c, i / cols );
  23128. const rows = cols - i;
  23129. for ( let j = 0; j <= rows; j ++ ) {
  23130. if ( j === 0 && i === cols ) {
  23131. v[ i ][ j ] = aj;
  23132. } else {
  23133. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  23134. }
  23135. }
  23136. }
  23137. // construct all of the faces
  23138. for ( let i = 0; i < cols; i ++ ) {
  23139. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23140. const k = Math.floor( j / 2 );
  23141. if ( j % 2 === 0 ) {
  23142. pushVertex( v[ i ][ k + 1 ] );
  23143. pushVertex( v[ i + 1 ][ k ] );
  23144. pushVertex( v[ i ][ k ] );
  23145. } else {
  23146. pushVertex( v[ i ][ k + 1 ] );
  23147. pushVertex( v[ i + 1 ][ k + 1 ] );
  23148. pushVertex( v[ i + 1 ][ k ] );
  23149. }
  23150. }
  23151. }
  23152. }
  23153. function applyRadius( radius ) {
  23154. const vertex = new Vector3();
  23155. // iterate over the entire buffer and apply the radius to each vertex
  23156. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23157. vertex.x = vertexBuffer[ i + 0 ];
  23158. vertex.y = vertexBuffer[ i + 1 ];
  23159. vertex.z = vertexBuffer[ i + 2 ];
  23160. vertex.normalize().multiplyScalar( radius );
  23161. vertexBuffer[ i + 0 ] = vertex.x;
  23162. vertexBuffer[ i + 1 ] = vertex.y;
  23163. vertexBuffer[ i + 2 ] = vertex.z;
  23164. }
  23165. }
  23166. function generateUVs() {
  23167. const vertex = new Vector3();
  23168. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  23169. vertex.x = vertexBuffer[ i + 0 ];
  23170. vertex.y = vertexBuffer[ i + 1 ];
  23171. vertex.z = vertexBuffer[ i + 2 ];
  23172. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  23173. const v = inclination( vertex ) / Math.PI + 0.5;
  23174. uvBuffer.push( u, 1 - v );
  23175. }
  23176. correctUVs();
  23177. correctSeam();
  23178. }
  23179. function correctSeam() {
  23180. // handle case when face straddles the seam, see #3269
  23181. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  23182. // uv data of a single face
  23183. const x0 = uvBuffer[ i + 0 ];
  23184. const x1 = uvBuffer[ i + 2 ];
  23185. const x2 = uvBuffer[ i + 4 ];
  23186. const max = Math.max( x0, x1, x2 );
  23187. const min = Math.min( x0, x1, x2 );
  23188. // 0.9 is somewhat arbitrary
  23189. if ( max > 0.9 && min < 0.1 ) {
  23190. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  23191. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  23192. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  23193. }
  23194. }
  23195. }
  23196. function pushVertex( vertex ) {
  23197. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  23198. }
  23199. function getVertexByIndex( index, vertex ) {
  23200. const stride = index * 3;
  23201. vertex.x = vertices[ stride + 0 ];
  23202. vertex.y = vertices[ stride + 1 ];
  23203. vertex.z = vertices[ stride + 2 ];
  23204. }
  23205. function correctUVs() {
  23206. const a = new Vector3();
  23207. const b = new Vector3();
  23208. const c = new Vector3();
  23209. const centroid = new Vector3();
  23210. const uvA = new Vector2();
  23211. const uvB = new Vector2();
  23212. const uvC = new Vector2();
  23213. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23214. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23215. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23216. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23217. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23218. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23219. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23220. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23221. const azi = azimuth( centroid );
  23222. correctUV( uvA, j + 0, a, azi );
  23223. correctUV( uvB, j + 2, b, azi );
  23224. correctUV( uvC, j + 4, c, azi );
  23225. }
  23226. }
  23227. function correctUV( uv, stride, vector, azimuth ) {
  23228. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23229. uvBuffer[ stride ] = uv.x - 1;
  23230. }
  23231. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23232. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23233. }
  23234. }
  23235. // Angle around the Y axis, counter-clockwise when looking from above.
  23236. function azimuth( vector ) {
  23237. return Math.atan2( vector.z, - vector.x );
  23238. }
  23239. // Angle above the XZ plane.
  23240. function inclination( vector ) {
  23241. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23242. }
  23243. }
  23244. copy( source ) {
  23245. super.copy( source );
  23246. this.parameters = Object.assign( {}, source.parameters );
  23247. return this;
  23248. }
  23249. /**
  23250. * Factory method for creating an instance of this class from the given
  23251. * JSON object.
  23252. *
  23253. * @param {Object} data - A JSON object representing the serialized geometry.
  23254. * @return {PolyhedronGeometry} A new instance.
  23255. */
  23256. static fromJSON( data ) {
  23257. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23258. }
  23259. }
  23260. /**
  23261. * A geometry class for representing a dodecahedron.
  23262. *
  23263. * ```js
  23264. * const geometry = new THREE.DodecahedronGeometry();
  23265. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23266. * const dodecahedron = new THREE.Mesh( geometry, material );
  23267. * scene.add( dodecahedron );
  23268. * ```
  23269. *
  23270. * @augments PolyhedronGeometry
  23271. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23272. */
  23273. class DodecahedronGeometry extends PolyhedronGeometry {
  23274. /**
  23275. * Constructs a new dodecahedron geometry.
  23276. *
  23277. * @param {number} [radius=1] - Radius of the dodecahedron.
  23278. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23279. */
  23280. constructor( radius = 1, detail = 0 ) {
  23281. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23282. const r = 1 / t;
  23283. const vertices = [
  23284. // (±1, ±1, ±1)
  23285. -1, -1, -1, -1, -1, 1,
  23286. -1, 1, -1, -1, 1, 1,
  23287. 1, -1, -1, 1, -1, 1,
  23288. 1, 1, -1, 1, 1, 1,
  23289. // (0, ±1/φ, ±φ)
  23290. 0, - r, - t, 0, - r, t,
  23291. 0, r, - t, 0, r, t,
  23292. // (±1/φ, ±φ, 0)
  23293. - r, - t, 0, - r, t, 0,
  23294. r, - t, 0, r, t, 0,
  23295. // (±φ, 0, ±1/φ)
  23296. - t, 0, - r, t, 0, - r,
  23297. - t, 0, r, t, 0, r
  23298. ];
  23299. const indices = [
  23300. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23301. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23302. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23303. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23304. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23305. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23306. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23307. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23308. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23309. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23310. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23311. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23312. ];
  23313. super( vertices, indices, radius, detail );
  23314. this.type = 'DodecahedronGeometry';
  23315. /**
  23316. * Holds the constructor parameters that have been
  23317. * used to generate the geometry. Any modification
  23318. * after instantiation does not change the geometry.
  23319. *
  23320. * @type {Object}
  23321. */
  23322. this.parameters = {
  23323. radius: radius,
  23324. detail: detail
  23325. };
  23326. }
  23327. /**
  23328. * Factory method for creating an instance of this class from the given
  23329. * JSON object.
  23330. *
  23331. * @param {Object} data - A JSON object representing the serialized geometry.
  23332. * @return {DodecahedronGeometry} A new instance.
  23333. */
  23334. static fromJSON( data ) {
  23335. return new DodecahedronGeometry( data.radius, data.detail );
  23336. }
  23337. }
  23338. const _v0$1 = /*@__PURE__*/ new Vector3();
  23339. const _v1$1 = /*@__PURE__*/ new Vector3();
  23340. const _normal = /*@__PURE__*/ new Vector3();
  23341. const _triangle = /*@__PURE__*/ new Triangle();
  23342. /**
  23343. * Can be used as a helper object to view the edges of a geometry.
  23344. *
  23345. * ```js
  23346. * const geometry = new THREE.BoxGeometry();
  23347. * const edges = new THREE.EdgesGeometry( geometry );
  23348. * const line = new THREE.LineSegments( edges );
  23349. * scene.add( line );
  23350. * ```
  23351. *
  23352. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23353. *
  23354. * @augments BufferGeometry
  23355. */
  23356. class EdgesGeometry extends BufferGeometry {
  23357. /**
  23358. * Constructs a new edges geometry.
  23359. *
  23360. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23361. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23362. * between the face normals of the adjoining faces exceeds this value.
  23363. */
  23364. constructor( geometry = null, thresholdAngle = 1 ) {
  23365. super();
  23366. this.type = 'EdgesGeometry';
  23367. /**
  23368. * Holds the constructor parameters that have been
  23369. * used to generate the geometry. Any modification
  23370. * after instantiation does not change the geometry.
  23371. *
  23372. * @type {Object}
  23373. */
  23374. this.parameters = {
  23375. geometry: geometry,
  23376. thresholdAngle: thresholdAngle
  23377. };
  23378. if ( geometry !== null ) {
  23379. const precisionPoints = 4;
  23380. const precision = Math.pow( 10, precisionPoints );
  23381. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23382. const indexAttr = geometry.getIndex();
  23383. const positionAttr = geometry.getAttribute( 'position' );
  23384. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23385. const indexArr = [ 0, 0, 0 ];
  23386. const vertKeys = [ 'a', 'b', 'c' ];
  23387. const hashes = new Array( 3 );
  23388. const edgeData = {};
  23389. const vertices = [];
  23390. for ( let i = 0; i < indexCount; i += 3 ) {
  23391. if ( indexAttr ) {
  23392. indexArr[ 0 ] = indexAttr.getX( i );
  23393. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23394. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23395. } else {
  23396. indexArr[ 0 ] = i;
  23397. indexArr[ 1 ] = i + 1;
  23398. indexArr[ 2 ] = i + 2;
  23399. }
  23400. const { a, b, c } = _triangle;
  23401. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23402. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23403. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23404. _triangle.getNormal( _normal );
  23405. // create hashes for the edge from the vertices
  23406. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23407. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23408. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23409. // skip degenerate triangles
  23410. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23411. continue;
  23412. }
  23413. // iterate over every edge
  23414. for ( let j = 0; j < 3; j ++ ) {
  23415. // get the first and next vertex making up the edge
  23416. const jNext = ( j + 1 ) % 3;
  23417. const vecHash0 = hashes[ j ];
  23418. const vecHash1 = hashes[ jNext ];
  23419. const v0 = _triangle[ vertKeys[ j ] ];
  23420. const v1 = _triangle[ vertKeys[ jNext ] ];
  23421. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23422. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23423. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23424. // if we found a sibling edge add it into the vertex array if
  23425. // it meets the angle threshold and delete the edge from the map.
  23426. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23427. vertices.push( v0.x, v0.y, v0.z );
  23428. vertices.push( v1.x, v1.y, v1.z );
  23429. }
  23430. edgeData[ reverseHash ] = null;
  23431. } else if ( ! ( hash in edgeData ) ) {
  23432. // if we've already got an edge here then skip adding a new one
  23433. edgeData[ hash ] = {
  23434. index0: indexArr[ j ],
  23435. index1: indexArr[ jNext ],
  23436. normal: _normal.clone(),
  23437. };
  23438. }
  23439. }
  23440. }
  23441. // iterate over all remaining, unmatched edges and add them to the vertex array
  23442. for ( const key in edgeData ) {
  23443. if ( edgeData[ key ] ) {
  23444. const { index0, index1 } = edgeData[ key ];
  23445. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23446. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23447. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23448. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23449. }
  23450. }
  23451. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23452. }
  23453. }
  23454. copy( source ) {
  23455. super.copy( source );
  23456. this.parameters = Object.assign( {}, source.parameters );
  23457. return this;
  23458. }
  23459. }
  23460. /**
  23461. * An abstract base class for creating an analytic curve object that contains methods
  23462. * for interpolation.
  23463. *
  23464. * @abstract
  23465. */
  23466. class Curve {
  23467. /**
  23468. * Constructs a new curve.
  23469. */
  23470. constructor() {
  23471. /**
  23472. * The type property is used for detecting the object type
  23473. * in context of serialization/deserialization.
  23474. *
  23475. * @type {string}
  23476. * @readonly
  23477. */
  23478. this.type = 'Curve';
  23479. /**
  23480. * This value determines the amount of divisions when calculating the
  23481. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23482. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23483. * recommended to increase the value of this property if the curve is very large.
  23484. *
  23485. * @type {number}
  23486. * @default 200
  23487. */
  23488. this.arcLengthDivisions = 200;
  23489. /**
  23490. * Must be set to `true` if the curve parameters have changed.
  23491. *
  23492. * @type {boolean}
  23493. * @default false
  23494. */
  23495. this.needsUpdate = false;
  23496. /**
  23497. * An internal cache that holds precomputed curve length values.
  23498. *
  23499. * @private
  23500. * @type {?Array<number>}
  23501. * @default null
  23502. */
  23503. this.cacheArcLengths = null;
  23504. }
  23505. /**
  23506. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23507. * for the given interpolation factor.
  23508. *
  23509. * @abstract
  23510. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23511. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23512. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23513. */
  23514. getPoint( /* t, optionalTarget */ ) {
  23515. warn( 'Curve: .getPoint() not implemented.' );
  23516. }
  23517. /**
  23518. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23519. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23520. * of the curve which equidistant samples.
  23521. *
  23522. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23523. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23524. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23525. */
  23526. getPointAt( u, optionalTarget ) {
  23527. const t = this.getUtoTmapping( u );
  23528. return this.getPoint( t, optionalTarget );
  23529. }
  23530. /**
  23531. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23532. * the curve shape.
  23533. *
  23534. * @param {number} [divisions=5] - The number of divisions.
  23535. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23536. */
  23537. getPoints( divisions = 5 ) {
  23538. const points = [];
  23539. for ( let d = 0; d <= divisions; d ++ ) {
  23540. points.push( this.getPoint( d / divisions ) );
  23541. }
  23542. return points;
  23543. }
  23544. // Get sequence of points using getPointAt( u )
  23545. /**
  23546. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23547. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23548. * curve.
  23549. *
  23550. * @param {number} [divisions=5] - The number of divisions.
  23551. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23552. */
  23553. getSpacedPoints( divisions = 5 ) {
  23554. const points = [];
  23555. for ( let d = 0; d <= divisions; d ++ ) {
  23556. points.push( this.getPointAt( d / divisions ) );
  23557. }
  23558. return points;
  23559. }
  23560. /**
  23561. * Returns the total arc length of the curve.
  23562. *
  23563. * @return {number} The length of the curve.
  23564. */
  23565. getLength() {
  23566. const lengths = this.getLengths();
  23567. return lengths[ lengths.length - 1 ];
  23568. }
  23569. /**
  23570. * Returns an array of cumulative segment lengths of the curve.
  23571. *
  23572. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23573. * @return {Array<number>} An array holding the cumulative segment lengths.
  23574. */
  23575. getLengths( divisions = this.arcLengthDivisions ) {
  23576. if ( this.cacheArcLengths &&
  23577. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23578. ! this.needsUpdate ) {
  23579. return this.cacheArcLengths;
  23580. }
  23581. this.needsUpdate = false;
  23582. const cache = [];
  23583. let current, last = this.getPoint( 0 );
  23584. let sum = 0;
  23585. cache.push( 0 );
  23586. for ( let p = 1; p <= divisions; p ++ ) {
  23587. current = this.getPoint( p / divisions );
  23588. sum += current.distanceTo( last );
  23589. cache.push( sum );
  23590. last = current;
  23591. }
  23592. this.cacheArcLengths = cache;
  23593. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23594. }
  23595. /**
  23596. * Update the cumulative segment distance cache. The method must be called
  23597. * every time curve parameters are changed. If an updated curve is part of a
  23598. * composed curve like {@link CurvePath}, this method must be called on the
  23599. * composed curve, too.
  23600. */
  23601. updateArcLengths() {
  23602. this.needsUpdate = true;
  23603. this.getLengths();
  23604. }
  23605. /**
  23606. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23607. * interpolation factor in the same range that can be ued to sample equidistant points
  23608. * from a curve.
  23609. *
  23610. * @param {number} u - The interpolation factor.
  23611. * @param {?number} distance - An optional distance on the curve.
  23612. * @return {number} The updated interpolation factor.
  23613. */
  23614. getUtoTmapping( u, distance = null ) {
  23615. const arcLengths = this.getLengths();
  23616. let i = 0;
  23617. const il = arcLengths.length;
  23618. let targetArcLength; // The targeted u distance value to get
  23619. if ( distance ) {
  23620. targetArcLength = distance;
  23621. } else {
  23622. targetArcLength = u * arcLengths[ il - 1 ];
  23623. }
  23624. // binary search for the index with largest value smaller than target u distance
  23625. let low = 0, high = il - 1, comparison;
  23626. while ( low <= high ) {
  23627. 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
  23628. comparison = arcLengths[ i ] - targetArcLength;
  23629. if ( comparison < 0 ) {
  23630. low = i + 1;
  23631. } else if ( comparison > 0 ) {
  23632. high = i - 1;
  23633. } else {
  23634. high = i;
  23635. break;
  23636. // DONE
  23637. }
  23638. }
  23639. i = high;
  23640. if ( arcLengths[ i ] === targetArcLength ) {
  23641. return i / ( il - 1 );
  23642. }
  23643. // we could get finer grain at lengths, or use simple interpolation between two points
  23644. const lengthBefore = arcLengths[ i ];
  23645. const lengthAfter = arcLengths[ i + 1 ];
  23646. const segmentLength = lengthAfter - lengthBefore;
  23647. // determine where we are between the 'before' and 'after' points
  23648. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23649. // add that fractional amount to t
  23650. const t = ( i + segmentFraction ) / ( il - 1 );
  23651. return t;
  23652. }
  23653. /**
  23654. * Returns a unit vector tangent for the given interpolation factor.
  23655. * If the derived curve does not implement its tangent derivation,
  23656. * two points a small delta apart will be used to find its gradient
  23657. * which seems to give a reasonable approximation.
  23658. *
  23659. * @param {number} t - The interpolation factor.
  23660. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23661. * @return {(Vector2|Vector3)} The tangent vector.
  23662. */
  23663. getTangent( t, optionalTarget ) {
  23664. const delta = 0.0001;
  23665. let t1 = t - delta;
  23666. let t2 = t + delta;
  23667. // Capping in case of danger
  23668. if ( t1 < 0 ) t1 = 0;
  23669. if ( t2 > 1 ) t2 = 1;
  23670. const pt1 = this.getPoint( t1 );
  23671. const pt2 = this.getPoint( t2 );
  23672. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23673. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23674. return tangent;
  23675. }
  23676. /**
  23677. * Same as {@link Curve#getTangent} but with equidistant samples.
  23678. *
  23679. * @param {number} u - The interpolation factor.
  23680. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23681. * @return {(Vector2|Vector3)} The tangent vector.
  23682. * @see {@link Curve#getPointAt}
  23683. */
  23684. getTangentAt( u, optionalTarget ) {
  23685. const t = this.getUtoTmapping( u );
  23686. return this.getTangent( t, optionalTarget );
  23687. }
  23688. /**
  23689. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23690. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23691. *
  23692. * @param {number} segments - The number of segments.
  23693. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23694. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23695. */
  23696. computeFrenetFrames( segments, closed = false ) {
  23697. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23698. const normal = new Vector3();
  23699. const tangents = [];
  23700. const normals = [];
  23701. const binormals = [];
  23702. const vec = new Vector3();
  23703. const mat = new Matrix4();
  23704. // compute the tangent vectors for each segment on the curve
  23705. for ( let i = 0; i <= segments; i ++ ) {
  23706. const u = i / segments;
  23707. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23708. }
  23709. // select an initial normal vector perpendicular to the first tangent vector,
  23710. // and in the direction of the minimum tangent xyz component
  23711. normals[ 0 ] = new Vector3();
  23712. binormals[ 0 ] = new Vector3();
  23713. let min = Number.MAX_VALUE;
  23714. const tx = Math.abs( tangents[ 0 ].x );
  23715. const ty = Math.abs( tangents[ 0 ].y );
  23716. const tz = Math.abs( tangents[ 0 ].z );
  23717. if ( tx <= min ) {
  23718. min = tx;
  23719. normal.set( 1, 0, 0 );
  23720. }
  23721. if ( ty <= min ) {
  23722. min = ty;
  23723. normal.set( 0, 1, 0 );
  23724. }
  23725. if ( tz <= min ) {
  23726. normal.set( 0, 0, 1 );
  23727. }
  23728. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23729. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23730. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23731. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23732. for ( let i = 1; i <= segments; i ++ ) {
  23733. normals[ i ] = normals[ i - 1 ].clone();
  23734. binormals[ i ] = binormals[ i - 1 ].clone();
  23735. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23736. if ( vec.length() > Number.EPSILON ) {
  23737. vec.normalize();
  23738. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23739. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23740. }
  23741. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23742. }
  23743. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23744. if ( closed === true ) {
  23745. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23746. theta /= segments;
  23747. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23748. theta = - theta;
  23749. }
  23750. for ( let i = 1; i <= segments; i ++ ) {
  23751. // twist a little...
  23752. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23753. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23754. }
  23755. }
  23756. return {
  23757. tangents: tangents,
  23758. normals: normals,
  23759. binormals: binormals
  23760. };
  23761. }
  23762. /**
  23763. * Returns a new curve with copied values from this instance.
  23764. *
  23765. * @return {Curve} A clone of this instance.
  23766. */
  23767. clone() {
  23768. return new this.constructor().copy( this );
  23769. }
  23770. /**
  23771. * Copies the values of the given curve to this instance.
  23772. *
  23773. * @param {Curve} source - The curve to copy.
  23774. * @return {Curve} A reference to this curve.
  23775. */
  23776. copy( source ) {
  23777. this.arcLengthDivisions = source.arcLengthDivisions;
  23778. return this;
  23779. }
  23780. /**
  23781. * Serializes the curve into JSON.
  23782. *
  23783. * @return {Object} A JSON object representing the serialized curve.
  23784. * @see {@link ObjectLoader#parse}
  23785. */
  23786. toJSON() {
  23787. const data = {
  23788. metadata: {
  23789. version: 4.7,
  23790. type: 'Curve',
  23791. generator: 'Curve.toJSON'
  23792. }
  23793. };
  23794. data.arcLengthDivisions = this.arcLengthDivisions;
  23795. data.type = this.type;
  23796. return data;
  23797. }
  23798. /**
  23799. * Deserializes the curve from the given JSON.
  23800. *
  23801. * @param {Object} json - The JSON holding the serialized curve.
  23802. * @return {Curve} A reference to this curve.
  23803. */
  23804. fromJSON( json ) {
  23805. this.arcLengthDivisions = json.arcLengthDivisions;
  23806. return this;
  23807. }
  23808. }
  23809. /**
  23810. * A curve representing an ellipse.
  23811. *
  23812. * ```js
  23813. * const curve = new THREE.EllipseCurve(
  23814. * 0, 0,
  23815. * 10, 10,
  23816. * 0, 2 * Math.PI,
  23817. * false,
  23818. * 0
  23819. * );
  23820. *
  23821. * const points = curve.getPoints( 50 );
  23822. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23823. *
  23824. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23825. *
  23826. * // Create the final object to add to the scene
  23827. * const ellipse = new THREE.Line( geometry, material );
  23828. * ```
  23829. *
  23830. * @augments Curve
  23831. */
  23832. class EllipseCurve extends Curve {
  23833. /**
  23834. * Constructs a new ellipse curve.
  23835. *
  23836. * @param {number} [aX=0] - The X center of the ellipse.
  23837. * @param {number} [aY=0] - The Y center of the ellipse.
  23838. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23839. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23840. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23841. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23842. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23843. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23844. */
  23845. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23846. super();
  23847. /**
  23848. * This flag can be used for type testing.
  23849. *
  23850. * @type {boolean}
  23851. * @readonly
  23852. * @default true
  23853. */
  23854. this.isEllipseCurve = true;
  23855. this.type = 'EllipseCurve';
  23856. /**
  23857. * The X center of the ellipse.
  23858. *
  23859. * @type {number}
  23860. * @default 0
  23861. */
  23862. this.aX = aX;
  23863. /**
  23864. * The Y center of the ellipse.
  23865. *
  23866. * @type {number}
  23867. * @default 0
  23868. */
  23869. this.aY = aY;
  23870. /**
  23871. * The radius of the ellipse in the x direction.
  23872. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23873. *
  23874. * @type {number}
  23875. * @default 1
  23876. */
  23877. this.xRadius = xRadius;
  23878. /**
  23879. * The radius of the ellipse in the y direction.
  23880. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23881. *
  23882. * @type {number}
  23883. * @default 1
  23884. */
  23885. this.yRadius = yRadius;
  23886. /**
  23887. * The start angle of the curve in radians starting from the positive X axis.
  23888. *
  23889. * @type {number}
  23890. * @default 0
  23891. */
  23892. this.aStartAngle = aStartAngle;
  23893. /**
  23894. * The end angle of the curve in radians starting from the positive X axis.
  23895. *
  23896. * @type {number}
  23897. * @default Math.PI*2
  23898. */
  23899. this.aEndAngle = aEndAngle;
  23900. /**
  23901. * Whether the ellipse is drawn clockwise or not.
  23902. *
  23903. * @type {boolean}
  23904. * @default false
  23905. */
  23906. this.aClockwise = aClockwise;
  23907. /**
  23908. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23909. *
  23910. * @type {number}
  23911. * @default 0
  23912. */
  23913. this.aRotation = aRotation;
  23914. }
  23915. /**
  23916. * Returns a point on the curve.
  23917. *
  23918. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23919. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23920. * @return {Vector2} The position on the curve.
  23921. */
  23922. getPoint( t, optionalTarget = new Vector2() ) {
  23923. const point = optionalTarget;
  23924. const twoPi = Math.PI * 2;
  23925. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23926. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23927. // ensures that deltaAngle is 0 .. 2 PI
  23928. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23929. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23930. if ( deltaAngle < Number.EPSILON ) {
  23931. if ( samePoints ) {
  23932. deltaAngle = 0;
  23933. } else {
  23934. deltaAngle = twoPi;
  23935. }
  23936. }
  23937. if ( this.aClockwise === true && ! samePoints ) {
  23938. if ( deltaAngle === twoPi ) {
  23939. deltaAngle = - twoPi;
  23940. } else {
  23941. deltaAngle = deltaAngle - twoPi;
  23942. }
  23943. }
  23944. const angle = this.aStartAngle + t * deltaAngle;
  23945. let x = this.aX + this.xRadius * Math.cos( angle );
  23946. let y = this.aY + this.yRadius * Math.sin( angle );
  23947. if ( this.aRotation !== 0 ) {
  23948. const cos = Math.cos( this.aRotation );
  23949. const sin = Math.sin( this.aRotation );
  23950. const tx = x - this.aX;
  23951. const ty = y - this.aY;
  23952. // Rotate the point about the center of the ellipse.
  23953. x = tx * cos - ty * sin + this.aX;
  23954. y = tx * sin + ty * cos + this.aY;
  23955. }
  23956. return point.set( x, y );
  23957. }
  23958. copy( source ) {
  23959. super.copy( source );
  23960. this.aX = source.aX;
  23961. this.aY = source.aY;
  23962. this.xRadius = source.xRadius;
  23963. this.yRadius = source.yRadius;
  23964. this.aStartAngle = source.aStartAngle;
  23965. this.aEndAngle = source.aEndAngle;
  23966. this.aClockwise = source.aClockwise;
  23967. this.aRotation = source.aRotation;
  23968. return this;
  23969. }
  23970. toJSON() {
  23971. const data = super.toJSON();
  23972. data.aX = this.aX;
  23973. data.aY = this.aY;
  23974. data.xRadius = this.xRadius;
  23975. data.yRadius = this.yRadius;
  23976. data.aStartAngle = this.aStartAngle;
  23977. data.aEndAngle = this.aEndAngle;
  23978. data.aClockwise = this.aClockwise;
  23979. data.aRotation = this.aRotation;
  23980. return data;
  23981. }
  23982. fromJSON( json ) {
  23983. super.fromJSON( json );
  23984. this.aX = json.aX;
  23985. this.aY = json.aY;
  23986. this.xRadius = json.xRadius;
  23987. this.yRadius = json.yRadius;
  23988. this.aStartAngle = json.aStartAngle;
  23989. this.aEndAngle = json.aEndAngle;
  23990. this.aClockwise = json.aClockwise;
  23991. this.aRotation = json.aRotation;
  23992. return this;
  23993. }
  23994. }
  23995. /**
  23996. * A curve representing an arc.
  23997. *
  23998. * @augments EllipseCurve
  23999. */
  24000. class ArcCurve extends EllipseCurve {
  24001. /**
  24002. * Constructs a new arc curve.
  24003. *
  24004. * @param {number} [aX=0] - The X center of the ellipse.
  24005. * @param {number} [aY=0] - The Y center of the ellipse.
  24006. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  24007. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  24008. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  24009. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  24010. */
  24011. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24012. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24013. /**
  24014. * This flag can be used for type testing.
  24015. *
  24016. * @type {boolean}
  24017. * @readonly
  24018. * @default true
  24019. */
  24020. this.isArcCurve = true;
  24021. this.type = 'ArcCurve';
  24022. }
  24023. }
  24024. function CubicPoly() {
  24025. /**
  24026. * Centripetal CatmullRom Curve - which is useful for avoiding
  24027. * cusps and self-intersections in non-uniform catmull rom curves.
  24028. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  24029. *
  24030. * curve.type accepts centripetal(default), chordal and catmullrom
  24031. * curve.tension is used for catmullrom which defaults to 0.5
  24032. */
  24033. /*
  24034. Based on an optimized c++ solution in
  24035. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  24036. - http://ideone.com/NoEbVM
  24037. This CubicPoly class could be used for reusing some variables and calculations,
  24038. but for three.js curve use, it could be possible inlined and flatten into a single function call
  24039. which can be placed in CurveUtils.
  24040. */
  24041. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  24042. /*
  24043. * Compute coefficients for a cubic polynomial
  24044. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  24045. * such that
  24046. * p(0) = x0, p(1) = x1
  24047. * and
  24048. * p'(0) = t0, p'(1) = t1.
  24049. */
  24050. function init( x0, x1, t0, t1 ) {
  24051. c0 = x0;
  24052. c1 = t0;
  24053. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  24054. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  24055. }
  24056. return {
  24057. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  24058. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  24059. },
  24060. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  24061. // compute tangents when parameterized in [t1,t2]
  24062. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  24063. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  24064. // rescale tangents for parametrization in [0,1]
  24065. t1 *= dt1;
  24066. t2 *= dt1;
  24067. init( x1, x2, t1, t2 );
  24068. },
  24069. calc: function ( t ) {
  24070. const t2 = t * t;
  24071. const t3 = t2 * t;
  24072. return c0 + c1 * t + c2 * t2 + c3 * t3;
  24073. }
  24074. };
  24075. }
  24076. //
  24077. const tmp = /*@__PURE__*/ new Vector3();
  24078. const px = /*@__PURE__*/ new CubicPoly();
  24079. const py = /*@__PURE__*/ new CubicPoly();
  24080. const pz = /*@__PURE__*/ new CubicPoly();
  24081. /**
  24082. * A curve representing a Catmull-Rom spline.
  24083. *
  24084. * ```js
  24085. * //Create a closed wavey loop
  24086. * const curve = new THREE.CatmullRomCurve3( [
  24087. * new THREE.Vector3( -10, 0, 10 ),
  24088. * new THREE.Vector3( -5, 5, 5 ),
  24089. * new THREE.Vector3( 0, 0, 0 ),
  24090. * new THREE.Vector3( 5, -5, 5 ),
  24091. * new THREE.Vector3( 10, 0, 10 )
  24092. * ] );
  24093. *
  24094. * const points = curve.getPoints( 50 );
  24095. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24096. *
  24097. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24098. *
  24099. * // Create the final object to add to the scene
  24100. * const curveObject = new THREE.Line( geometry, material );
  24101. * ```
  24102. *
  24103. * @augments Curve
  24104. */
  24105. class CatmullRomCurve3 extends Curve {
  24106. /**
  24107. * Constructs a new Catmull-Rom curve.
  24108. *
  24109. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  24110. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  24111. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  24112. * @param {number} [tension=0.5] - Tension of the curve.
  24113. */
  24114. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  24115. super();
  24116. /**
  24117. * This flag can be used for type testing.
  24118. *
  24119. * @type {boolean}
  24120. * @readonly
  24121. * @default true
  24122. */
  24123. this.isCatmullRomCurve3 = true;
  24124. this.type = 'CatmullRomCurve3';
  24125. /**
  24126. * An array of 3D points defining the curve.
  24127. *
  24128. * @type {Array<Vector3>}
  24129. */
  24130. this.points = points;
  24131. /**
  24132. * Whether the curve is closed or not.
  24133. *
  24134. * @type {boolean}
  24135. * @default false
  24136. */
  24137. this.closed = closed;
  24138. /**
  24139. * The curve type.
  24140. *
  24141. * @type {('centripetal'|'chordal'|'catmullrom')}
  24142. * @default 'centripetal'
  24143. */
  24144. this.curveType = curveType;
  24145. /**
  24146. * Tension of the curve.
  24147. *
  24148. * @type {number}
  24149. * @default 0.5
  24150. */
  24151. this.tension = tension;
  24152. }
  24153. /**
  24154. * Returns a point on the curve.
  24155. *
  24156. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24157. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24158. * @return {Vector3} The position on the curve.
  24159. */
  24160. getPoint( t, optionalTarget = new Vector3() ) {
  24161. const point = optionalTarget;
  24162. const points = this.points;
  24163. const l = points.length;
  24164. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  24165. let intPoint = Math.floor( p );
  24166. let weight = p - intPoint;
  24167. if ( this.closed ) {
  24168. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  24169. } else if ( weight === 0 && intPoint === l - 1 ) {
  24170. intPoint = l - 2;
  24171. weight = 1;
  24172. }
  24173. let p0, p3; // 4 points (p1 & p2 defined below)
  24174. if ( this.closed || intPoint > 0 ) {
  24175. p0 = points[ ( intPoint - 1 ) % l ];
  24176. } else {
  24177. // extrapolate first point
  24178. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  24179. p0 = tmp;
  24180. }
  24181. const p1 = points[ intPoint % l ];
  24182. const p2 = points[ ( intPoint + 1 ) % l ];
  24183. if ( this.closed || intPoint + 2 < l ) {
  24184. p3 = points[ ( intPoint + 2 ) % l ];
  24185. } else {
  24186. // extrapolate last point
  24187. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  24188. p3 = tmp;
  24189. }
  24190. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  24191. // init Centripetal / Chordal Catmull-Rom
  24192. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  24193. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  24194. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  24195. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  24196. // safety check for repeated points
  24197. if ( dt1 < 1e-4 ) dt1 = 1.0;
  24198. if ( dt0 < 1e-4 ) dt0 = dt1;
  24199. if ( dt2 < 1e-4 ) dt2 = dt1;
  24200. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24201. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24202. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24203. } else if ( this.curveType === 'catmullrom' ) {
  24204. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24205. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24206. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24207. }
  24208. point.set(
  24209. px.calc( weight ),
  24210. py.calc( weight ),
  24211. pz.calc( weight )
  24212. );
  24213. return point;
  24214. }
  24215. copy( source ) {
  24216. super.copy( source );
  24217. this.points = [];
  24218. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24219. const point = source.points[ i ];
  24220. this.points.push( point.clone() );
  24221. }
  24222. this.closed = source.closed;
  24223. this.curveType = source.curveType;
  24224. this.tension = source.tension;
  24225. return this;
  24226. }
  24227. toJSON() {
  24228. const data = super.toJSON();
  24229. data.points = [];
  24230. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24231. const point = this.points[ i ];
  24232. data.points.push( point.toArray() );
  24233. }
  24234. data.closed = this.closed;
  24235. data.curveType = this.curveType;
  24236. data.tension = this.tension;
  24237. return data;
  24238. }
  24239. fromJSON( json ) {
  24240. super.fromJSON( json );
  24241. this.points = [];
  24242. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24243. const point = json.points[ i ];
  24244. this.points.push( new Vector3().fromArray( point ) );
  24245. }
  24246. this.closed = json.closed;
  24247. this.curveType = json.curveType;
  24248. this.tension = json.tension;
  24249. return this;
  24250. }
  24251. }
  24252. /**
  24253. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24254. *
  24255. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24256. *
  24257. * @module Interpolations
  24258. */
  24259. /**
  24260. * Computes a point on a Catmull-Rom spline.
  24261. *
  24262. * @param {number} t - The interpolation factor.
  24263. * @param {number} p0 - The first control point.
  24264. * @param {number} p1 - The second control point.
  24265. * @param {number} p2 - The third control point.
  24266. * @param {number} p3 - The fourth control point.
  24267. * @return {number} The calculated point on a Catmull-Rom spline.
  24268. */
  24269. function CatmullRom( t, p0, p1, p2, p3 ) {
  24270. const v0 = ( p2 - p0 ) * 0.5;
  24271. const v1 = ( p3 - p1 ) * 0.5;
  24272. const t2 = t * t;
  24273. const t3 = t * t2;
  24274. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24275. }
  24276. //
  24277. function QuadraticBezierP0( t, p ) {
  24278. const k = 1 - t;
  24279. return k * k * p;
  24280. }
  24281. function QuadraticBezierP1( t, p ) {
  24282. return 2 * ( 1 - t ) * t * p;
  24283. }
  24284. function QuadraticBezierP2( t, p ) {
  24285. return t * t * p;
  24286. }
  24287. /**
  24288. * Computes a point on a Quadratic Bezier curve.
  24289. *
  24290. * @param {number} t - The interpolation factor.
  24291. * @param {number} p0 - The first control point.
  24292. * @param {number} p1 - The second control point.
  24293. * @param {number} p2 - The third control point.
  24294. * @return {number} The calculated point on a Quadratic Bezier curve.
  24295. */
  24296. function QuadraticBezier( t, p0, p1, p2 ) {
  24297. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24298. QuadraticBezierP2( t, p2 );
  24299. }
  24300. //
  24301. function CubicBezierP0( t, p ) {
  24302. const k = 1 - t;
  24303. return k * k * k * p;
  24304. }
  24305. function CubicBezierP1( t, p ) {
  24306. const k = 1 - t;
  24307. return 3 * k * k * t * p;
  24308. }
  24309. function CubicBezierP2( t, p ) {
  24310. return 3 * ( 1 - t ) * t * t * p;
  24311. }
  24312. function CubicBezierP3( t, p ) {
  24313. return t * t * t * p;
  24314. }
  24315. /**
  24316. * Computes a point on a Cubic Bezier curve.
  24317. *
  24318. * @param {number} t - The interpolation factor.
  24319. * @param {number} p0 - The first control point.
  24320. * @param {number} p1 - The second control point.
  24321. * @param {number} p2 - The third control point.
  24322. * @param {number} p3 - The fourth control point.
  24323. * @return {number} The calculated point on a Cubic Bezier curve.
  24324. */
  24325. function CubicBezier( t, p0, p1, p2, p3 ) {
  24326. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24327. CubicBezierP3( t, p3 );
  24328. }
  24329. /**
  24330. * A curve representing a 2D Cubic Bezier curve.
  24331. *
  24332. * ```js
  24333. * const curve = new THREE.CubicBezierCurve(
  24334. * new THREE.Vector2( - 0, 0 ),
  24335. * new THREE.Vector2( - 5, 15 ),
  24336. * new THREE.Vector2( 20, 15 ),
  24337. * new THREE.Vector2( 10, 0 )
  24338. * );
  24339. *
  24340. * const points = curve.getPoints( 50 );
  24341. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24342. *
  24343. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24344. *
  24345. * // Create the final object to add to the scene
  24346. * const curveObject = new THREE.Line( geometry, material );
  24347. * ```
  24348. *
  24349. * @augments Curve
  24350. */
  24351. class CubicBezierCurve extends Curve {
  24352. /**
  24353. * Constructs a new Cubic Bezier curve.
  24354. *
  24355. * @param {Vector2} [v0] - The start point.
  24356. * @param {Vector2} [v1] - The first control point.
  24357. * @param {Vector2} [v2] - The second control point.
  24358. * @param {Vector2} [v3] - The end point.
  24359. */
  24360. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24361. super();
  24362. /**
  24363. * This flag can be used for type testing.
  24364. *
  24365. * @type {boolean}
  24366. * @readonly
  24367. * @default true
  24368. */
  24369. this.isCubicBezierCurve = true;
  24370. this.type = 'CubicBezierCurve';
  24371. /**
  24372. * The start point.
  24373. *
  24374. * @type {Vector2}
  24375. */
  24376. this.v0 = v0;
  24377. /**
  24378. * The first control point.
  24379. *
  24380. * @type {Vector2}
  24381. */
  24382. this.v1 = v1;
  24383. /**
  24384. * The second control point.
  24385. *
  24386. * @type {Vector2}
  24387. */
  24388. this.v2 = v2;
  24389. /**
  24390. * The end point.
  24391. *
  24392. * @type {Vector2}
  24393. */
  24394. this.v3 = v3;
  24395. }
  24396. /**
  24397. * Returns a point on the curve.
  24398. *
  24399. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24400. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24401. * @return {Vector2} The position on the curve.
  24402. */
  24403. getPoint( t, optionalTarget = new Vector2() ) {
  24404. const point = optionalTarget;
  24405. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24406. point.set(
  24407. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24408. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24409. );
  24410. return point;
  24411. }
  24412. copy( source ) {
  24413. super.copy( source );
  24414. this.v0.copy( source.v0 );
  24415. this.v1.copy( source.v1 );
  24416. this.v2.copy( source.v2 );
  24417. this.v3.copy( source.v3 );
  24418. return this;
  24419. }
  24420. toJSON() {
  24421. const data = super.toJSON();
  24422. data.v0 = this.v0.toArray();
  24423. data.v1 = this.v1.toArray();
  24424. data.v2 = this.v2.toArray();
  24425. data.v3 = this.v3.toArray();
  24426. return data;
  24427. }
  24428. fromJSON( json ) {
  24429. super.fromJSON( json );
  24430. this.v0.fromArray( json.v0 );
  24431. this.v1.fromArray( json.v1 );
  24432. this.v2.fromArray( json.v2 );
  24433. this.v3.fromArray( json.v3 );
  24434. return this;
  24435. }
  24436. }
  24437. /**
  24438. * A curve representing a 3D Cubic Bezier curve.
  24439. *
  24440. * @augments Curve
  24441. */
  24442. class CubicBezierCurve3 extends Curve {
  24443. /**
  24444. * Constructs a new Cubic Bezier curve.
  24445. *
  24446. * @param {Vector3} [v0] - The start point.
  24447. * @param {Vector3} [v1] - The first control point.
  24448. * @param {Vector3} [v2] - The second control point.
  24449. * @param {Vector3} [v3] - The end point.
  24450. */
  24451. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24452. super();
  24453. /**
  24454. * This flag can be used for type testing.
  24455. *
  24456. * @type {boolean}
  24457. * @readonly
  24458. * @default true
  24459. */
  24460. this.isCubicBezierCurve3 = true;
  24461. this.type = 'CubicBezierCurve3';
  24462. /**
  24463. * The start point.
  24464. *
  24465. * @type {Vector3}
  24466. */
  24467. this.v0 = v0;
  24468. /**
  24469. * The first control point.
  24470. *
  24471. * @type {Vector3}
  24472. */
  24473. this.v1 = v1;
  24474. /**
  24475. * The second control point.
  24476. *
  24477. * @type {Vector3}
  24478. */
  24479. this.v2 = v2;
  24480. /**
  24481. * The end point.
  24482. *
  24483. * @type {Vector3}
  24484. */
  24485. this.v3 = v3;
  24486. }
  24487. /**
  24488. * Returns a point on the curve.
  24489. *
  24490. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24491. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24492. * @return {Vector3} The position on the curve.
  24493. */
  24494. getPoint( t, optionalTarget = new Vector3() ) {
  24495. const point = optionalTarget;
  24496. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24497. point.set(
  24498. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24499. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24500. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24501. );
  24502. return point;
  24503. }
  24504. copy( source ) {
  24505. super.copy( source );
  24506. this.v0.copy( source.v0 );
  24507. this.v1.copy( source.v1 );
  24508. this.v2.copy( source.v2 );
  24509. this.v3.copy( source.v3 );
  24510. return this;
  24511. }
  24512. toJSON() {
  24513. const data = super.toJSON();
  24514. data.v0 = this.v0.toArray();
  24515. data.v1 = this.v1.toArray();
  24516. data.v2 = this.v2.toArray();
  24517. data.v3 = this.v3.toArray();
  24518. return data;
  24519. }
  24520. fromJSON( json ) {
  24521. super.fromJSON( json );
  24522. this.v0.fromArray( json.v0 );
  24523. this.v1.fromArray( json.v1 );
  24524. this.v2.fromArray( json.v2 );
  24525. this.v3.fromArray( json.v3 );
  24526. return this;
  24527. }
  24528. }
  24529. /**
  24530. * A curve representing a 2D line segment.
  24531. *
  24532. * @augments Curve
  24533. */
  24534. class LineCurve extends Curve {
  24535. /**
  24536. * Constructs a new line curve.
  24537. *
  24538. * @param {Vector2} [v1] - The start point.
  24539. * @param {Vector2} [v2] - The end point.
  24540. */
  24541. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24542. super();
  24543. /**
  24544. * This flag can be used for type testing.
  24545. *
  24546. * @type {boolean}
  24547. * @readonly
  24548. * @default true
  24549. */
  24550. this.isLineCurve = true;
  24551. this.type = 'LineCurve';
  24552. /**
  24553. * The start point.
  24554. *
  24555. * @type {Vector2}
  24556. */
  24557. this.v1 = v1;
  24558. /**
  24559. * The end point.
  24560. *
  24561. * @type {Vector2}
  24562. */
  24563. this.v2 = v2;
  24564. }
  24565. /**
  24566. * Returns a point on the line.
  24567. *
  24568. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24569. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24570. * @return {Vector2} The position on the line.
  24571. */
  24572. getPoint( t, optionalTarget = new Vector2() ) {
  24573. const point = optionalTarget;
  24574. if ( t === 1 ) {
  24575. point.copy( this.v2 );
  24576. } else {
  24577. point.copy( this.v2 ).sub( this.v1 );
  24578. point.multiplyScalar( t ).add( this.v1 );
  24579. }
  24580. return point;
  24581. }
  24582. // Line curve is linear, so we can overwrite default getPointAt
  24583. getPointAt( u, optionalTarget ) {
  24584. return this.getPoint( u, optionalTarget );
  24585. }
  24586. getTangent( t, optionalTarget = new Vector2() ) {
  24587. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24588. }
  24589. getTangentAt( u, optionalTarget ) {
  24590. return this.getTangent( u, optionalTarget );
  24591. }
  24592. copy( source ) {
  24593. super.copy( source );
  24594. this.v1.copy( source.v1 );
  24595. this.v2.copy( source.v2 );
  24596. return this;
  24597. }
  24598. toJSON() {
  24599. const data = super.toJSON();
  24600. data.v1 = this.v1.toArray();
  24601. data.v2 = this.v2.toArray();
  24602. return data;
  24603. }
  24604. fromJSON( json ) {
  24605. super.fromJSON( json );
  24606. this.v1.fromArray( json.v1 );
  24607. this.v2.fromArray( json.v2 );
  24608. return this;
  24609. }
  24610. }
  24611. /**
  24612. * A curve representing a 3D line segment.
  24613. *
  24614. * @augments Curve
  24615. */
  24616. class LineCurve3 extends Curve {
  24617. /**
  24618. * Constructs a new line curve.
  24619. *
  24620. * @param {Vector3} [v1] - The start point.
  24621. * @param {Vector3} [v2] - The end point.
  24622. */
  24623. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24624. super();
  24625. /**
  24626. * This flag can be used for type testing.
  24627. *
  24628. * @type {boolean}
  24629. * @readonly
  24630. * @default true
  24631. */
  24632. this.isLineCurve3 = true;
  24633. this.type = 'LineCurve3';
  24634. /**
  24635. * The start point.
  24636. *
  24637. * @type {Vector3}
  24638. */
  24639. this.v1 = v1;
  24640. /**
  24641. * The end point.
  24642. *
  24643. * @type {Vector2}
  24644. */
  24645. this.v2 = v2;
  24646. }
  24647. /**
  24648. * Returns a point on the line.
  24649. *
  24650. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24651. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24652. * @return {Vector3} The position on the line.
  24653. */
  24654. getPoint( t, optionalTarget = new Vector3() ) {
  24655. const point = optionalTarget;
  24656. if ( t === 1 ) {
  24657. point.copy( this.v2 );
  24658. } else {
  24659. point.copy( this.v2 ).sub( this.v1 );
  24660. point.multiplyScalar( t ).add( this.v1 );
  24661. }
  24662. return point;
  24663. }
  24664. // Line curve is linear, so we can overwrite default getPointAt
  24665. getPointAt( u, optionalTarget ) {
  24666. return this.getPoint( u, optionalTarget );
  24667. }
  24668. getTangent( t, optionalTarget = new Vector3() ) {
  24669. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24670. }
  24671. getTangentAt( u, optionalTarget ) {
  24672. return this.getTangent( u, optionalTarget );
  24673. }
  24674. copy( source ) {
  24675. super.copy( source );
  24676. this.v1.copy( source.v1 );
  24677. this.v2.copy( source.v2 );
  24678. return this;
  24679. }
  24680. toJSON() {
  24681. const data = super.toJSON();
  24682. data.v1 = this.v1.toArray();
  24683. data.v2 = this.v2.toArray();
  24684. return data;
  24685. }
  24686. fromJSON( json ) {
  24687. super.fromJSON( json );
  24688. this.v1.fromArray( json.v1 );
  24689. this.v2.fromArray( json.v2 );
  24690. return this;
  24691. }
  24692. }
  24693. /**
  24694. * A curve representing a 2D Quadratic Bezier curve.
  24695. *
  24696. * ```js
  24697. * const curve = new THREE.QuadraticBezierCurve(
  24698. * new THREE.Vector2( - 10, 0 ),
  24699. * new THREE.Vector2( 20, 15 ),
  24700. * new THREE.Vector2( 10, 0 )
  24701. * )
  24702. *
  24703. * const points = curve.getPoints( 50 );
  24704. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24705. *
  24706. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24707. *
  24708. * // Create the final object to add to the scene
  24709. * const curveObject = new THREE.Line( geometry, material );
  24710. * ```
  24711. *
  24712. * @augments Curve
  24713. */
  24714. class QuadraticBezierCurve extends Curve {
  24715. /**
  24716. * Constructs a new Quadratic Bezier curve.
  24717. *
  24718. * @param {Vector2} [v0] - The start point.
  24719. * @param {Vector2} [v1] - The control point.
  24720. * @param {Vector2} [v2] - The end point.
  24721. */
  24722. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24723. super();
  24724. /**
  24725. * This flag can be used for type testing.
  24726. *
  24727. * @type {boolean}
  24728. * @readonly
  24729. * @default true
  24730. */
  24731. this.isQuadraticBezierCurve = true;
  24732. this.type = 'QuadraticBezierCurve';
  24733. /**
  24734. * The start point.
  24735. *
  24736. * @type {Vector2}
  24737. */
  24738. this.v0 = v0;
  24739. /**
  24740. * The control point.
  24741. *
  24742. * @type {Vector2}
  24743. */
  24744. this.v1 = v1;
  24745. /**
  24746. * The end point.
  24747. *
  24748. * @type {Vector2}
  24749. */
  24750. this.v2 = v2;
  24751. }
  24752. /**
  24753. * Returns a point on the curve.
  24754. *
  24755. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24756. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24757. * @return {Vector2} The position on the curve.
  24758. */
  24759. getPoint( t, optionalTarget = new Vector2() ) {
  24760. const point = optionalTarget;
  24761. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24762. point.set(
  24763. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24764. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24765. );
  24766. return point;
  24767. }
  24768. copy( source ) {
  24769. super.copy( source );
  24770. this.v0.copy( source.v0 );
  24771. this.v1.copy( source.v1 );
  24772. this.v2.copy( source.v2 );
  24773. return this;
  24774. }
  24775. toJSON() {
  24776. const data = super.toJSON();
  24777. data.v0 = this.v0.toArray();
  24778. data.v1 = this.v1.toArray();
  24779. data.v2 = this.v2.toArray();
  24780. return data;
  24781. }
  24782. fromJSON( json ) {
  24783. super.fromJSON( json );
  24784. this.v0.fromArray( json.v0 );
  24785. this.v1.fromArray( json.v1 );
  24786. this.v2.fromArray( json.v2 );
  24787. return this;
  24788. }
  24789. }
  24790. /**
  24791. * A curve representing a 3D Quadratic Bezier curve.
  24792. *
  24793. * @augments Curve
  24794. */
  24795. class QuadraticBezierCurve3 extends Curve {
  24796. /**
  24797. * Constructs a new Quadratic Bezier curve.
  24798. *
  24799. * @param {Vector3} [v0] - The start point.
  24800. * @param {Vector3} [v1] - The control point.
  24801. * @param {Vector3} [v2] - The end point.
  24802. */
  24803. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24804. super();
  24805. /**
  24806. * This flag can be used for type testing.
  24807. *
  24808. * @type {boolean}
  24809. * @readonly
  24810. * @default true
  24811. */
  24812. this.isQuadraticBezierCurve3 = true;
  24813. this.type = 'QuadraticBezierCurve3';
  24814. /**
  24815. * The start point.
  24816. *
  24817. * @type {Vector3}
  24818. */
  24819. this.v0 = v0;
  24820. /**
  24821. * The control point.
  24822. *
  24823. * @type {Vector3}
  24824. */
  24825. this.v1 = v1;
  24826. /**
  24827. * The end point.
  24828. *
  24829. * @type {Vector3}
  24830. */
  24831. this.v2 = v2;
  24832. }
  24833. /**
  24834. * Returns a point on the curve.
  24835. *
  24836. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24837. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24838. * @return {Vector3} The position on the curve.
  24839. */
  24840. getPoint( t, optionalTarget = new Vector3() ) {
  24841. const point = optionalTarget;
  24842. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24843. point.set(
  24844. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24845. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24846. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24847. );
  24848. return point;
  24849. }
  24850. copy( source ) {
  24851. super.copy( source );
  24852. this.v0.copy( source.v0 );
  24853. this.v1.copy( source.v1 );
  24854. this.v2.copy( source.v2 );
  24855. return this;
  24856. }
  24857. toJSON() {
  24858. const data = super.toJSON();
  24859. data.v0 = this.v0.toArray();
  24860. data.v1 = this.v1.toArray();
  24861. data.v2 = this.v2.toArray();
  24862. return data;
  24863. }
  24864. fromJSON( json ) {
  24865. super.fromJSON( json );
  24866. this.v0.fromArray( json.v0 );
  24867. this.v1.fromArray( json.v1 );
  24868. this.v2.fromArray( json.v2 );
  24869. return this;
  24870. }
  24871. }
  24872. /**
  24873. * A curve representing a 2D spline curve.
  24874. *
  24875. * ```js
  24876. * // Create a sine-like wave
  24877. * const curve = new THREE.SplineCurve( [
  24878. * new THREE.Vector2( -10, 0 ),
  24879. * new THREE.Vector2( -5, 5 ),
  24880. * new THREE.Vector2( 0, 0 ),
  24881. * new THREE.Vector2( 5, -5 ),
  24882. * new THREE.Vector2( 10, 0 )
  24883. * ] );
  24884. *
  24885. * const points = curve.getPoints( 50 );
  24886. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24887. *
  24888. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24889. *
  24890. * // Create the final object to add to the scene
  24891. * const splineObject = new THREE.Line( geometry, material );
  24892. * ```
  24893. *
  24894. * @augments Curve
  24895. */
  24896. class SplineCurve extends Curve {
  24897. /**
  24898. * Constructs a new 2D spline curve.
  24899. *
  24900. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24901. */
  24902. constructor( points = [] ) {
  24903. super();
  24904. /**
  24905. * This flag can be used for type testing.
  24906. *
  24907. * @type {boolean}
  24908. * @readonly
  24909. * @default true
  24910. */
  24911. this.isSplineCurve = true;
  24912. this.type = 'SplineCurve';
  24913. /**
  24914. * An array of 2D points defining the curve.
  24915. *
  24916. * @type {Array<Vector2>}
  24917. */
  24918. this.points = points;
  24919. }
  24920. /**
  24921. * Returns a point on the curve.
  24922. *
  24923. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24924. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24925. * @return {Vector2} The position on the curve.
  24926. */
  24927. getPoint( t, optionalTarget = new Vector2() ) {
  24928. const point = optionalTarget;
  24929. const points = this.points;
  24930. const p = ( points.length - 1 ) * t;
  24931. const intPoint = Math.floor( p );
  24932. const weight = p - intPoint;
  24933. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24934. const p1 = points[ intPoint ];
  24935. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24936. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24937. point.set(
  24938. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24939. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24940. );
  24941. return point;
  24942. }
  24943. copy( source ) {
  24944. super.copy( source );
  24945. this.points = [];
  24946. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24947. const point = source.points[ i ];
  24948. this.points.push( point.clone() );
  24949. }
  24950. return this;
  24951. }
  24952. toJSON() {
  24953. const data = super.toJSON();
  24954. data.points = [];
  24955. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24956. const point = this.points[ i ];
  24957. data.points.push( point.toArray() );
  24958. }
  24959. return data;
  24960. }
  24961. fromJSON( json ) {
  24962. super.fromJSON( json );
  24963. this.points = [];
  24964. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24965. const point = json.points[ i ];
  24966. this.points.push( new Vector2().fromArray( point ) );
  24967. }
  24968. return this;
  24969. }
  24970. }
  24971. var Curves = /*#__PURE__*/Object.freeze({
  24972. __proto__: null,
  24973. ArcCurve: ArcCurve,
  24974. CatmullRomCurve3: CatmullRomCurve3,
  24975. CubicBezierCurve: CubicBezierCurve,
  24976. CubicBezierCurve3: CubicBezierCurve3,
  24977. EllipseCurve: EllipseCurve,
  24978. LineCurve: LineCurve,
  24979. LineCurve3: LineCurve3,
  24980. QuadraticBezierCurve: QuadraticBezierCurve,
  24981. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24982. SplineCurve: SplineCurve
  24983. });
  24984. /**
  24985. * A base class extending {@link Curve}. `CurvePath` is simply an
  24986. * array of connected curves, but retains the API of a curve.
  24987. *
  24988. * @augments Curve
  24989. */
  24990. class CurvePath extends Curve {
  24991. /**
  24992. * Constructs a new curve path.
  24993. */
  24994. constructor() {
  24995. super();
  24996. this.type = 'CurvePath';
  24997. /**
  24998. * An array of curves defining the
  24999. * path.
  25000. *
  25001. * @type {Array<Curve>}
  25002. */
  25003. this.curves = [];
  25004. /**
  25005. * Whether the path should automatically be closed
  25006. * by a line curve.
  25007. *
  25008. * @type {boolean}
  25009. * @default false
  25010. */
  25011. this.autoClose = false;
  25012. }
  25013. /**
  25014. * Adds a curve to this curve path.
  25015. *
  25016. * @param {Curve} curve - The curve to add.
  25017. */
  25018. add( curve ) {
  25019. this.curves.push( curve );
  25020. }
  25021. /**
  25022. * Adds a line curve to close the path.
  25023. *
  25024. * @return {CurvePath} A reference to this curve path.
  25025. */
  25026. closePath() {
  25027. // Add a line curve if start and end of lines are not connected
  25028. const startPoint = this.curves[ 0 ].getPoint( 0 );
  25029. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  25030. if ( ! startPoint.equals( endPoint ) ) {
  25031. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  25032. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  25033. }
  25034. return this;
  25035. }
  25036. /**
  25037. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  25038. * for the given interpolation factor.
  25039. *
  25040. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  25041. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  25042. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  25043. */
  25044. getPoint( t, optionalTarget ) {
  25045. // To get accurate point with reference to
  25046. // entire path distance at time t,
  25047. // following has to be done:
  25048. // 1. Length of each sub path have to be known
  25049. // 2. Locate and identify type of curve
  25050. // 3. Get t for the curve
  25051. // 4. Return curve.getPointAt(t')
  25052. const d = t * this.getLength();
  25053. const curveLengths = this.getCurveLengths();
  25054. let i = 0;
  25055. // To think about boundaries points.
  25056. while ( i < curveLengths.length ) {
  25057. if ( curveLengths[ i ] >= d ) {
  25058. const diff = curveLengths[ i ] - d;
  25059. const curve = this.curves[ i ];
  25060. const segmentLength = curve.getLength();
  25061. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  25062. return curve.getPointAt( u, optionalTarget );
  25063. }
  25064. i ++;
  25065. }
  25066. return null;
  25067. // loop where sum != 0, sum > d , sum+1 <d
  25068. }
  25069. getLength() {
  25070. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  25071. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  25072. // getPoint() depends on getLength
  25073. const lens = this.getCurveLengths();
  25074. return lens[ lens.length - 1 ];
  25075. }
  25076. updateArcLengths() {
  25077. // cacheLengths must be recalculated.
  25078. this.needsUpdate = true;
  25079. this.cacheLengths = null;
  25080. this.getCurveLengths();
  25081. }
  25082. /**
  25083. * Returns list of cumulative curve lengths of the defined curves.
  25084. *
  25085. * @return {Array<number>} The curve lengths.
  25086. */
  25087. getCurveLengths() {
  25088. // Compute lengths and cache them
  25089. // We cannot overwrite getLengths() because UtoT mapping uses it.
  25090. // We use cache values if curves and cache array are same length
  25091. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  25092. return this.cacheLengths;
  25093. }
  25094. // Get length of sub-curve
  25095. // Push sums into cached array
  25096. const lengths = [];
  25097. let sums = 0;
  25098. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25099. sums += this.curves[ i ].getLength();
  25100. lengths.push( sums );
  25101. }
  25102. this.cacheLengths = lengths;
  25103. return lengths;
  25104. }
  25105. getSpacedPoints( divisions = 40 ) {
  25106. const points = [];
  25107. for ( let i = 0; i <= divisions; i ++ ) {
  25108. points.push( this.getPoint( i / divisions ) );
  25109. }
  25110. if ( this.autoClose ) {
  25111. points.push( points[ 0 ] );
  25112. }
  25113. return points;
  25114. }
  25115. getPoints( divisions = 12 ) {
  25116. const points = [];
  25117. let last;
  25118. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  25119. const curve = curves[ i ];
  25120. const resolution = curve.isEllipseCurve ? divisions * 2
  25121. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  25122. : curve.isSplineCurve ? divisions * curve.points.length
  25123. : divisions;
  25124. const pts = curve.getPoints( resolution );
  25125. for ( let j = 0; j < pts.length; j ++ ) {
  25126. const point = pts[ j ];
  25127. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  25128. points.push( point );
  25129. last = point;
  25130. }
  25131. }
  25132. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  25133. points.push( points[ 0 ] );
  25134. }
  25135. return points;
  25136. }
  25137. copy( source ) {
  25138. super.copy( source );
  25139. this.curves = [];
  25140. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  25141. const curve = source.curves[ i ];
  25142. this.curves.push( curve.clone() );
  25143. }
  25144. this.autoClose = source.autoClose;
  25145. return this;
  25146. }
  25147. toJSON() {
  25148. const data = super.toJSON();
  25149. data.autoClose = this.autoClose;
  25150. data.curves = [];
  25151. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  25152. const curve = this.curves[ i ];
  25153. data.curves.push( curve.toJSON() );
  25154. }
  25155. return data;
  25156. }
  25157. fromJSON( json ) {
  25158. super.fromJSON( json );
  25159. this.autoClose = json.autoClose;
  25160. this.curves = [];
  25161. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  25162. const curve = json.curves[ i ];
  25163. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  25164. }
  25165. return this;
  25166. }
  25167. }
  25168. /**
  25169. * A 2D path representation. The class provides methods for creating paths
  25170. * and contours of 2D shapes similar to the 2D Canvas API.
  25171. *
  25172. * ```js
  25173. * const path = new THREE.Path();
  25174. *
  25175. * path.lineTo( 0, 0.8 );
  25176. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  25177. * path.lineTo( 1, 1 );
  25178. *
  25179. * const points = path.getPoints();
  25180. *
  25181. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  25182. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  25183. *
  25184. * const line = new THREE.Line( geometry, material );
  25185. * scene.add( line );
  25186. * ```
  25187. *
  25188. * @augments CurvePath
  25189. */
  25190. class Path extends CurvePath {
  25191. /**
  25192. * Constructs a new path.
  25193. *
  25194. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  25195. */
  25196. constructor( points ) {
  25197. super();
  25198. this.type = 'Path';
  25199. /**
  25200. * The current offset of the path. Any new curve added will start here.
  25201. *
  25202. * @type {Vector2}
  25203. */
  25204. this.currentPoint = new Vector2();
  25205. if ( points ) {
  25206. this.setFromPoints( points );
  25207. }
  25208. }
  25209. /**
  25210. * Creates a path from the given list of points. The points are added
  25211. * to the path as instances of {@link LineCurve}.
  25212. *
  25213. * @param {Array<Vector2>} points - An array of 2D points.
  25214. * @return {Path} A reference to this path.
  25215. */
  25216. setFromPoints( points ) {
  25217. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25218. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25219. this.lineTo( points[ i ].x, points[ i ].y );
  25220. }
  25221. return this;
  25222. }
  25223. /**
  25224. * Moves {@link Path#currentPoint} to the given point.
  25225. *
  25226. * @param {number} x - The x coordinate.
  25227. * @param {number} y - The y coordinate.
  25228. * @return {Path} A reference to this path.
  25229. */
  25230. moveTo( x, y ) {
  25231. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25232. return this;
  25233. }
  25234. /**
  25235. * Adds an instance of {@link LineCurve} to the path by connecting
  25236. * the current point with the given one.
  25237. *
  25238. * @param {number} x - The x coordinate of the end point.
  25239. * @param {number} y - The y coordinate of the end point.
  25240. * @return {Path} A reference to this path.
  25241. */
  25242. lineTo( x, y ) {
  25243. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25244. this.curves.push( curve );
  25245. this.currentPoint.set( x, y );
  25246. return this;
  25247. }
  25248. /**
  25249. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25250. * the current point with the given one.
  25251. *
  25252. * @param {number} aCPx - The x coordinate of the control point.
  25253. * @param {number} aCPy - The y coordinate of the control point.
  25254. * @param {number} aX - The x coordinate of the end point.
  25255. * @param {number} aY - The y coordinate of the end point.
  25256. * @return {Path} A reference to this path.
  25257. */
  25258. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25259. const curve = new QuadraticBezierCurve(
  25260. this.currentPoint.clone(),
  25261. new Vector2( aCPx, aCPy ),
  25262. new Vector2( aX, aY )
  25263. );
  25264. this.curves.push( curve );
  25265. this.currentPoint.set( aX, aY );
  25266. return this;
  25267. }
  25268. /**
  25269. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25270. * the current point with the given one.
  25271. *
  25272. * @param {number} aCP1x - The x coordinate of the first control point.
  25273. * @param {number} aCP1y - The y coordinate of the first control point.
  25274. * @param {number} aCP2x - The x coordinate of the second control point.
  25275. * @param {number} aCP2y - The y coordinate of the second control point.
  25276. * @param {number} aX - The x coordinate of the end point.
  25277. * @param {number} aY - The y coordinate of the end point.
  25278. * @return {Path} A reference to this path.
  25279. */
  25280. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25281. const curve = new CubicBezierCurve(
  25282. this.currentPoint.clone(),
  25283. new Vector2( aCP1x, aCP1y ),
  25284. new Vector2( aCP2x, aCP2y ),
  25285. new Vector2( aX, aY )
  25286. );
  25287. this.curves.push( curve );
  25288. this.currentPoint.set( aX, aY );
  25289. return this;
  25290. }
  25291. /**
  25292. * Adds an instance of {@link SplineCurve} to the path by connecting
  25293. * the current point with the given list of points.
  25294. *
  25295. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25296. * @return {Path} A reference to this path.
  25297. */
  25298. splineThru( pts ) {
  25299. const npts = [ this.currentPoint.clone() ].concat( pts );
  25300. const curve = new SplineCurve( npts );
  25301. this.curves.push( curve );
  25302. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25303. return this;
  25304. }
  25305. /**
  25306. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25307. * to the current point.
  25308. *
  25309. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25310. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25311. * @param {number} [aRadius=1] - The radius of the arc.
  25312. * @param {number} [aStartAngle=0] - The start angle in radians.
  25313. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25314. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25315. * @return {Path} A reference to this path.
  25316. */
  25317. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25318. const x0 = this.currentPoint.x;
  25319. const y0 = this.currentPoint.y;
  25320. this.absarc( aX + x0, aY + y0, aRadius,
  25321. aStartAngle, aEndAngle, aClockwise );
  25322. return this;
  25323. }
  25324. /**
  25325. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25326. *
  25327. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25328. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25329. * @param {number} [aRadius=1] - The radius of the arc.
  25330. * @param {number} [aStartAngle=0] - The start angle in radians.
  25331. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25332. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25333. * @return {Path} A reference to this path.
  25334. */
  25335. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25336. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25337. return this;
  25338. }
  25339. /**
  25340. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25341. * to the current point
  25342. *
  25343. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25344. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25345. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25346. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25347. * @param {number} [aStartAngle=0] - The start angle in radians.
  25348. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25349. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25350. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25351. * @return {Path} A reference to this path.
  25352. */
  25353. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25354. const x0 = this.currentPoint.x;
  25355. const y0 = this.currentPoint.y;
  25356. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25357. return this;
  25358. }
  25359. /**
  25360. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25361. *
  25362. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25363. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25364. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25365. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25366. * @param {number} [aStartAngle=0] - The start angle in radians.
  25367. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25368. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25369. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25370. * @return {Path} A reference to this path.
  25371. */
  25372. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25373. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25374. if ( this.curves.length > 0 ) {
  25375. // if a previous curve is present, attempt to join
  25376. const firstPoint = curve.getPoint( 0 );
  25377. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25378. this.lineTo( firstPoint.x, firstPoint.y );
  25379. }
  25380. }
  25381. this.curves.push( curve );
  25382. const lastPoint = curve.getPoint( 1 );
  25383. this.currentPoint.copy( lastPoint );
  25384. return this;
  25385. }
  25386. copy( source ) {
  25387. super.copy( source );
  25388. this.currentPoint.copy( source.currentPoint );
  25389. return this;
  25390. }
  25391. toJSON() {
  25392. const data = super.toJSON();
  25393. data.currentPoint = this.currentPoint.toArray();
  25394. return data;
  25395. }
  25396. fromJSON( json ) {
  25397. super.fromJSON( json );
  25398. this.currentPoint.fromArray( json.currentPoint );
  25399. return this;
  25400. }
  25401. }
  25402. /**
  25403. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25404. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25405. * points, or to get triangulated faces.
  25406. *
  25407. * ```js
  25408. * const heartShape = new THREE.Shape();
  25409. *
  25410. * heartShape.moveTo( 25, 25 );
  25411. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25412. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25413. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25414. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25415. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25416. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25417. *
  25418. * const extrudeSettings = {
  25419. * depth: 8,
  25420. * bevelEnabled: true,
  25421. * bevelSegments: 2,
  25422. * steps: 2,
  25423. * bevelSize: 1,
  25424. * bevelThickness: 1
  25425. * };
  25426. *
  25427. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25428. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25429. * ```
  25430. *
  25431. * @augments Path
  25432. */
  25433. class Shape extends Path {
  25434. /**
  25435. * Constructs a new shape.
  25436. *
  25437. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25438. */
  25439. constructor( points ) {
  25440. super( points );
  25441. /**
  25442. * The UUID of the shape.
  25443. *
  25444. * @type {string}
  25445. * @readonly
  25446. */
  25447. this.uuid = generateUUID();
  25448. this.type = 'Shape';
  25449. /**
  25450. * Defines the holes in the shape. Hole definitions must use the
  25451. * opposite winding order (CW/CCW) than the outer shape.
  25452. *
  25453. * @type {Array<Path>}
  25454. * @readonly
  25455. */
  25456. this.holes = [];
  25457. }
  25458. /**
  25459. * Returns an array representing each contour of the holes
  25460. * as a list of 2D points.
  25461. *
  25462. * @param {number} divisions - The fineness of the result.
  25463. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25464. */
  25465. getPointsHoles( divisions ) {
  25466. const holesPts = [];
  25467. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25468. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25469. }
  25470. return holesPts;
  25471. }
  25472. // get points of shape and holes (keypoints based on segments parameter)
  25473. /**
  25474. * Returns an object that holds contour data for the shape and its holes as
  25475. * arrays of 2D points.
  25476. *
  25477. * @param {number} divisions - The fineness of the result.
  25478. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25479. */
  25480. extractPoints( divisions ) {
  25481. return {
  25482. shape: this.getPoints( divisions ),
  25483. holes: this.getPointsHoles( divisions )
  25484. };
  25485. }
  25486. copy( source ) {
  25487. super.copy( source );
  25488. this.holes = [];
  25489. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25490. const hole = source.holes[ i ];
  25491. this.holes.push( hole.clone() );
  25492. }
  25493. return this;
  25494. }
  25495. toJSON() {
  25496. const data = super.toJSON();
  25497. data.uuid = this.uuid;
  25498. data.holes = [];
  25499. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25500. const hole = this.holes[ i ];
  25501. data.holes.push( hole.toJSON() );
  25502. }
  25503. return data;
  25504. }
  25505. fromJSON( json ) {
  25506. super.fromJSON( json );
  25507. this.uuid = json.uuid;
  25508. this.holes = [];
  25509. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25510. const hole = json.holes[ i ];
  25511. this.holes.push( new Path().fromJSON( hole ) );
  25512. }
  25513. return this;
  25514. }
  25515. }
  25516. /* eslint-disable */
  25517. // copy of mapbox/earcut version 3.0.2
  25518. // https://github.com/mapbox/earcut/tree/v3.0.2
  25519. function earcut(data, holeIndices, dim = 2) {
  25520. const hasHoles = holeIndices && holeIndices.length;
  25521. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25522. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25523. const triangles = [];
  25524. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25525. let minX, minY, invSize;
  25526. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25527. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25528. if (data.length > 80 * dim) {
  25529. minX = data[0];
  25530. minY = data[1];
  25531. let maxX = minX;
  25532. let maxY = minY;
  25533. for (let i = dim; i < outerLen; i += dim) {
  25534. const x = data[i];
  25535. const y = data[i + 1];
  25536. if (x < minX) minX = x;
  25537. if (y < minY) minY = y;
  25538. if (x > maxX) maxX = x;
  25539. if (y > maxY) maxY = y;
  25540. }
  25541. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25542. invSize = Math.max(maxX - minX, maxY - minY);
  25543. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25544. }
  25545. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25546. return triangles;
  25547. }
  25548. // create a circular doubly linked list from polygon points in the specified winding order
  25549. function linkedList(data, start, end, dim, clockwise) {
  25550. let last;
  25551. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25552. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25553. } else {
  25554. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25555. }
  25556. if (last && equals(last, last.next)) {
  25557. removeNode(last);
  25558. last = last.next;
  25559. }
  25560. return last;
  25561. }
  25562. // eliminate colinear or duplicate points
  25563. function filterPoints(start, end) {
  25564. if (!start) return start;
  25565. if (!end) end = start;
  25566. let p = start,
  25567. again;
  25568. do {
  25569. again = false;
  25570. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25571. removeNode(p);
  25572. p = end = p.prev;
  25573. if (p === p.next) break;
  25574. again = true;
  25575. } else {
  25576. p = p.next;
  25577. }
  25578. } while (again || p !== end);
  25579. return end;
  25580. }
  25581. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25582. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25583. if (!ear) return;
  25584. // interlink polygon nodes in z-order
  25585. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25586. let stop = ear;
  25587. // iterate through ears, slicing them one by one
  25588. while (ear.prev !== ear.next) {
  25589. const prev = ear.prev;
  25590. const next = ear.next;
  25591. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25592. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25593. removeNode(ear);
  25594. // skipping the next vertex leads to less sliver triangles
  25595. ear = next.next;
  25596. stop = next.next;
  25597. continue;
  25598. }
  25599. ear = next;
  25600. // if we looped through the whole remaining polygon and can't find any more ears
  25601. if (ear === stop) {
  25602. // try filtering points and slicing again
  25603. if (!pass) {
  25604. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25605. // if this didn't work, try curing all small self-intersections locally
  25606. } else if (pass === 1) {
  25607. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25608. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25609. // as a last resort, try splitting the remaining polygon into two
  25610. } else if (pass === 2) {
  25611. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25612. }
  25613. break;
  25614. }
  25615. }
  25616. }
  25617. // check whether a polygon node forms a valid ear with adjacent nodes
  25618. function isEar(ear) {
  25619. const a = ear.prev,
  25620. b = ear,
  25621. c = ear.next;
  25622. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25623. // now make sure we don't have other points inside the potential ear
  25624. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25625. // triangle bbox
  25626. const x0 = Math.min(ax, bx, cx),
  25627. y0 = Math.min(ay, by, cy),
  25628. x1 = Math.max(ax, bx, cx),
  25629. y1 = Math.max(ay, by, cy);
  25630. let p = c.next;
  25631. while (p !== a) {
  25632. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25633. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25634. area(p.prev, p, p.next) >= 0) return false;
  25635. p = p.next;
  25636. }
  25637. return true;
  25638. }
  25639. function isEarHashed(ear, minX, minY, invSize) {
  25640. const a = ear.prev,
  25641. b = ear,
  25642. c = ear.next;
  25643. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25644. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25645. // triangle bbox
  25646. const x0 = Math.min(ax, bx, cx),
  25647. y0 = Math.min(ay, by, cy),
  25648. x1 = Math.max(ax, bx, cx),
  25649. y1 = Math.max(ay, by, cy);
  25650. // z-order range for the current triangle bbox;
  25651. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25652. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25653. let p = ear.prevZ,
  25654. n = ear.nextZ;
  25655. // look for points inside the triangle in both directions
  25656. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25657. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25658. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25659. p = p.prevZ;
  25660. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25661. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25662. n = n.nextZ;
  25663. }
  25664. // look for remaining points in decreasing z-order
  25665. while (p && p.z >= minZ) {
  25666. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25667. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25668. p = p.prevZ;
  25669. }
  25670. // look for remaining points in increasing z-order
  25671. while (n && n.z <= maxZ) {
  25672. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25673. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25674. n = n.nextZ;
  25675. }
  25676. return true;
  25677. }
  25678. // go through all polygon nodes and cure small local self-intersections
  25679. function cureLocalIntersections(start, triangles) {
  25680. let p = start;
  25681. do {
  25682. const a = p.prev,
  25683. b = p.next.next;
  25684. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25685. triangles.push(a.i, p.i, b.i);
  25686. // remove two nodes involved
  25687. removeNode(p);
  25688. removeNode(p.next);
  25689. p = start = b;
  25690. }
  25691. p = p.next;
  25692. } while (p !== start);
  25693. return filterPoints(p);
  25694. }
  25695. // try splitting polygon into two and triangulate them independently
  25696. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25697. // look for a valid diagonal that divides the polygon into two
  25698. let a = start;
  25699. do {
  25700. let b = a.next.next;
  25701. while (b !== a.prev) {
  25702. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25703. // split the polygon in two by the diagonal
  25704. let c = splitPolygon(a, b);
  25705. // filter colinear points around the cuts
  25706. a = filterPoints(a, a.next);
  25707. c = filterPoints(c, c.next);
  25708. // run earcut on each half
  25709. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25710. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25711. return;
  25712. }
  25713. b = b.next;
  25714. }
  25715. a = a.next;
  25716. } while (a !== start);
  25717. }
  25718. // link every hole into the outer loop, producing a single-ring polygon without holes
  25719. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25720. const queue = [];
  25721. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25722. const start = holeIndices[i] * dim;
  25723. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25724. const list = linkedList(data, start, end, dim, false);
  25725. if (list === list.next) list.steiner = true;
  25726. queue.push(getLeftmost(list));
  25727. }
  25728. queue.sort(compareXYSlope);
  25729. // process holes from left to right
  25730. for (let i = 0; i < queue.length; i++) {
  25731. outerNode = eliminateHole(queue[i], outerNode);
  25732. }
  25733. return outerNode;
  25734. }
  25735. function compareXYSlope(a, b) {
  25736. let result = a.x - b.x;
  25737. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25738. // the bridge to the outer shell is always the point that they meet at.
  25739. if (result === 0) {
  25740. result = a.y - b.y;
  25741. if (result === 0) {
  25742. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25743. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25744. result = aSlope - bSlope;
  25745. }
  25746. }
  25747. return result;
  25748. }
  25749. // find a bridge between vertices that connects hole with an outer ring and link it
  25750. function eliminateHole(hole, outerNode) {
  25751. const bridge = findHoleBridge(hole, outerNode);
  25752. if (!bridge) {
  25753. return outerNode;
  25754. }
  25755. const bridgeReverse = splitPolygon(bridge, hole);
  25756. // filter collinear points around the cuts
  25757. filterPoints(bridgeReverse, bridgeReverse.next);
  25758. return filterPoints(bridge, bridge.next);
  25759. }
  25760. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25761. function findHoleBridge(hole, outerNode) {
  25762. let p = outerNode;
  25763. const hx = hole.x;
  25764. const hy = hole.y;
  25765. let qx = -Infinity;
  25766. let m;
  25767. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25768. // segment's endpoint with lesser x will be potential connection point
  25769. // unless they intersect at a vertex, then choose the vertex
  25770. if (equals(hole, p)) return p;
  25771. do {
  25772. if (equals(hole, p.next)) return p.next;
  25773. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25774. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25775. if (x <= hx && x > qx) {
  25776. qx = x;
  25777. m = p.x < p.next.x ? p : p.next;
  25778. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25779. }
  25780. }
  25781. p = p.next;
  25782. } while (p !== outerNode);
  25783. if (!m) return null;
  25784. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25785. // if there are no points found, we have a valid connection;
  25786. // otherwise choose the point of the minimum angle with the ray as connection point
  25787. const stop = m;
  25788. const mx = m.x;
  25789. const my = m.y;
  25790. let tanMin = Infinity;
  25791. p = m;
  25792. do {
  25793. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25794. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25795. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25796. if (locallyInside(p, hole) &&
  25797. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25798. m = p;
  25799. tanMin = tan;
  25800. }
  25801. }
  25802. p = p.next;
  25803. } while (p !== stop);
  25804. return m;
  25805. }
  25806. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25807. function sectorContainsSector(m, p) {
  25808. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25809. }
  25810. // interlink polygon nodes in z-order
  25811. function indexCurve(start, minX, minY, invSize) {
  25812. let p = start;
  25813. do {
  25814. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25815. p.prevZ = p.prev;
  25816. p.nextZ = p.next;
  25817. p = p.next;
  25818. } while (p !== start);
  25819. p.prevZ.nextZ = null;
  25820. p.prevZ = null;
  25821. sortLinked(p);
  25822. }
  25823. // Simon Tatham's linked list merge sort algorithm
  25824. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25825. function sortLinked(list) {
  25826. let numMerges;
  25827. let inSize = 1;
  25828. do {
  25829. let p = list;
  25830. let e;
  25831. list = null;
  25832. let tail = null;
  25833. numMerges = 0;
  25834. while (p) {
  25835. numMerges++;
  25836. let q = p;
  25837. let pSize = 0;
  25838. for (let i = 0; i < inSize; i++) {
  25839. pSize++;
  25840. q = q.nextZ;
  25841. if (!q) break;
  25842. }
  25843. let qSize = inSize;
  25844. while (pSize > 0 || (qSize > 0 && q)) {
  25845. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25846. e = p;
  25847. p = p.nextZ;
  25848. pSize--;
  25849. } else {
  25850. e = q;
  25851. q = q.nextZ;
  25852. qSize--;
  25853. }
  25854. if (tail) tail.nextZ = e;
  25855. else list = e;
  25856. e.prevZ = tail;
  25857. tail = e;
  25858. }
  25859. p = q;
  25860. }
  25861. tail.nextZ = null;
  25862. inSize *= 2;
  25863. } while (numMerges > 1);
  25864. return list;
  25865. }
  25866. // z-order of a point given coords and inverse of the longer side of data bbox
  25867. function zOrder(x, y, minX, minY, invSize) {
  25868. // coords are transformed into non-negative 15-bit integer range
  25869. x = (x - minX) * invSize | 0;
  25870. y = (y - minY) * invSize | 0;
  25871. x = (x | (x << 8)) & 0x00FF00FF;
  25872. x = (x | (x << 4)) & 0x0F0F0F0F;
  25873. x = (x | (x << 2)) & 0x33333333;
  25874. x = (x | (x << 1)) & 0x55555555;
  25875. y = (y | (y << 8)) & 0x00FF00FF;
  25876. y = (y | (y << 4)) & 0x0F0F0F0F;
  25877. y = (y | (y << 2)) & 0x33333333;
  25878. y = (y | (y << 1)) & 0x55555555;
  25879. return x | (y << 1);
  25880. }
  25881. // find the leftmost node of a polygon ring
  25882. function getLeftmost(start) {
  25883. let p = start,
  25884. leftmost = start;
  25885. do {
  25886. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25887. p = p.next;
  25888. } while (p !== start);
  25889. return leftmost;
  25890. }
  25891. // check if a point lies within a convex triangle
  25892. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25893. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25894. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25895. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25896. }
  25897. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25898. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25899. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25900. }
  25901. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25902. function isValidDiagonal(a, b) {
  25903. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25904. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25905. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25906. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25907. }
  25908. // signed area of a triangle
  25909. function area(p, q, r) {
  25910. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25911. }
  25912. // check if two points are equal
  25913. function equals(p1, p2) {
  25914. return p1.x === p2.x && p1.y === p2.y;
  25915. }
  25916. // check if two segments intersect
  25917. function intersects(p1, q1, p2, q2) {
  25918. const o1 = sign(area(p1, q1, p2));
  25919. const o2 = sign(area(p1, q1, q2));
  25920. const o3 = sign(area(p2, q2, p1));
  25921. const o4 = sign(area(p2, q2, q1));
  25922. if (o1 !== o2 && o3 !== o4) return true; // general case
  25923. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25924. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25925. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25926. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25927. return false;
  25928. }
  25929. // for collinear points p, q, r, check if point q lies on segment pr
  25930. function onSegment(p, q, r) {
  25931. 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);
  25932. }
  25933. function sign(num) {
  25934. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25935. }
  25936. // check if a polygon diagonal intersects any polygon segments
  25937. function intersectsPolygon(a, b) {
  25938. let p = a;
  25939. do {
  25940. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25941. intersects(p, p.next, a, b)) return true;
  25942. p = p.next;
  25943. } while (p !== a);
  25944. return false;
  25945. }
  25946. // check if a polygon diagonal is locally inside the polygon
  25947. function locallyInside(a, b) {
  25948. return area(a.prev, a, a.next) < 0 ?
  25949. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25950. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25951. }
  25952. // check if the middle point of a polygon diagonal is inside the polygon
  25953. function middleInside(a, b) {
  25954. let p = a;
  25955. let inside = false;
  25956. const px = (a.x + b.x) / 2;
  25957. const py = (a.y + b.y) / 2;
  25958. do {
  25959. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25960. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25961. inside = !inside;
  25962. p = p.next;
  25963. } while (p !== a);
  25964. return inside;
  25965. }
  25966. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25967. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25968. function splitPolygon(a, b) {
  25969. const a2 = createNode(a.i, a.x, a.y),
  25970. b2 = createNode(b.i, b.x, b.y),
  25971. an = a.next,
  25972. bp = b.prev;
  25973. a.next = b;
  25974. b.prev = a;
  25975. a2.next = an;
  25976. an.prev = a2;
  25977. b2.next = a2;
  25978. a2.prev = b2;
  25979. bp.next = b2;
  25980. b2.prev = bp;
  25981. return b2;
  25982. }
  25983. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25984. function insertNode(i, x, y, last) {
  25985. const p = createNode(i, x, y);
  25986. if (!last) {
  25987. p.prev = p;
  25988. p.next = p;
  25989. } else {
  25990. p.next = last.next;
  25991. p.prev = last;
  25992. last.next.prev = p;
  25993. last.next = p;
  25994. }
  25995. return p;
  25996. }
  25997. function removeNode(p) {
  25998. p.next.prev = p.prev;
  25999. p.prev.next = p.next;
  26000. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  26001. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  26002. }
  26003. function createNode(i, x, y) {
  26004. return {
  26005. i, // vertex index in coordinates array
  26006. x, y, // vertex coordinates
  26007. prev: null, // previous and next vertex nodes in a polygon ring
  26008. next: null,
  26009. z: 0, // z-order curve value
  26010. prevZ: null, // previous and next nodes in z-order
  26011. nextZ: null,
  26012. steiner: false // indicates whether this is a steiner point
  26013. };
  26014. }
  26015. function signedArea(data, start, end, dim) {
  26016. let sum = 0;
  26017. for (let i = start, j = end - dim; i < end; i += dim) {
  26018. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  26019. j = i;
  26020. }
  26021. return sum;
  26022. }
  26023. /**
  26024. * An implementation of the earcut polygon triangulation algorithm.
  26025. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  26026. *
  26027. * @see https://github.com/mapbox/earcut
  26028. */
  26029. class Earcut {
  26030. /**
  26031. * Triangulates the given shape definition by returning an array of triangles.
  26032. *
  26033. * @param {Array<number>} data - An array with 2D points.
  26034. * @param {Array<number>} holeIndices - An array with indices defining holes.
  26035. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  26036. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  26037. * representing vertex indices.
  26038. */
  26039. static triangulate( data, holeIndices, dim = 2 ) {
  26040. return earcut( data, holeIndices, dim );
  26041. }
  26042. }
  26043. /**
  26044. * A class containing utility functions for shapes.
  26045. *
  26046. * @hideconstructor
  26047. */
  26048. class ShapeUtils {
  26049. /**
  26050. * Calculate area of a ( 2D ) contour polygon.
  26051. *
  26052. * @param {Array<Vector2>} contour - An array of 2D points.
  26053. * @return {number} The area.
  26054. */
  26055. static area( contour ) {
  26056. const n = contour.length;
  26057. let a = 0.0;
  26058. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  26059. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  26060. }
  26061. return a * 0.5;
  26062. }
  26063. /**
  26064. * Returns `true` if the given contour uses a clockwise winding order.
  26065. *
  26066. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  26067. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  26068. */
  26069. static isClockWise( pts ) {
  26070. return ShapeUtils.area( pts ) < 0;
  26071. }
  26072. /**
  26073. * Triangulates the given shape definition.
  26074. *
  26075. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  26076. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  26077. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  26078. */
  26079. static triangulateShape( contour, holes ) {
  26080. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  26081. const holeIndices = []; // array of hole indices
  26082. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  26083. removeDupEndPts( contour );
  26084. addContour( vertices, contour );
  26085. //
  26086. let holeIndex = contour.length;
  26087. holes.forEach( removeDupEndPts );
  26088. for ( let i = 0; i < holes.length; i ++ ) {
  26089. holeIndices.push( holeIndex );
  26090. holeIndex += holes[ i ].length;
  26091. addContour( vertices, holes[ i ] );
  26092. }
  26093. //
  26094. const triangles = Earcut.triangulate( vertices, holeIndices );
  26095. //
  26096. for ( let i = 0; i < triangles.length; i += 3 ) {
  26097. faces.push( triangles.slice( i, i + 3 ) );
  26098. }
  26099. return faces;
  26100. }
  26101. }
  26102. function removeDupEndPts( points ) {
  26103. const l = points.length;
  26104. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  26105. points.pop();
  26106. }
  26107. }
  26108. function addContour( vertices, contour ) {
  26109. for ( let i = 0; i < contour.length; i ++ ) {
  26110. vertices.push( contour[ i ].x );
  26111. vertices.push( contour[ i ].y );
  26112. }
  26113. }
  26114. /**
  26115. * Creates extruded geometry from a path shape.
  26116. *
  26117. * ```js
  26118. * const length = 12, width = 8;
  26119. *
  26120. * const shape = new THREE.Shape();
  26121. * shape.moveTo( 0,0 );
  26122. * shape.lineTo( 0, width );
  26123. * shape.lineTo( length, width );
  26124. * shape.lineTo( length, 0 );
  26125. * shape.lineTo( 0, 0 );
  26126. *
  26127. * const geometry = new THREE.ExtrudeGeometry( shape );
  26128. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  26129. * const mesh = new THREE.Mesh( geometry, material ) ;
  26130. * scene.add( mesh );
  26131. * ```
  26132. *
  26133. * @augments BufferGeometry
  26134. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  26135. */
  26136. class ExtrudeGeometry extends BufferGeometry {
  26137. /**
  26138. * Constructs a new extrude geometry.
  26139. *
  26140. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26141. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  26142. */
  26143. 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 = {} ) {
  26144. super();
  26145. this.type = 'ExtrudeGeometry';
  26146. /**
  26147. * Holds the constructor parameters that have been
  26148. * used to generate the geometry. Any modification
  26149. * after instantiation does not change the geometry.
  26150. *
  26151. * @type {Object}
  26152. */
  26153. this.parameters = {
  26154. shapes: shapes,
  26155. options: options
  26156. };
  26157. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  26158. const scope = this;
  26159. const verticesArray = [];
  26160. const uvArray = [];
  26161. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26162. const shape = shapes[ i ];
  26163. addShape( shape );
  26164. }
  26165. // build geometry
  26166. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  26167. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  26168. this.computeVertexNormals();
  26169. // functions
  26170. function addShape( shape ) {
  26171. const placeholder = [];
  26172. // options
  26173. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  26174. const steps = options.steps !== undefined ? options.steps : 1;
  26175. const depth = options.depth !== undefined ? options.depth : 1;
  26176. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  26177. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  26178. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  26179. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  26180. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  26181. const extrudePath = options.extrudePath;
  26182. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  26183. //
  26184. let extrudePts, extrudeByPath = false;
  26185. let splineTube, binormal, normal, position2;
  26186. if ( extrudePath ) {
  26187. extrudePts = extrudePath.getSpacedPoints( steps );
  26188. extrudeByPath = true;
  26189. bevelEnabled = false; // bevels not supported for path extrusion
  26190. // SETUP TNB variables
  26191. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  26192. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  26193. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  26194. binormal = new Vector3();
  26195. normal = new Vector3();
  26196. position2 = new Vector3();
  26197. }
  26198. // Safeguards if bevels are not enabled
  26199. if ( ! bevelEnabled ) {
  26200. bevelSegments = 0;
  26201. bevelThickness = 0;
  26202. bevelSize = 0;
  26203. bevelOffset = 0;
  26204. }
  26205. // Variables initialization
  26206. const shapePoints = shape.extractPoints( curveSegments );
  26207. let vertices = shapePoints.shape;
  26208. const holes = shapePoints.holes;
  26209. const reverse = ! ShapeUtils.isClockWise( vertices );
  26210. if ( reverse ) {
  26211. vertices = vertices.reverse();
  26212. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26213. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26214. const ahole = holes[ h ];
  26215. if ( ShapeUtils.isClockWise( ahole ) ) {
  26216. holes[ h ] = ahole.reverse();
  26217. }
  26218. }
  26219. }
  26220. /**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.
  26221. * @param {Array<Vector2>} points
  26222. */
  26223. function mergeOverlappingPoints( points ) {
  26224. const THRESHOLD = 1e-10;
  26225. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26226. let prevPos = points[ 0 ];
  26227. for ( let i = 1; i <= points.length; i ++ ) {
  26228. const currentIndex = i % points.length;
  26229. const currentPos = points[ currentIndex ];
  26230. const dx = currentPos.x - prevPos.x;
  26231. const dy = currentPos.y - prevPos.y;
  26232. const distSq = dx * dx + dy * dy;
  26233. const scalingFactorSqrt = Math.max(
  26234. Math.abs( currentPos.x ),
  26235. Math.abs( currentPos.y ),
  26236. Math.abs( prevPos.x ),
  26237. Math.abs( prevPos.y )
  26238. );
  26239. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26240. if ( distSq <= thresholdSqScaled ) {
  26241. points.splice( currentIndex, 1 );
  26242. i --;
  26243. continue;
  26244. }
  26245. prevPos = currentPos;
  26246. }
  26247. }
  26248. mergeOverlappingPoints( vertices );
  26249. holes.forEach( mergeOverlappingPoints );
  26250. const numHoles = holes.length;
  26251. /* Vertices */
  26252. const contour = vertices; // vertices has all points but contour has only points of circumference
  26253. for ( let h = 0; h < numHoles; h ++ ) {
  26254. const ahole = holes[ h ];
  26255. vertices = vertices.concat( ahole );
  26256. }
  26257. function scalePt2( pt, vec, size ) {
  26258. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26259. return pt.clone().addScaledVector( vec, size );
  26260. }
  26261. const vlen = vertices.length;
  26262. // Find directions for point movement
  26263. function getBevelVec( inPt, inPrev, inNext ) {
  26264. // computes for inPt the corresponding point inPt' on a new contour
  26265. // shifted by 1 unit (length of normalized vector) to the left
  26266. // if we walk along contour clockwise, this new contour is outside the old one
  26267. //
  26268. // inPt' is the intersection of the two lines parallel to the two
  26269. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26270. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26271. // good reading for geometry algorithms (here: line-line intersection)
  26272. // http://geomalgorithms.com/a05-_intersect-1.html
  26273. const v_prev_x = inPt.x - inPrev.x,
  26274. v_prev_y = inPt.y - inPrev.y;
  26275. const v_next_x = inNext.x - inPt.x,
  26276. v_next_y = inNext.y - inPt.y;
  26277. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26278. // check for collinear edges
  26279. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26280. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26281. // not collinear
  26282. // length of vectors for normalizing
  26283. const v_prev_len = Math.sqrt( v_prev_lensq );
  26284. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26285. // shift adjacent points by unit vectors to the left
  26286. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26287. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26288. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26289. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26290. // scaling factor for v_prev to intersection point
  26291. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26292. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26293. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26294. // vector from inPt to intersection point
  26295. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26296. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26297. // Don't normalize!, otherwise sharp corners become ugly
  26298. // but prevent crazy spikes
  26299. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26300. if ( v_trans_lensq <= 2 ) {
  26301. return new Vector2( v_trans_x, v_trans_y );
  26302. } else {
  26303. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26304. }
  26305. } else {
  26306. // handle special case of collinear edges
  26307. let direction_eq = false; // assumes: opposite
  26308. if ( v_prev_x > Number.EPSILON ) {
  26309. if ( v_next_x > Number.EPSILON ) {
  26310. direction_eq = true;
  26311. }
  26312. } else {
  26313. if ( v_prev_x < - Number.EPSILON ) {
  26314. if ( v_next_x < - Number.EPSILON ) {
  26315. direction_eq = true;
  26316. }
  26317. } else {
  26318. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26319. direction_eq = true;
  26320. }
  26321. }
  26322. }
  26323. if ( direction_eq ) {
  26324. // log("Warning: lines are a straight sequence");
  26325. v_trans_x = - v_prev_y;
  26326. v_trans_y = v_prev_x;
  26327. shrink_by = Math.sqrt( v_prev_lensq );
  26328. } else {
  26329. // log("Warning: lines are a straight spike");
  26330. v_trans_x = v_prev_x;
  26331. v_trans_y = v_prev_y;
  26332. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26333. }
  26334. }
  26335. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26336. }
  26337. const contourMovements = [];
  26338. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26339. if ( j === il ) j = 0;
  26340. if ( k === il ) k = 0;
  26341. // (j)---(i)---(k)
  26342. // log('i,j,k', i, j , k)
  26343. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26344. }
  26345. const holesMovements = [];
  26346. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26347. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26348. const ahole = holes[ h ];
  26349. oneHoleMovements = [];
  26350. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26351. if ( j === il ) j = 0;
  26352. if ( k === il ) k = 0;
  26353. // (j)---(i)---(k)
  26354. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26355. }
  26356. holesMovements.push( oneHoleMovements );
  26357. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26358. }
  26359. let faces;
  26360. if ( bevelSegments === 0 ) {
  26361. faces = ShapeUtils.triangulateShape( contour, holes );
  26362. } else {
  26363. const contractedContourVertices = [];
  26364. const expandedHoleVertices = [];
  26365. // Loop bevelSegments, 1 for the front, 1 for the back
  26366. for ( let b = 0; b < bevelSegments; b ++ ) {
  26367. //for ( b = bevelSegments; b > 0; b -- ) {
  26368. const t = b / bevelSegments;
  26369. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26370. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26371. // contract shape
  26372. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26373. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26374. v( vert.x, vert.y, - z );
  26375. if ( t === 0 ) contractedContourVertices.push( vert );
  26376. }
  26377. // expand holes
  26378. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26379. const ahole = holes[ h ];
  26380. oneHoleMovements = holesMovements[ h ];
  26381. const oneHoleVertices = [];
  26382. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26383. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26384. v( vert.x, vert.y, - z );
  26385. if ( t === 0 ) oneHoleVertices.push( vert );
  26386. }
  26387. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26388. }
  26389. }
  26390. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26391. }
  26392. const flen = faces.length;
  26393. const bs = bevelSize + bevelOffset;
  26394. // Back facing vertices
  26395. for ( let i = 0; i < vlen; i ++ ) {
  26396. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26397. if ( ! extrudeByPath ) {
  26398. v( vert.x, vert.y, 0 );
  26399. } else {
  26400. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26401. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26402. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26403. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26404. v( position2.x, position2.y, position2.z );
  26405. }
  26406. }
  26407. // Add stepped vertices...
  26408. // Including front facing vertices
  26409. for ( let s = 1; s <= steps; s ++ ) {
  26410. for ( let i = 0; i < vlen; i ++ ) {
  26411. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26412. if ( ! extrudeByPath ) {
  26413. v( vert.x, vert.y, depth / steps * s );
  26414. } else {
  26415. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26416. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26417. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26418. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26419. v( position2.x, position2.y, position2.z );
  26420. }
  26421. }
  26422. }
  26423. // Add bevel segments planes
  26424. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26425. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26426. const t = b / bevelSegments;
  26427. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26428. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26429. // contract shape
  26430. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26431. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26432. v( vert.x, vert.y, depth + z );
  26433. }
  26434. // expand holes
  26435. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26436. const ahole = holes[ h ];
  26437. oneHoleMovements = holesMovements[ h ];
  26438. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26439. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26440. if ( ! extrudeByPath ) {
  26441. v( vert.x, vert.y, depth + z );
  26442. } else {
  26443. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26444. }
  26445. }
  26446. }
  26447. }
  26448. /* Faces */
  26449. // Top and bottom faces
  26450. buildLidFaces();
  26451. // Sides faces
  26452. buildSideFaces();
  26453. ///// Internal functions
  26454. function buildLidFaces() {
  26455. const start = verticesArray.length / 3;
  26456. if ( bevelEnabled ) {
  26457. let layer = 0; // steps + 1
  26458. let offset = vlen * layer;
  26459. // Bottom faces
  26460. for ( let i = 0; i < flen; i ++ ) {
  26461. const face = faces[ i ];
  26462. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26463. }
  26464. layer = steps + bevelSegments * 2;
  26465. offset = vlen * layer;
  26466. // Top faces
  26467. for ( let i = 0; i < flen; i ++ ) {
  26468. const face = faces[ i ];
  26469. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26470. }
  26471. } else {
  26472. // Bottom faces
  26473. for ( let i = 0; i < flen; i ++ ) {
  26474. const face = faces[ i ];
  26475. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26476. }
  26477. // Top faces
  26478. for ( let i = 0; i < flen; i ++ ) {
  26479. const face = faces[ i ];
  26480. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26481. }
  26482. }
  26483. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26484. }
  26485. // Create faces for the z-sides of the shape
  26486. function buildSideFaces() {
  26487. const start = verticesArray.length / 3;
  26488. let layeroffset = 0;
  26489. sidewalls( contour, layeroffset );
  26490. layeroffset += contour.length;
  26491. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26492. const ahole = holes[ h ];
  26493. sidewalls( ahole, layeroffset );
  26494. //, true
  26495. layeroffset += ahole.length;
  26496. }
  26497. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26498. }
  26499. function sidewalls( contour, layeroffset ) {
  26500. let i = contour.length;
  26501. while ( -- i >= 0 ) {
  26502. const j = i;
  26503. let k = i - 1;
  26504. if ( k < 0 ) k = contour.length - 1;
  26505. //log('b', i,j, i-1, k,vertices.length);
  26506. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26507. const slen1 = vlen * s;
  26508. const slen2 = vlen * ( s + 1 );
  26509. const a = layeroffset + j + slen1,
  26510. b = layeroffset + k + slen1,
  26511. c = layeroffset + k + slen2,
  26512. d = layeroffset + j + slen2;
  26513. f4( a, b, c, d );
  26514. }
  26515. }
  26516. }
  26517. function v( x, y, z ) {
  26518. placeholder.push( x );
  26519. placeholder.push( y );
  26520. placeholder.push( z );
  26521. }
  26522. function f3( a, b, c ) {
  26523. addVertex( a );
  26524. addVertex( b );
  26525. addVertex( c );
  26526. const nextIndex = verticesArray.length / 3;
  26527. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26528. addUV( uvs[ 0 ] );
  26529. addUV( uvs[ 1 ] );
  26530. addUV( uvs[ 2 ] );
  26531. }
  26532. function f4( a, b, c, d ) {
  26533. addVertex( a );
  26534. addVertex( b );
  26535. addVertex( d );
  26536. addVertex( b );
  26537. addVertex( c );
  26538. addVertex( d );
  26539. const nextIndex = verticesArray.length / 3;
  26540. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26541. addUV( uvs[ 0 ] );
  26542. addUV( uvs[ 1 ] );
  26543. addUV( uvs[ 3 ] );
  26544. addUV( uvs[ 1 ] );
  26545. addUV( uvs[ 2 ] );
  26546. addUV( uvs[ 3 ] );
  26547. }
  26548. function addVertex( index ) {
  26549. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26550. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26551. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26552. }
  26553. function addUV( vector2 ) {
  26554. uvArray.push( vector2.x );
  26555. uvArray.push( vector2.y );
  26556. }
  26557. }
  26558. }
  26559. copy( source ) {
  26560. super.copy( source );
  26561. this.parameters = Object.assign( {}, source.parameters );
  26562. return this;
  26563. }
  26564. toJSON() {
  26565. const data = super.toJSON();
  26566. const shapes = this.parameters.shapes;
  26567. const options = this.parameters.options;
  26568. return toJSON$1( shapes, options, data );
  26569. }
  26570. /**
  26571. * Factory method for creating an instance of this class from the given
  26572. * JSON object.
  26573. *
  26574. * @param {Object} data - A JSON object representing the serialized geometry.
  26575. * @param {Array<Shape>} shapes - An array of shapes.
  26576. * @return {ExtrudeGeometry} A new instance.
  26577. */
  26578. static fromJSON( data, shapes ) {
  26579. const geometryShapes = [];
  26580. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26581. const shape = shapes[ data.shapes[ j ] ];
  26582. geometryShapes.push( shape );
  26583. }
  26584. const extrudePath = data.options.extrudePath;
  26585. if ( extrudePath !== undefined ) {
  26586. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26587. }
  26588. return new ExtrudeGeometry( geometryShapes, data.options );
  26589. }
  26590. }
  26591. const WorldUVGenerator = {
  26592. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26593. const a_x = vertices[ indexA * 3 ];
  26594. const a_y = vertices[ indexA * 3 + 1 ];
  26595. const b_x = vertices[ indexB * 3 ];
  26596. const b_y = vertices[ indexB * 3 + 1 ];
  26597. const c_x = vertices[ indexC * 3 ];
  26598. const c_y = vertices[ indexC * 3 + 1 ];
  26599. return [
  26600. new Vector2( a_x, a_y ),
  26601. new Vector2( b_x, b_y ),
  26602. new Vector2( c_x, c_y )
  26603. ];
  26604. },
  26605. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26606. const a_x = vertices[ indexA * 3 ];
  26607. const a_y = vertices[ indexA * 3 + 1 ];
  26608. const a_z = vertices[ indexA * 3 + 2 ];
  26609. const b_x = vertices[ indexB * 3 ];
  26610. const b_y = vertices[ indexB * 3 + 1 ];
  26611. const b_z = vertices[ indexB * 3 + 2 ];
  26612. const c_x = vertices[ indexC * 3 ];
  26613. const c_y = vertices[ indexC * 3 + 1 ];
  26614. const c_z = vertices[ indexC * 3 + 2 ];
  26615. const d_x = vertices[ indexD * 3 ];
  26616. const d_y = vertices[ indexD * 3 + 1 ];
  26617. const d_z = vertices[ indexD * 3 + 2 ];
  26618. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26619. return [
  26620. new Vector2( a_x, 1 - a_z ),
  26621. new Vector2( b_x, 1 - b_z ),
  26622. new Vector2( c_x, 1 - c_z ),
  26623. new Vector2( d_x, 1 - d_z )
  26624. ];
  26625. } else {
  26626. return [
  26627. new Vector2( a_y, 1 - a_z ),
  26628. new Vector2( b_y, 1 - b_z ),
  26629. new Vector2( c_y, 1 - c_z ),
  26630. new Vector2( d_y, 1 - d_z )
  26631. ];
  26632. }
  26633. }
  26634. };
  26635. function toJSON$1( shapes, options, data ) {
  26636. data.shapes = [];
  26637. if ( Array.isArray( shapes ) ) {
  26638. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26639. const shape = shapes[ i ];
  26640. data.shapes.push( shape.uuid );
  26641. }
  26642. } else {
  26643. data.shapes.push( shapes.uuid );
  26644. }
  26645. data.options = Object.assign( {}, options );
  26646. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26647. return data;
  26648. }
  26649. /**
  26650. * A geometry class for representing an icosahedron.
  26651. *
  26652. * ```js
  26653. * const geometry = new THREE.IcosahedronGeometry();
  26654. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26655. * const icosahedron = new THREE.Mesh( geometry, material );
  26656. * scene.add( icosahedron );
  26657. * ```
  26658. *
  26659. * @augments PolyhedronGeometry
  26660. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26661. */
  26662. class IcosahedronGeometry extends PolyhedronGeometry {
  26663. /**
  26664. * Constructs a new icosahedron geometry.
  26665. *
  26666. * @param {number} [radius=1] - Radius of the icosahedron.
  26667. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26668. */
  26669. constructor( radius = 1, detail = 0 ) {
  26670. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26671. const vertices = [
  26672. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26673. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26674. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26675. ];
  26676. const indices = [
  26677. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26678. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26679. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26680. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26681. ];
  26682. super( vertices, indices, radius, detail );
  26683. this.type = 'IcosahedronGeometry';
  26684. /**
  26685. * Holds the constructor parameters that have been
  26686. * used to generate the geometry. Any modification
  26687. * after instantiation does not change the geometry.
  26688. *
  26689. * @type {Object}
  26690. */
  26691. this.parameters = {
  26692. radius: radius,
  26693. detail: detail
  26694. };
  26695. }
  26696. /**
  26697. * Factory method for creating an instance of this class from the given
  26698. * JSON object.
  26699. *
  26700. * @param {Object} data - A JSON object representing the serialized geometry.
  26701. * @return {IcosahedronGeometry} A new instance.
  26702. */
  26703. static fromJSON( data ) {
  26704. return new IcosahedronGeometry( data.radius, data.detail );
  26705. }
  26706. }
  26707. /**
  26708. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26709. *
  26710. * ```js
  26711. * const points = [];
  26712. * for ( let i = 0; i < 10; i ++ ) {
  26713. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26714. * }
  26715. * const geometry = new THREE.LatheGeometry( points );
  26716. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26717. * const lathe = new THREE.Mesh( geometry, material );
  26718. * scene.add( lathe );
  26719. * ```
  26720. *
  26721. * @augments BufferGeometry
  26722. * @demo scenes/geometry-browser.html#LatheGeometry
  26723. */
  26724. class LatheGeometry extends BufferGeometry {
  26725. /**
  26726. * Constructs a new lathe geometry.
  26727. *
  26728. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26729. * must be greater than zero.
  26730. * @param {number} [segments=12] - The number of circumference segments to generate.
  26731. * @param {number} [phiStart=0] - The starting angle in radians.
  26732. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26733. * closed lathe, less than 2PI is a portion.
  26734. */
  26735. 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 ) {
  26736. super();
  26737. this.type = 'LatheGeometry';
  26738. /**
  26739. * Holds the constructor parameters that have been
  26740. * used to generate the geometry. Any modification
  26741. * after instantiation does not change the geometry.
  26742. *
  26743. * @type {Object}
  26744. */
  26745. this.parameters = {
  26746. points: points,
  26747. segments: segments,
  26748. phiStart: phiStart,
  26749. phiLength: phiLength
  26750. };
  26751. segments = Math.floor( segments );
  26752. // clamp phiLength so it's in range of [ 0, 2PI ]
  26753. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26754. // buffers
  26755. const indices = [];
  26756. const vertices = [];
  26757. const uvs = [];
  26758. const initNormals = [];
  26759. const normals = [];
  26760. // helper variables
  26761. const inverseSegments = 1.0 / segments;
  26762. const vertex = new Vector3();
  26763. const uv = new Vector2();
  26764. const normal = new Vector3();
  26765. const curNormal = new Vector3();
  26766. const prevNormal = new Vector3();
  26767. let dx = 0;
  26768. let dy = 0;
  26769. // pre-compute normals for initial "meridian"
  26770. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26771. switch ( j ) {
  26772. case 0: // special handling for 1st vertex on path
  26773. dx = points[ j + 1 ].x - points[ j ].x;
  26774. dy = points[ j + 1 ].y - points[ j ].y;
  26775. normal.x = dy * 1.0;
  26776. normal.y = - dx;
  26777. normal.z = dy * 0.0;
  26778. prevNormal.copy( normal );
  26779. normal.normalize();
  26780. initNormals.push( normal.x, normal.y, normal.z );
  26781. break;
  26782. case ( points.length - 1 ): // special handling for last Vertex on path
  26783. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26784. break;
  26785. default: // default handling for all vertices in between
  26786. dx = points[ j + 1 ].x - points[ j ].x;
  26787. dy = points[ j + 1 ].y - points[ j ].y;
  26788. normal.x = dy * 1.0;
  26789. normal.y = - dx;
  26790. normal.z = dy * 0.0;
  26791. curNormal.copy( normal );
  26792. normal.x += prevNormal.x;
  26793. normal.y += prevNormal.y;
  26794. normal.z += prevNormal.z;
  26795. normal.normalize();
  26796. initNormals.push( normal.x, normal.y, normal.z );
  26797. prevNormal.copy( curNormal );
  26798. }
  26799. }
  26800. // generate vertices, uvs and normals
  26801. for ( let i = 0; i <= segments; i ++ ) {
  26802. const phi = phiStart + i * inverseSegments * phiLength;
  26803. const sin = Math.sin( phi );
  26804. const cos = Math.cos( phi );
  26805. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26806. // vertex
  26807. vertex.x = points[ j ].x * sin;
  26808. vertex.y = points[ j ].y;
  26809. vertex.z = points[ j ].x * cos;
  26810. vertices.push( vertex.x, vertex.y, vertex.z );
  26811. // uv
  26812. uv.x = i / segments;
  26813. uv.y = j / ( points.length - 1 );
  26814. uvs.push( uv.x, uv.y );
  26815. // normal
  26816. const x = initNormals[ 3 * j + 0 ] * sin;
  26817. const y = initNormals[ 3 * j + 1 ];
  26818. const z = initNormals[ 3 * j + 0 ] * cos;
  26819. normals.push( x, y, z );
  26820. }
  26821. }
  26822. // indices
  26823. for ( let i = 0; i < segments; i ++ ) {
  26824. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26825. const base = j + i * points.length;
  26826. const a = base;
  26827. const b = base + points.length;
  26828. const c = base + points.length + 1;
  26829. const d = base + 1;
  26830. // faces
  26831. indices.push( a, b, d );
  26832. indices.push( c, d, b );
  26833. }
  26834. }
  26835. // build geometry
  26836. this.setIndex( indices );
  26837. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26838. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26839. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26840. }
  26841. copy( source ) {
  26842. super.copy( source );
  26843. this.parameters = Object.assign( {}, source.parameters );
  26844. return this;
  26845. }
  26846. /**
  26847. * Factory method for creating an instance of this class from the given
  26848. * JSON object.
  26849. *
  26850. * @param {Object} data - A JSON object representing the serialized geometry.
  26851. * @return {LatheGeometry} A new instance.
  26852. */
  26853. static fromJSON( data ) {
  26854. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26855. }
  26856. }
  26857. /**
  26858. * A geometry class for representing an octahedron.
  26859. *
  26860. * ```js
  26861. * const geometry = new THREE.OctahedronGeometry();
  26862. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26863. * const octahedron = new THREE.Mesh( geometry, material );
  26864. * scene.add( octahedron );
  26865. * ```
  26866. *
  26867. * @augments PolyhedronGeometry
  26868. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26869. */
  26870. class OctahedronGeometry extends PolyhedronGeometry {
  26871. /**
  26872. * Constructs a new octahedron geometry.
  26873. *
  26874. * @param {number} [radius=1] - Radius of the octahedron.
  26875. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26876. */
  26877. constructor( radius = 1, detail = 0 ) {
  26878. const vertices = [
  26879. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26880. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26881. ];
  26882. const indices = [
  26883. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26884. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26885. 1, 3, 4, 1, 4, 2
  26886. ];
  26887. super( vertices, indices, radius, detail );
  26888. this.type = 'OctahedronGeometry';
  26889. /**
  26890. * Holds the constructor parameters that have been
  26891. * used to generate the geometry. Any modification
  26892. * after instantiation does not change the geometry.
  26893. *
  26894. * @type {Object}
  26895. */
  26896. this.parameters = {
  26897. radius: radius,
  26898. detail: detail
  26899. };
  26900. }
  26901. /**
  26902. * Factory method for creating an instance of this class from the given
  26903. * JSON object.
  26904. *
  26905. * @param {Object} data - A JSON object representing the serialized geometry.
  26906. * @return {OctahedronGeometry} A new instance.
  26907. */
  26908. static fromJSON( data ) {
  26909. return new OctahedronGeometry( data.radius, data.detail );
  26910. }
  26911. }
  26912. /**
  26913. * A geometry class for representing a plane.
  26914. *
  26915. * ```js
  26916. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26917. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26918. * const plane = new THREE.Mesh( geometry, material );
  26919. * scene.add( plane );
  26920. * ```
  26921. *
  26922. * @augments BufferGeometry
  26923. * @demo scenes/geometry-browser.html#PlaneGeometry
  26924. */
  26925. class PlaneGeometry extends BufferGeometry {
  26926. /**
  26927. * Constructs a new plane geometry.
  26928. *
  26929. * @param {number} [width=1] - The width along the X axis.
  26930. * @param {number} [height=1] - The height along the Y axis
  26931. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26932. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26933. */
  26934. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26935. super();
  26936. this.type = 'PlaneGeometry';
  26937. /**
  26938. * Holds the constructor parameters that have been
  26939. * used to generate the geometry. Any modification
  26940. * after instantiation does not change the geometry.
  26941. *
  26942. * @type {Object}
  26943. */
  26944. this.parameters = {
  26945. width: width,
  26946. height: height,
  26947. widthSegments: widthSegments,
  26948. heightSegments: heightSegments
  26949. };
  26950. const width_half = width / 2;
  26951. const height_half = height / 2;
  26952. const gridX = Math.floor( widthSegments );
  26953. const gridY = Math.floor( heightSegments );
  26954. const gridX1 = gridX + 1;
  26955. const gridY1 = gridY + 1;
  26956. const segment_width = width / gridX;
  26957. const segment_height = height / gridY;
  26958. //
  26959. const indices = [];
  26960. const vertices = [];
  26961. const normals = [];
  26962. const uvs = [];
  26963. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26964. const y = iy * segment_height - height_half;
  26965. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26966. const x = ix * segment_width - width_half;
  26967. vertices.push( x, - y, 0 );
  26968. normals.push( 0, 0, 1 );
  26969. uvs.push( ix / gridX );
  26970. uvs.push( 1 - ( iy / gridY ) );
  26971. }
  26972. }
  26973. for ( let iy = 0; iy < gridY; iy ++ ) {
  26974. for ( let ix = 0; ix < gridX; ix ++ ) {
  26975. const a = ix + gridX1 * iy;
  26976. const b = ix + gridX1 * ( iy + 1 );
  26977. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26978. const d = ( ix + 1 ) + gridX1 * iy;
  26979. indices.push( a, b, d );
  26980. indices.push( b, c, d );
  26981. }
  26982. }
  26983. this.setIndex( indices );
  26984. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26985. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26986. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26987. }
  26988. copy( source ) {
  26989. super.copy( source );
  26990. this.parameters = Object.assign( {}, source.parameters );
  26991. return this;
  26992. }
  26993. /**
  26994. * Factory method for creating an instance of this class from the given
  26995. * JSON object.
  26996. *
  26997. * @param {Object} data - A JSON object representing the serialized geometry.
  26998. * @return {PlaneGeometry} A new instance.
  26999. */
  27000. static fromJSON( data ) {
  27001. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  27002. }
  27003. }
  27004. /**
  27005. * A class for generating a two-dimensional ring geometry.
  27006. *
  27007. * ```js
  27008. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  27009. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  27010. * const mesh = new THREE.Mesh( geometry, material );
  27011. * scene.add( mesh );
  27012. * ```
  27013. *
  27014. * @augments BufferGeometry
  27015. * @demo scenes/geometry-browser.html#RingGeometry
  27016. */
  27017. class RingGeometry extends BufferGeometry {
  27018. /**
  27019. * Constructs a new ring geometry.
  27020. *
  27021. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  27022. * @param {number} [outerRadius=1] - The outer radius of the ring.
  27023. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  27024. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  27025. * @param {number} [thetaStart=0] - Starting angle in radians.
  27026. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  27027. */
  27028. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27029. super();
  27030. this.type = 'RingGeometry';
  27031. /**
  27032. * Holds the constructor parameters that have been
  27033. * used to generate the geometry. Any modification
  27034. * after instantiation does not change the geometry.
  27035. *
  27036. * @type {Object}
  27037. */
  27038. this.parameters = {
  27039. innerRadius: innerRadius,
  27040. outerRadius: outerRadius,
  27041. thetaSegments: thetaSegments,
  27042. phiSegments: phiSegments,
  27043. thetaStart: thetaStart,
  27044. thetaLength: thetaLength
  27045. };
  27046. thetaSegments = Math.max( 3, thetaSegments );
  27047. phiSegments = Math.max( 1, phiSegments );
  27048. // buffers
  27049. const indices = [];
  27050. const vertices = [];
  27051. const normals = [];
  27052. const uvs = [];
  27053. // some helper variables
  27054. let radius = innerRadius;
  27055. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  27056. const vertex = new Vector3();
  27057. const uv = new Vector2();
  27058. // generate vertices, normals and uvs
  27059. for ( let j = 0; j <= phiSegments; j ++ ) {
  27060. for ( let i = 0; i <= thetaSegments; i ++ ) {
  27061. // values are generate from the inside of the ring to the outside
  27062. const segment = thetaStart + i / thetaSegments * thetaLength;
  27063. // vertex
  27064. vertex.x = radius * Math.cos( segment );
  27065. vertex.y = radius * Math.sin( segment );
  27066. vertices.push( vertex.x, vertex.y, vertex.z );
  27067. // normal
  27068. normals.push( 0, 0, 1 );
  27069. // uv
  27070. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  27071. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  27072. uvs.push( uv.x, uv.y );
  27073. }
  27074. // increase the radius for next row of vertices
  27075. radius += radiusStep;
  27076. }
  27077. // indices
  27078. for ( let j = 0; j < phiSegments; j ++ ) {
  27079. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  27080. for ( let i = 0; i < thetaSegments; i ++ ) {
  27081. const segment = i + thetaSegmentLevel;
  27082. const a = segment;
  27083. const b = segment + thetaSegments + 1;
  27084. const c = segment + thetaSegments + 2;
  27085. const d = segment + 1;
  27086. // faces
  27087. indices.push( a, b, d );
  27088. indices.push( b, c, d );
  27089. }
  27090. }
  27091. // build geometry
  27092. this.setIndex( indices );
  27093. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27094. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27095. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27096. }
  27097. copy( source ) {
  27098. super.copy( source );
  27099. this.parameters = Object.assign( {}, source.parameters );
  27100. return this;
  27101. }
  27102. /**
  27103. * Factory method for creating an instance of this class from the given
  27104. * JSON object.
  27105. *
  27106. * @param {Object} data - A JSON object representing the serialized geometry.
  27107. * @return {RingGeometry} A new instance.
  27108. */
  27109. static fromJSON( data ) {
  27110. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  27111. }
  27112. }
  27113. /**
  27114. * Creates an one-sided polygonal geometry from one or more path shapes.
  27115. *
  27116. * ```js
  27117. * const arcShape = new THREE.Shape()
  27118. * .moveTo( 5, 1 )
  27119. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  27120. *
  27121. * const geometry = new THREE.ShapeGeometry( arcShape );
  27122. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  27123. * const mesh = new THREE.Mesh( geometry, material ) ;
  27124. * scene.add( mesh );
  27125. * ```
  27126. *
  27127. * @augments BufferGeometry
  27128. * @demo scenes/geometry-browser.html#ShapeGeometry
  27129. */
  27130. class ShapeGeometry extends BufferGeometry {
  27131. /**
  27132. * Constructs a new shape geometry.
  27133. *
  27134. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  27135. * @param {number} [curveSegments=12] - Number of segments per shape.
  27136. */
  27137. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  27138. super();
  27139. this.type = 'ShapeGeometry';
  27140. /**
  27141. * Holds the constructor parameters that have been
  27142. * used to generate the geometry. Any modification
  27143. * after instantiation does not change the geometry.
  27144. *
  27145. * @type {Object}
  27146. */
  27147. this.parameters = {
  27148. shapes: shapes,
  27149. curveSegments: curveSegments
  27150. };
  27151. // buffers
  27152. const indices = [];
  27153. const vertices = [];
  27154. const normals = [];
  27155. const uvs = [];
  27156. // helper variables
  27157. let groupStart = 0;
  27158. let groupCount = 0;
  27159. // allow single and array values for "shapes" parameter
  27160. if ( Array.isArray( shapes ) === false ) {
  27161. addShape( shapes );
  27162. } else {
  27163. for ( let i = 0; i < shapes.length; i ++ ) {
  27164. addShape( shapes[ i ] );
  27165. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  27166. groupStart += groupCount;
  27167. groupCount = 0;
  27168. }
  27169. }
  27170. // build geometry
  27171. this.setIndex( indices );
  27172. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27173. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27174. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27175. // helper functions
  27176. function addShape( shape ) {
  27177. const indexOffset = vertices.length / 3;
  27178. const points = shape.extractPoints( curveSegments );
  27179. let shapeVertices = points.shape;
  27180. const shapeHoles = points.holes;
  27181. // check direction of vertices
  27182. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  27183. shapeVertices = shapeVertices.reverse();
  27184. }
  27185. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27186. const shapeHole = shapeHoles[ i ];
  27187. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  27188. shapeHoles[ i ] = shapeHole.reverse();
  27189. }
  27190. }
  27191. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  27192. // join vertices of inner and outer paths to a single array
  27193. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  27194. const shapeHole = shapeHoles[ i ];
  27195. shapeVertices = shapeVertices.concat( shapeHole );
  27196. }
  27197. // vertices, normals, uvs
  27198. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  27199. const vertex = shapeVertices[ i ];
  27200. vertices.push( vertex.x, vertex.y, 0 );
  27201. normals.push( 0, 0, 1 );
  27202. uvs.push( vertex.x, vertex.y ); // world uvs
  27203. }
  27204. // indices
  27205. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27206. const face = faces[ i ];
  27207. const a = face[ 0 ] + indexOffset;
  27208. const b = face[ 1 ] + indexOffset;
  27209. const c = face[ 2 ] + indexOffset;
  27210. indices.push( a, b, c );
  27211. groupCount += 3;
  27212. }
  27213. }
  27214. }
  27215. copy( source ) {
  27216. super.copy( source );
  27217. this.parameters = Object.assign( {}, source.parameters );
  27218. return this;
  27219. }
  27220. toJSON() {
  27221. const data = super.toJSON();
  27222. const shapes = this.parameters.shapes;
  27223. return toJSON( shapes, data );
  27224. }
  27225. /**
  27226. * Factory method for creating an instance of this class from the given
  27227. * JSON object.
  27228. *
  27229. * @param {Object} data - A JSON object representing the serialized geometry.
  27230. * @param {Array<Shape>} shapes - An array of shapes.
  27231. * @return {ShapeGeometry} A new instance.
  27232. */
  27233. static fromJSON( data, shapes ) {
  27234. const geometryShapes = [];
  27235. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27236. const shape = shapes[ data.shapes[ j ] ];
  27237. geometryShapes.push( shape );
  27238. }
  27239. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27240. }
  27241. }
  27242. function toJSON( shapes, data ) {
  27243. data.shapes = [];
  27244. if ( Array.isArray( shapes ) ) {
  27245. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27246. const shape = shapes[ i ];
  27247. data.shapes.push( shape.uuid );
  27248. }
  27249. } else {
  27250. data.shapes.push( shapes.uuid );
  27251. }
  27252. return data;
  27253. }
  27254. /**
  27255. * A class for generating a sphere geometry.
  27256. *
  27257. * ```js
  27258. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27259. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27260. * const sphere = new THREE.Mesh( geometry, material );
  27261. * scene.add( sphere );
  27262. * ```
  27263. *
  27264. * @augments BufferGeometry
  27265. * @demo scenes/geometry-browser.html#SphereGeometry
  27266. */
  27267. class SphereGeometry extends BufferGeometry {
  27268. /**
  27269. * Constructs a new sphere geometry.
  27270. *
  27271. * @param {number} [radius=1] - The sphere radius.
  27272. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27273. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27274. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27275. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27276. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27277. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27278. */
  27279. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27280. super();
  27281. this.type = 'SphereGeometry';
  27282. /**
  27283. * Holds the constructor parameters that have been
  27284. * used to generate the geometry. Any modification
  27285. * after instantiation does not change the geometry.
  27286. *
  27287. * @type {Object}
  27288. */
  27289. this.parameters = {
  27290. radius: radius,
  27291. widthSegments: widthSegments,
  27292. heightSegments: heightSegments,
  27293. phiStart: phiStart,
  27294. phiLength: phiLength,
  27295. thetaStart: thetaStart,
  27296. thetaLength: thetaLength
  27297. };
  27298. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27299. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27300. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27301. let index = 0;
  27302. const grid = [];
  27303. const vertex = new Vector3();
  27304. const normal = new Vector3();
  27305. // buffers
  27306. const indices = [];
  27307. const vertices = [];
  27308. const normals = [];
  27309. const uvs = [];
  27310. // generate vertices, normals and uvs
  27311. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27312. const verticesRow = [];
  27313. const v = iy / heightSegments;
  27314. // special case for the poles
  27315. let uOffset = 0;
  27316. if ( iy === 0 && thetaStart === 0 ) {
  27317. uOffset = 0.5 / widthSegments;
  27318. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27319. uOffset = -0.5 / widthSegments;
  27320. }
  27321. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27322. const u = ix / widthSegments;
  27323. // vertex
  27324. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27325. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27326. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27327. vertices.push( vertex.x, vertex.y, vertex.z );
  27328. // normal
  27329. normal.copy( vertex ).normalize();
  27330. normals.push( normal.x, normal.y, normal.z );
  27331. // uv
  27332. uvs.push( u + uOffset, 1 - v );
  27333. verticesRow.push( index ++ );
  27334. }
  27335. grid.push( verticesRow );
  27336. }
  27337. // indices
  27338. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27339. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27340. const a = grid[ iy ][ ix + 1 ];
  27341. const b = grid[ iy ][ ix ];
  27342. const c = grid[ iy + 1 ][ ix ];
  27343. const d = grid[ iy + 1 ][ ix + 1 ];
  27344. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27345. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27346. }
  27347. }
  27348. // build geometry
  27349. this.setIndex( indices );
  27350. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27351. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27352. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27353. }
  27354. copy( source ) {
  27355. super.copy( source );
  27356. this.parameters = Object.assign( {}, source.parameters );
  27357. return this;
  27358. }
  27359. /**
  27360. * Factory method for creating an instance of this class from the given
  27361. * JSON object.
  27362. *
  27363. * @param {Object} data - A JSON object representing the serialized geometry.
  27364. * @return {SphereGeometry} A new instance.
  27365. */
  27366. static fromJSON( data ) {
  27367. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27368. }
  27369. }
  27370. /**
  27371. * A geometry class for representing an tetrahedron.
  27372. *
  27373. * ```js
  27374. * const geometry = new THREE.TetrahedronGeometry();
  27375. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27376. * const tetrahedron = new THREE.Mesh( geometry, material );
  27377. * scene.add( tetrahedron );
  27378. * ```
  27379. *
  27380. * @augments PolyhedronGeometry
  27381. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27382. */
  27383. class TetrahedronGeometry extends PolyhedronGeometry {
  27384. /**
  27385. * Constructs a new tetrahedron geometry.
  27386. *
  27387. * @param {number} [radius=1] - Radius of the tetrahedron.
  27388. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27389. */
  27390. constructor( radius = 1, detail = 0 ) {
  27391. const vertices = [
  27392. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27393. ];
  27394. const indices = [
  27395. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27396. ];
  27397. super( vertices, indices, radius, detail );
  27398. this.type = 'TetrahedronGeometry';
  27399. /**
  27400. * Holds the constructor parameters that have been
  27401. * used to generate the geometry. Any modification
  27402. * after instantiation does not change the geometry.
  27403. *
  27404. * @type {Object}
  27405. */
  27406. this.parameters = {
  27407. radius: radius,
  27408. detail: detail
  27409. };
  27410. }
  27411. /**
  27412. * Factory method for creating an instance of this class from the given
  27413. * JSON object.
  27414. *
  27415. * @param {Object} data - A JSON object representing the serialized geometry.
  27416. * @return {TetrahedronGeometry} A new instance.
  27417. */
  27418. static fromJSON( data ) {
  27419. return new TetrahedronGeometry( data.radius, data.detail );
  27420. }
  27421. }
  27422. /**
  27423. * A geometry class for representing an torus.
  27424. *
  27425. * ```js
  27426. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27427. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27428. * const torus = new THREE.Mesh( geometry, material );
  27429. * scene.add( torus );
  27430. * ```
  27431. *
  27432. * @augments BufferGeometry
  27433. * @demo scenes/geometry-browser.html#TorusGeometry
  27434. */
  27435. class TorusGeometry extends BufferGeometry {
  27436. /**
  27437. * Constructs a new torus geometry.
  27438. *
  27439. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27440. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27441. * @param {number} [radialSegments=12] - The number of radial segments.
  27442. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27443. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27444. * @param {number} [thetaStart=0] - Start of the tubular sweep in radians.
  27445. * @param {number} [thetaLength=Math.PI*2] - Length of the tubular sweep in radians.
  27446. */
  27447. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  27448. super();
  27449. this.type = 'TorusGeometry';
  27450. /**
  27451. * Holds the constructor parameters that have been
  27452. * used to generate the geometry. Any modification
  27453. * after instantiation does not change the geometry.
  27454. *
  27455. * @type {Object}
  27456. */
  27457. this.parameters = {
  27458. radius: radius,
  27459. tube: tube,
  27460. radialSegments: radialSegments,
  27461. tubularSegments: tubularSegments,
  27462. arc: arc,
  27463. thetaStart: thetaStart,
  27464. thetaLength: thetaLength,
  27465. };
  27466. radialSegments = Math.floor( radialSegments );
  27467. tubularSegments = Math.floor( tubularSegments );
  27468. // buffers
  27469. const indices = [];
  27470. const vertices = [];
  27471. const normals = [];
  27472. const uvs = [];
  27473. // helper variables
  27474. const center = new Vector3();
  27475. const vertex = new Vector3();
  27476. const normal = new Vector3();
  27477. // generate vertices, normals and uvs
  27478. for ( let j = 0; j <= radialSegments; j ++ ) {
  27479. const v = thetaStart + ( j / radialSegments ) * thetaLength;
  27480. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27481. const u = i / tubularSegments * arc;
  27482. // vertex
  27483. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27484. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27485. vertex.z = tube * Math.sin( v );
  27486. vertices.push( vertex.x, vertex.y, vertex.z );
  27487. // normal
  27488. center.x = radius * Math.cos( u );
  27489. center.y = radius * Math.sin( u );
  27490. normal.subVectors( vertex, center ).normalize();
  27491. normals.push( normal.x, normal.y, normal.z );
  27492. // uv
  27493. uvs.push( i / tubularSegments );
  27494. uvs.push( j / radialSegments );
  27495. }
  27496. }
  27497. // generate indices
  27498. for ( let j = 1; j <= radialSegments; j ++ ) {
  27499. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27500. // indices
  27501. const a = ( tubularSegments + 1 ) * j + i - 1;
  27502. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27503. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27504. const d = ( tubularSegments + 1 ) * j + i;
  27505. // faces
  27506. indices.push( a, b, d );
  27507. indices.push( b, c, d );
  27508. }
  27509. }
  27510. // build geometry
  27511. this.setIndex( indices );
  27512. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27513. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27514. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27515. }
  27516. copy( source ) {
  27517. super.copy( source );
  27518. this.parameters = Object.assign( {}, source.parameters );
  27519. return this;
  27520. }
  27521. /**
  27522. * Factory method for creating an instance of this class from the given
  27523. * JSON object.
  27524. *
  27525. * @param {Object} data - A JSON object representing the serialized geometry.
  27526. * @return {TorusGeometry} A new instance.
  27527. */
  27528. static fromJSON( data ) {
  27529. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27530. }
  27531. }
  27532. /**
  27533. * Creates a torus knot, the particular shape of which is defined by a pair
  27534. * of coprime integers, p and q. If p and q are not coprime, the result will
  27535. * be a torus link.
  27536. *
  27537. * ```js
  27538. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27539. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27540. * const torusKnot = new THREE.Mesh( geometry, material );
  27541. * scene.add( torusKnot );
  27542. * ```
  27543. *
  27544. * @augments BufferGeometry
  27545. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27546. */
  27547. class TorusKnotGeometry extends BufferGeometry {
  27548. /**
  27549. * Constructs a new torus knot geometry.
  27550. *
  27551. * @param {number} [radius=1] - Radius of the torus knot.
  27552. * @param {number} [tube=0.4] - Radius of the tube.
  27553. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27554. * @param {number} [radialSegments=8] - The number of radial segments.
  27555. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27556. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27557. */
  27558. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27559. super();
  27560. this.type = 'TorusKnotGeometry';
  27561. /**
  27562. * Holds the constructor parameters that have been
  27563. * used to generate the geometry. Any modification
  27564. * after instantiation does not change the geometry.
  27565. *
  27566. * @type {Object}
  27567. */
  27568. this.parameters = {
  27569. radius: radius,
  27570. tube: tube,
  27571. tubularSegments: tubularSegments,
  27572. radialSegments: radialSegments,
  27573. p: p,
  27574. q: q
  27575. };
  27576. tubularSegments = Math.floor( tubularSegments );
  27577. radialSegments = Math.floor( radialSegments );
  27578. // buffers
  27579. const indices = [];
  27580. const vertices = [];
  27581. const normals = [];
  27582. const uvs = [];
  27583. // helper variables
  27584. const vertex = new Vector3();
  27585. const normal = new Vector3();
  27586. const P1 = new Vector3();
  27587. const P2 = new Vector3();
  27588. const B = new Vector3();
  27589. const T = new Vector3();
  27590. const N = new Vector3();
  27591. // generate vertices, normals and uvs
  27592. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27593. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27594. const u = i / tubularSegments * p * Math.PI * 2;
  27595. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27596. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27597. calculatePositionOnCurve( u, p, q, radius, P1 );
  27598. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27599. // calculate orthonormal basis
  27600. T.subVectors( P2, P1 );
  27601. N.addVectors( P2, P1 );
  27602. B.crossVectors( T, N );
  27603. N.crossVectors( B, T );
  27604. // normalize B, N. T can be ignored, we don't use it
  27605. B.normalize();
  27606. N.normalize();
  27607. for ( let j = 0; j <= radialSegments; ++ j ) {
  27608. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27609. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27610. const v = j / radialSegments * Math.PI * 2;
  27611. const cx = - tube * Math.cos( v );
  27612. const cy = tube * Math.sin( v );
  27613. // now calculate the final vertex position.
  27614. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27615. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27616. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27617. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27618. vertices.push( vertex.x, vertex.y, vertex.z );
  27619. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27620. normal.subVectors( vertex, P1 ).normalize();
  27621. normals.push( normal.x, normal.y, normal.z );
  27622. // uv
  27623. uvs.push( i / tubularSegments );
  27624. uvs.push( j / radialSegments );
  27625. }
  27626. }
  27627. // generate indices
  27628. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27629. for ( let i = 1; i <= radialSegments; i ++ ) {
  27630. // indices
  27631. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27632. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27633. const c = ( radialSegments + 1 ) * j + i;
  27634. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27635. // faces
  27636. indices.push( a, b, d );
  27637. indices.push( b, c, d );
  27638. }
  27639. }
  27640. // build geometry
  27641. this.setIndex( indices );
  27642. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27643. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27644. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27645. // this function calculates the current position on the torus curve
  27646. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27647. const cu = Math.cos( u );
  27648. const su = Math.sin( u );
  27649. const quOverP = q / p * u;
  27650. const cs = Math.cos( quOverP );
  27651. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27652. position.y = radius * ( 2 + cs ) * su * 0.5;
  27653. position.z = radius * Math.sin( quOverP ) * 0.5;
  27654. }
  27655. }
  27656. copy( source ) {
  27657. super.copy( source );
  27658. this.parameters = Object.assign( {}, source.parameters );
  27659. return this;
  27660. }
  27661. /**
  27662. * Factory method for creating an instance of this class from the given
  27663. * JSON object.
  27664. *
  27665. * @param {Object} data - A JSON object representing the serialized geometry.
  27666. * @return {TorusKnotGeometry} A new instance.
  27667. */
  27668. static fromJSON( data ) {
  27669. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27670. }
  27671. }
  27672. /**
  27673. * Creates a tube that extrudes along a 3D curve.
  27674. *
  27675. * ```js
  27676. * class CustomSinCurve extends THREE.Curve {
  27677. *
  27678. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27679. *
  27680. * const tx = t * 3 - 1.5;
  27681. * const ty = Math.sin( 2 * Math.PI * t );
  27682. * const tz = 0;
  27683. *
  27684. * return optionalTarget.set( tx, ty, tz );
  27685. * }
  27686. *
  27687. * }
  27688. *
  27689. * const path = new CustomSinCurve( 10 );
  27690. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27691. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27692. * const mesh = new THREE.Mesh( geometry, material );
  27693. * scene.add( mesh );
  27694. * ```
  27695. *
  27696. * @augments BufferGeometry
  27697. * @demo scenes/geometry-browser.html#TubeGeometry
  27698. */
  27699. class TubeGeometry extends BufferGeometry {
  27700. /**
  27701. * Constructs a new tube geometry.
  27702. *
  27703. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27704. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27705. * @param {number} [radius=1] -The radius of the tube.
  27706. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27707. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27708. */
  27709. 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 ) {
  27710. super();
  27711. this.type = 'TubeGeometry';
  27712. /**
  27713. * Holds the constructor parameters that have been
  27714. * used to generate the geometry. Any modification
  27715. * after instantiation does not change the geometry.
  27716. *
  27717. * @type {Object}
  27718. */
  27719. this.parameters = {
  27720. path: path,
  27721. tubularSegments: tubularSegments,
  27722. radius: radius,
  27723. radialSegments: radialSegments,
  27724. closed: closed
  27725. };
  27726. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27727. // expose internals
  27728. this.tangents = frames.tangents;
  27729. this.normals = frames.normals;
  27730. this.binormals = frames.binormals;
  27731. // helper variables
  27732. const vertex = new Vector3();
  27733. const normal = new Vector3();
  27734. const uv = new Vector2();
  27735. let P = new Vector3();
  27736. // buffer
  27737. const vertices = [];
  27738. const normals = [];
  27739. const uvs = [];
  27740. const indices = [];
  27741. // create buffer data
  27742. generateBufferData();
  27743. // build geometry
  27744. this.setIndex( indices );
  27745. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27746. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27747. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27748. // functions
  27749. function generateBufferData() {
  27750. for ( let i = 0; i < tubularSegments; i ++ ) {
  27751. generateSegment( i );
  27752. }
  27753. // if the geometry is not closed, generate the last row of vertices and normals
  27754. // at the regular position on the given path
  27755. //
  27756. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27757. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27758. // uvs are generated in a separate function.
  27759. // this makes it easy compute correct values for closed geometries
  27760. generateUVs();
  27761. // finally create faces
  27762. generateIndices();
  27763. }
  27764. function generateSegment( i ) {
  27765. // we use getPointAt to sample evenly distributed points from the given path
  27766. P = path.getPointAt( i / tubularSegments, P );
  27767. // retrieve corresponding normal and binormal
  27768. const N = frames.normals[ i ];
  27769. const B = frames.binormals[ i ];
  27770. // generate normals and vertices for the current segment
  27771. for ( let j = 0; j <= radialSegments; j ++ ) {
  27772. const v = j / radialSegments * Math.PI * 2;
  27773. const sin = Math.sin( v );
  27774. const cos = - Math.cos( v );
  27775. // normal
  27776. normal.x = ( cos * N.x + sin * B.x );
  27777. normal.y = ( cos * N.y + sin * B.y );
  27778. normal.z = ( cos * N.z + sin * B.z );
  27779. normal.normalize();
  27780. normals.push( normal.x, normal.y, normal.z );
  27781. // vertex
  27782. vertex.x = P.x + radius * normal.x;
  27783. vertex.y = P.y + radius * normal.y;
  27784. vertex.z = P.z + radius * normal.z;
  27785. vertices.push( vertex.x, vertex.y, vertex.z );
  27786. }
  27787. }
  27788. function generateIndices() {
  27789. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27790. for ( let i = 1; i <= radialSegments; i ++ ) {
  27791. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27792. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27793. const c = ( radialSegments + 1 ) * j + i;
  27794. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27795. // faces
  27796. indices.push( a, b, d );
  27797. indices.push( b, c, d );
  27798. }
  27799. }
  27800. }
  27801. function generateUVs() {
  27802. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27803. for ( let j = 0; j <= radialSegments; j ++ ) {
  27804. uv.x = i / tubularSegments;
  27805. uv.y = j / radialSegments;
  27806. uvs.push( uv.x, uv.y );
  27807. }
  27808. }
  27809. }
  27810. }
  27811. copy( source ) {
  27812. super.copy( source );
  27813. this.parameters = Object.assign( {}, source.parameters );
  27814. return this;
  27815. }
  27816. toJSON() {
  27817. const data = super.toJSON();
  27818. data.path = this.parameters.path.toJSON();
  27819. return data;
  27820. }
  27821. /**
  27822. * Factory method for creating an instance of this class from the given
  27823. * JSON object.
  27824. *
  27825. * @param {Object} data - A JSON object representing the serialized geometry.
  27826. * @return {TubeGeometry} A new instance.
  27827. */
  27828. static fromJSON( data ) {
  27829. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27830. // User defined curves or instances of CurvePath will not be deserialized.
  27831. return new TubeGeometry(
  27832. new Curves[ data.path.type ]().fromJSON( data.path ),
  27833. data.tubularSegments,
  27834. data.radius,
  27835. data.radialSegments,
  27836. data.closed
  27837. );
  27838. }
  27839. }
  27840. /**
  27841. * Can be used as a helper object to visualize a geometry as a wireframe.
  27842. *
  27843. * ```js
  27844. * const geometry = new THREE.SphereGeometry();
  27845. *
  27846. * const wireframe = new THREE.WireframeGeometry( geometry );
  27847. *
  27848. * const line = new THREE.LineSegments( wireframe );
  27849. * line.material.depthWrite = false;
  27850. * line.material.opacity = 0.25;
  27851. * line.material.transparent = true;
  27852. *
  27853. * scene.add( line );
  27854. * ```
  27855. *
  27856. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27857. *
  27858. * @augments BufferGeometry
  27859. */
  27860. class WireframeGeometry extends BufferGeometry {
  27861. /**
  27862. * Constructs a new wireframe geometry.
  27863. *
  27864. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27865. */
  27866. constructor( geometry = null ) {
  27867. super();
  27868. this.type = 'WireframeGeometry';
  27869. /**
  27870. * Holds the constructor parameters that have been
  27871. * used to generate the geometry. Any modification
  27872. * after instantiation does not change the geometry.
  27873. *
  27874. * @type {Object}
  27875. */
  27876. this.parameters = {
  27877. geometry: geometry
  27878. };
  27879. if ( geometry !== null ) {
  27880. // buffer
  27881. const vertices = [];
  27882. const edges = new Set();
  27883. // helper variables
  27884. const start = new Vector3();
  27885. const end = new Vector3();
  27886. if ( geometry.index !== null ) {
  27887. // indexed BufferGeometry
  27888. const position = geometry.attributes.position;
  27889. const indices = geometry.index;
  27890. let groups = geometry.groups;
  27891. if ( groups.length === 0 ) {
  27892. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27893. }
  27894. // create a data structure that contains all edges without duplicates
  27895. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27896. const group = groups[ o ];
  27897. const groupStart = group.start;
  27898. const groupCount = group.count;
  27899. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27900. for ( let j = 0; j < 3; j ++ ) {
  27901. const index1 = indices.getX( i + j );
  27902. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27903. start.fromBufferAttribute( position, index1 );
  27904. end.fromBufferAttribute( position, index2 );
  27905. if ( isUniqueEdge( start, end, edges ) === true ) {
  27906. vertices.push( start.x, start.y, start.z );
  27907. vertices.push( end.x, end.y, end.z );
  27908. }
  27909. }
  27910. }
  27911. }
  27912. } else {
  27913. // non-indexed BufferGeometry
  27914. const position = geometry.attributes.position;
  27915. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27916. for ( let j = 0; j < 3; j ++ ) {
  27917. // three edges per triangle, an edge is represented as (index1, index2)
  27918. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27919. const index1 = 3 * i + j;
  27920. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27921. start.fromBufferAttribute( position, index1 );
  27922. end.fromBufferAttribute( position, index2 );
  27923. if ( isUniqueEdge( start, end, edges ) === true ) {
  27924. vertices.push( start.x, start.y, start.z );
  27925. vertices.push( end.x, end.y, end.z );
  27926. }
  27927. }
  27928. }
  27929. }
  27930. // build geometry
  27931. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27932. }
  27933. }
  27934. copy( source ) {
  27935. super.copy( source );
  27936. this.parameters = Object.assign( {}, source.parameters );
  27937. return this;
  27938. }
  27939. }
  27940. function isUniqueEdge( start, end, edges ) {
  27941. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27942. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27943. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27944. return false;
  27945. } else {
  27946. edges.add( hash1 );
  27947. edges.add( hash2 );
  27948. return true;
  27949. }
  27950. }
  27951. var Geometries = /*#__PURE__*/Object.freeze({
  27952. __proto__: null,
  27953. BoxGeometry: BoxGeometry,
  27954. CapsuleGeometry: CapsuleGeometry,
  27955. CircleGeometry: CircleGeometry,
  27956. ConeGeometry: ConeGeometry,
  27957. CylinderGeometry: CylinderGeometry,
  27958. DodecahedronGeometry: DodecahedronGeometry,
  27959. EdgesGeometry: EdgesGeometry,
  27960. ExtrudeGeometry: ExtrudeGeometry,
  27961. IcosahedronGeometry: IcosahedronGeometry,
  27962. LatheGeometry: LatheGeometry,
  27963. OctahedronGeometry: OctahedronGeometry,
  27964. PlaneGeometry: PlaneGeometry,
  27965. PolyhedronGeometry: PolyhedronGeometry,
  27966. RingGeometry: RingGeometry,
  27967. ShapeGeometry: ShapeGeometry,
  27968. SphereGeometry: SphereGeometry,
  27969. TetrahedronGeometry: TetrahedronGeometry,
  27970. TorusGeometry: TorusGeometry,
  27971. TorusKnotGeometry: TorusKnotGeometry,
  27972. TubeGeometry: TubeGeometry,
  27973. WireframeGeometry: WireframeGeometry
  27974. });
  27975. /**
  27976. * This material can receive shadows, but otherwise is completely transparent.
  27977. *
  27978. * ```js
  27979. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27980. * geometry.rotateX( - Math.PI / 2 );
  27981. *
  27982. * const material = new THREE.ShadowMaterial();
  27983. * material.opacity = 0.2;
  27984. *
  27985. * const plane = new THREE.Mesh( geometry, material );
  27986. * plane.position.y = -200;
  27987. * plane.receiveShadow = true;
  27988. * scene.add( plane );
  27989. * ```
  27990. *
  27991. * @augments Material
  27992. */
  27993. class ShadowMaterial extends Material {
  27994. /**
  27995. * Constructs a new shadow material.
  27996. *
  27997. * @param {Object} [parameters] - An object with one or more properties
  27998. * defining the material's appearance. Any property of the material
  27999. * (including any property from inherited materials) can be passed
  28000. * in here. Color values can be passed any type of value accepted
  28001. * by {@link Color#set}.
  28002. */
  28003. constructor( parameters ) {
  28004. super();
  28005. /**
  28006. * This flag can be used for type testing.
  28007. *
  28008. * @type {boolean}
  28009. * @readonly
  28010. * @default true
  28011. */
  28012. this.isShadowMaterial = true;
  28013. this.type = 'ShadowMaterial';
  28014. /**
  28015. * Color of the material.
  28016. *
  28017. * @type {Color}
  28018. * @default (0,0,0)
  28019. */
  28020. this.color = new Color( 0x000000 );
  28021. /**
  28022. * Overwritten since shadow materials are transparent
  28023. * by default.
  28024. *
  28025. * @type {boolean}
  28026. * @default true
  28027. */
  28028. this.transparent = true;
  28029. /**
  28030. * Whether the material is affected by fog or not.
  28031. *
  28032. * @type {boolean}
  28033. * @default true
  28034. */
  28035. this.fog = true;
  28036. this.setValues( parameters );
  28037. }
  28038. copy( source ) {
  28039. super.copy( source );
  28040. this.color.copy( source.color );
  28041. this.fog = source.fog;
  28042. return this;
  28043. }
  28044. }
  28045. /**
  28046. * This class works just like {@link ShaderMaterial}, except that definitions
  28047. * of built-in uniforms and attributes are not automatically prepended to the
  28048. * GLSL shader code.
  28049. *
  28050. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  28051. *
  28052. * @augments ShaderMaterial
  28053. */
  28054. class RawShaderMaterial extends ShaderMaterial {
  28055. /**
  28056. * Constructs a new raw shader material.
  28057. *
  28058. * @param {Object} [parameters] - An object with one or more properties
  28059. * defining the material's appearance. Any property of the material
  28060. * (including any property from inherited materials) can be passed
  28061. * in here. Color values can be passed any type of value accepted
  28062. * by {@link Color#set}.
  28063. */
  28064. constructor( parameters ) {
  28065. super( parameters );
  28066. /**
  28067. * This flag can be used for type testing.
  28068. *
  28069. * @type {boolean}
  28070. * @readonly
  28071. * @default true
  28072. */
  28073. this.isRawShaderMaterial = true;
  28074. this.type = 'RawShaderMaterial';
  28075. }
  28076. }
  28077. /**
  28078. * A standard physically based material, using Metallic-Roughness workflow.
  28079. *
  28080. * Physically based rendering (PBR) has recently become the standard in many
  28081. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  28082. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  28083. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  28084. *
  28085. * This approach differs from older approaches in that instead of using
  28086. * approximations for the way in which light interacts with a surface, a
  28087. * physically correct model is used. The idea is that, instead of tweaking
  28088. * materials to look good under specific lighting, a material can be created
  28089. * that will react 'correctly' under all lighting scenarios.
  28090. *
  28091. * In practice this gives a more accurate and realistic looking result than
  28092. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  28093. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  28094. * shading.
  28095. *
  28096. * Note that for best results you should always specify an environment map when using this material.
  28097. *
  28098. * For a non-technical introduction to the concept of PBR and how to set up a
  28099. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  28100. *
  28101. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  28102. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  28103. *
  28104. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  28105. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  28106. * (pdf), by Brent Burley.
  28107. *
  28108. * @augments Material
  28109. * @demo scenes/material-browser.html#MeshStandardMaterial
  28110. */
  28111. class MeshStandardMaterial extends Material {
  28112. /**
  28113. * Constructs a new mesh standard material.
  28114. *
  28115. * @param {Object} [parameters] - An object with one or more properties
  28116. * defining the material's appearance. Any property of the material
  28117. * (including any property from inherited materials) can be passed
  28118. * in here. Color values can be passed any type of value accepted
  28119. * by {@link Color#set}.
  28120. */
  28121. constructor( parameters ) {
  28122. super();
  28123. /**
  28124. * This flag can be used for type testing.
  28125. *
  28126. * @type {boolean}
  28127. * @readonly
  28128. * @default true
  28129. */
  28130. this.isMeshStandardMaterial = true;
  28131. this.type = 'MeshStandardMaterial';
  28132. this.defines = { 'STANDARD': '' };
  28133. /**
  28134. * Color of the material.
  28135. *
  28136. * @type {Color}
  28137. * @default (1,1,1)
  28138. */
  28139. this.color = new Color( 0xffffff ); // diffuse
  28140. /**
  28141. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  28142. * means fully diffuse. If `roughnessMap` is also provided,
  28143. * both values are multiplied.
  28144. *
  28145. * @type {number}
  28146. * @default 1
  28147. */
  28148. this.roughness = 1.0;
  28149. /**
  28150. * How much the material is like a metal. Non-metallic materials such as wood
  28151. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  28152. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  28153. * If `metalnessMap` is also provided, both values are multiplied.
  28154. *
  28155. * @type {number}
  28156. * @default 0
  28157. */
  28158. this.metalness = 0.0;
  28159. /**
  28160. * The color map. May optionally include an alpha channel, typically combined
  28161. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28162. * color is modulated by the diffuse `color`.
  28163. *
  28164. * @type {?Texture}
  28165. * @default null
  28166. */
  28167. this.map = null;
  28168. /**
  28169. * The light map. Requires a second set of UVs.
  28170. *
  28171. * @type {?Texture}
  28172. * @default null
  28173. */
  28174. this.lightMap = null;
  28175. /**
  28176. * Intensity of the baked light.
  28177. *
  28178. * @type {number}
  28179. * @default 1
  28180. */
  28181. this.lightMapIntensity = 1.0;
  28182. /**
  28183. * The red channel of this texture is used as the ambient occlusion map.
  28184. * Requires a second set of UVs.
  28185. *
  28186. * @type {?Texture}
  28187. * @default null
  28188. */
  28189. this.aoMap = null;
  28190. /**
  28191. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28192. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28193. * red channel is also `1`, ambient light is fully occluded on a surface.
  28194. *
  28195. * @type {number}
  28196. * @default 1
  28197. */
  28198. this.aoMapIntensity = 1.0;
  28199. /**
  28200. * Emissive (light) color of the material, essentially a solid color
  28201. * unaffected by other lighting.
  28202. *
  28203. * @type {Color}
  28204. * @default (0,0,0)
  28205. */
  28206. this.emissive = new Color( 0x000000 );
  28207. /**
  28208. * Intensity of the emissive light. Modulates the emissive color.
  28209. *
  28210. * @type {number}
  28211. * @default 1
  28212. */
  28213. this.emissiveIntensity = 1.0;
  28214. /**
  28215. * Set emissive (glow) map. The emissive map color is modulated by the
  28216. * emissive color and the emissive intensity. If you have an emissive map,
  28217. * be sure to set the emissive color to something other than black.
  28218. *
  28219. * @type {?Texture}
  28220. * @default null
  28221. */
  28222. this.emissiveMap = null;
  28223. /**
  28224. * The texture to create a bump map. The black and white values map to the
  28225. * perceived depth in relation to the lights. Bump doesn't actually affect
  28226. * the geometry of the object, only the lighting. If a normal map is defined
  28227. * this will be ignored.
  28228. *
  28229. * @type {?Texture}
  28230. * @default null
  28231. */
  28232. this.bumpMap = null;
  28233. /**
  28234. * How much the bump map affects the material. Typical range is `[0,1]`.
  28235. *
  28236. * @type {number}
  28237. * @default 1
  28238. */
  28239. this.bumpScale = 1;
  28240. /**
  28241. * The texture to create a normal map. The RGB values affect the surface
  28242. * normal for each pixel fragment and change the way the color is lit. Normal
  28243. * maps do not change the actual shape of the surface, only the lighting. In
  28244. * case the material has a normal map authored using the left handed
  28245. * convention, the `y` component of `normalScale` should be negated to compensate
  28246. * for the different handedness.
  28247. *
  28248. * @type {?Texture}
  28249. * @default null
  28250. */
  28251. this.normalMap = null;
  28252. /**
  28253. * The type of normal map.
  28254. *
  28255. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28256. * @default TangentSpaceNormalMap
  28257. */
  28258. this.normalMapType = TangentSpaceNormalMap;
  28259. /**
  28260. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28261. *
  28262. * @type {Vector2}
  28263. * @default (1,1)
  28264. */
  28265. this.normalScale = new Vector2( 1, 1 );
  28266. /**
  28267. * The displacement map affects the position of the mesh's vertices. Unlike
  28268. * other maps which only affect the light and shade of the material the
  28269. * displaced vertices can cast shadows, block other objects, and otherwise
  28270. * act as real geometry. The displacement texture is an image where the value
  28271. * of each pixel (white being the highest) is mapped against, and
  28272. * repositions, the vertices of the mesh.
  28273. *
  28274. * @type {?Texture}
  28275. * @default null
  28276. */
  28277. this.displacementMap = null;
  28278. /**
  28279. * How much the displacement map affects the mesh (where black is no
  28280. * displacement, and white is maximum displacement). Without a displacement
  28281. * map set, this value is not applied.
  28282. *
  28283. * @type {number}
  28284. * @default 0
  28285. */
  28286. this.displacementScale = 1;
  28287. /**
  28288. * The offset of the displacement map's values on the mesh's vertices.
  28289. * The bias is added to the scaled sample of the displacement map.
  28290. * Without a displacement map set, this value is not applied.
  28291. *
  28292. * @type {number}
  28293. * @default 0
  28294. */
  28295. this.displacementBias = 0;
  28296. /**
  28297. * The green channel of this texture is used to alter the roughness of the
  28298. * material.
  28299. *
  28300. * @type {?Texture}
  28301. * @default null
  28302. */
  28303. this.roughnessMap = null;
  28304. /**
  28305. * The blue channel of this texture is used to alter the metalness of the
  28306. * material.
  28307. *
  28308. * @type {?Texture}
  28309. * @default null
  28310. */
  28311. this.metalnessMap = null;
  28312. /**
  28313. * The alpha map is a grayscale texture that controls the opacity across the
  28314. * surface (black: fully transparent; white: fully opaque).
  28315. *
  28316. * Only the color of the texture is used, ignoring the alpha channel if one
  28317. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28318. * when sampling this texture due to the extra bit of precision provided for
  28319. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28320. * luminance/alpha textures will also still work as expected.
  28321. *
  28322. * @type {?Texture}
  28323. * @default null
  28324. */
  28325. this.alphaMap = null;
  28326. /**
  28327. * The environment map. To ensure a physically correct rendering, environment maps
  28328. * are internally pre-processed with {@link PMREMGenerator}.
  28329. *
  28330. * @type {?Texture}
  28331. * @default null
  28332. */
  28333. this.envMap = null;
  28334. /**
  28335. * The rotation of the environment map in radians.
  28336. *
  28337. * @type {Euler}
  28338. * @default (0,0,0)
  28339. */
  28340. this.envMapRotation = new Euler();
  28341. /**
  28342. * Scales the effect of the environment map by multiplying its color.
  28343. *
  28344. * @type {number}
  28345. * @default 1
  28346. */
  28347. this.envMapIntensity = 1.0;
  28348. /**
  28349. * Renders the geometry as a wireframe.
  28350. *
  28351. * @type {boolean}
  28352. * @default false
  28353. */
  28354. this.wireframe = false;
  28355. /**
  28356. * Controls the thickness of the wireframe.
  28357. *
  28358. * Can only be used with {@link SVGRenderer}.
  28359. *
  28360. * @type {number}
  28361. * @default 1
  28362. */
  28363. this.wireframeLinewidth = 1;
  28364. /**
  28365. * Defines appearance of wireframe ends.
  28366. *
  28367. * Can only be used with {@link SVGRenderer}.
  28368. *
  28369. * @type {('round'|'bevel'|'miter')}
  28370. * @default 'round'
  28371. */
  28372. this.wireframeLinecap = 'round';
  28373. /**
  28374. * Defines appearance of wireframe joints.
  28375. *
  28376. * Can only be used with {@link SVGRenderer}.
  28377. *
  28378. * @type {('round'|'bevel'|'miter')}
  28379. * @default 'round'
  28380. */
  28381. this.wireframeLinejoin = 'round';
  28382. /**
  28383. * Whether the material is rendered with flat shading or not.
  28384. *
  28385. * @type {boolean}
  28386. * @default false
  28387. */
  28388. this.flatShading = false;
  28389. /**
  28390. * Whether the material is affected by fog or not.
  28391. *
  28392. * @type {boolean}
  28393. * @default true
  28394. */
  28395. this.fog = true;
  28396. this.setValues( parameters );
  28397. }
  28398. copy( source ) {
  28399. super.copy( source );
  28400. this.defines = { 'STANDARD': '' };
  28401. this.color.copy( source.color );
  28402. this.roughness = source.roughness;
  28403. this.metalness = source.metalness;
  28404. this.map = source.map;
  28405. this.lightMap = source.lightMap;
  28406. this.lightMapIntensity = source.lightMapIntensity;
  28407. this.aoMap = source.aoMap;
  28408. this.aoMapIntensity = source.aoMapIntensity;
  28409. this.emissive.copy( source.emissive );
  28410. this.emissiveMap = source.emissiveMap;
  28411. this.emissiveIntensity = source.emissiveIntensity;
  28412. this.bumpMap = source.bumpMap;
  28413. this.bumpScale = source.bumpScale;
  28414. this.normalMap = source.normalMap;
  28415. this.normalMapType = source.normalMapType;
  28416. this.normalScale.copy( source.normalScale );
  28417. this.displacementMap = source.displacementMap;
  28418. this.displacementScale = source.displacementScale;
  28419. this.displacementBias = source.displacementBias;
  28420. this.roughnessMap = source.roughnessMap;
  28421. this.metalnessMap = source.metalnessMap;
  28422. this.alphaMap = source.alphaMap;
  28423. this.envMap = source.envMap;
  28424. this.envMapRotation.copy( source.envMapRotation );
  28425. this.envMapIntensity = source.envMapIntensity;
  28426. this.wireframe = source.wireframe;
  28427. this.wireframeLinewidth = source.wireframeLinewidth;
  28428. this.wireframeLinecap = source.wireframeLinecap;
  28429. this.wireframeLinejoin = source.wireframeLinejoin;
  28430. this.flatShading = source.flatShading;
  28431. this.fog = source.fog;
  28432. return this;
  28433. }
  28434. }
  28435. /**
  28436. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28437. * physically-based rendering properties:
  28438. *
  28439. * - Anisotropy: Ability to represent the anisotropic property of materials
  28440. * as observable with brushed metals.
  28441. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28442. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28443. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28444. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28445. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28446. * wings of many insects.
  28447. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28448. * transparent materials are less reflective. Physically-based transmission provides a more
  28449. * realistic option for thin, transparent surfaces like glass.
  28450. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28451. * - Sheen: Can be used for representing cloth and fabric materials.
  28452. *
  28453. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28454. * higher performance cost, per pixel, than other three.js materials. Most
  28455. * effects are disabled by default, and add cost as they are enabled. For
  28456. * best results, always specify an environment map when using this material.
  28457. *
  28458. * @augments MeshStandardMaterial
  28459. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28460. */
  28461. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28462. /**
  28463. * Constructs a new mesh physical material.
  28464. *
  28465. * @param {Object} [parameters] - An object with one or more properties
  28466. * defining the material's appearance. Any property of the material
  28467. * (including any property from inherited materials) can be passed
  28468. * in here. Color values can be passed any type of value accepted
  28469. * by {@link Color#set}.
  28470. */
  28471. constructor( parameters ) {
  28472. super();
  28473. /**
  28474. * This flag can be used for type testing.
  28475. *
  28476. * @type {boolean}
  28477. * @readonly
  28478. * @default true
  28479. */
  28480. this.isMeshPhysicalMaterial = true;
  28481. this.defines = {
  28482. 'STANDARD': '',
  28483. 'PHYSICAL': ''
  28484. };
  28485. this.type = 'MeshPhysicalMaterial';
  28486. /**
  28487. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28488. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28489. * property provides additional rotation to the vectors in the texture.
  28490. *
  28491. * @type {number}
  28492. * @default 1
  28493. */
  28494. this.anisotropyRotation = 0;
  28495. /**
  28496. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28497. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28498. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28499. *
  28500. * @type {?Texture}
  28501. * @default null
  28502. */
  28503. this.anisotropyMap = null;
  28504. /**
  28505. * The red channel of this texture is multiplied against `clearcoat`,
  28506. * for per-pixel control over a coating's intensity.
  28507. *
  28508. * @type {?Texture}
  28509. * @default null
  28510. */
  28511. this.clearcoatMap = null;
  28512. /**
  28513. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28514. *
  28515. * @type {number}
  28516. * @default 0
  28517. */
  28518. this.clearcoatRoughness = 0.0;
  28519. /**
  28520. * The green channel of this texture is multiplied against
  28521. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28522. *
  28523. * @type {?Texture}
  28524. * @default null
  28525. */
  28526. this.clearcoatRoughnessMap = null;
  28527. /**
  28528. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28529. * `(0,0)` to `(1,1)`.
  28530. *
  28531. * @type {Vector2}
  28532. * @default (1,1)
  28533. */
  28534. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28535. /**
  28536. * Can be used to enable independent normals for the clear coat layer.
  28537. *
  28538. * @type {?Texture}
  28539. * @default null
  28540. */
  28541. this.clearcoatNormalMap = null;
  28542. /**
  28543. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28544. *
  28545. * @type {number}
  28546. * @default 1.5
  28547. */
  28548. this.ior = 1.5;
  28549. /**
  28550. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28551. * corresponds to an index-of-refraction of `1.5`.
  28552. *
  28553. * This models the reflectivity of non-metallic materials. It has no effect
  28554. * when `metalness` is `1.0`
  28555. *
  28556. * @name MeshPhysicalMaterial#reflectivity
  28557. * @type {number}
  28558. * @default 0.5
  28559. */
  28560. Object.defineProperty( this, 'reflectivity', {
  28561. get: function () {
  28562. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28563. },
  28564. set: function ( reflectivity ) {
  28565. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28566. }
  28567. } );
  28568. /**
  28569. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28570. * control over iridescence.
  28571. *
  28572. * @type {?Texture}
  28573. * @default null
  28574. */
  28575. this.iridescenceMap = null;
  28576. /**
  28577. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28578. * Between `1.0` to `2.333`.
  28579. *
  28580. * @type {number}
  28581. * @default 1.3
  28582. */
  28583. this.iridescenceIOR = 1.3;
  28584. /**
  28585. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28586. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28587. *
  28588. * @type {Array<number,number>}
  28589. * @default [100,400]
  28590. */
  28591. this.iridescenceThicknessRange = [ 100, 400 ];
  28592. /**
  28593. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28594. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28595. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28596. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28597. * - Values in-between will linearly interpolate between the elements of the array.
  28598. *
  28599. * @type {?Texture}
  28600. * @default null
  28601. */
  28602. this.iridescenceThicknessMap = null;
  28603. /**
  28604. * The sheen tint.
  28605. *
  28606. * @type {Color}
  28607. * @default (0,0,0)
  28608. */
  28609. this.sheenColor = new Color( 0x000000 );
  28610. /**
  28611. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28612. * over sheen tint.
  28613. *
  28614. * @type {?Texture}
  28615. * @default null
  28616. */
  28617. this.sheenColorMap = null;
  28618. /**
  28619. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28620. *
  28621. * @type {number}
  28622. * @default 1
  28623. */
  28624. this.sheenRoughness = 1.0;
  28625. /**
  28626. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28627. * over sheen roughness.
  28628. *
  28629. * @type {?Texture}
  28630. * @default null
  28631. */
  28632. this.sheenRoughnessMap = null;
  28633. /**
  28634. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28635. * optical transparency.
  28636. *
  28637. * @type {?Texture}
  28638. * @default null
  28639. */
  28640. this.transmissionMap = null;
  28641. /**
  28642. * The thickness of the volume beneath the surface. The value is given in the
  28643. * coordinate space of the mesh. If the value is `0` the material is
  28644. * thin-walled. Otherwise the material is a volume boundary.
  28645. *
  28646. * @type {number}
  28647. * @default 0
  28648. */
  28649. this.thickness = 0;
  28650. /**
  28651. * A texture that defines the thickness, stored in the green channel. This will
  28652. * be multiplied by `thickness`.
  28653. *
  28654. * @type {?Texture}
  28655. * @default null
  28656. */
  28657. this.thicknessMap = null;
  28658. /**
  28659. * Density of the medium given as the average distance that light travels in
  28660. * the medium before interacting with a particle. The value is given in world
  28661. * space units, and must be greater than zero.
  28662. *
  28663. * @type {number}
  28664. * @default Infinity
  28665. */
  28666. this.attenuationDistance = Infinity;
  28667. /**
  28668. * The color that white light turns into due to absorption when reaching the
  28669. * attenuation distance.
  28670. *
  28671. * @type {Color}
  28672. * @default (1,1,1)
  28673. */
  28674. this.attenuationColor = new Color( 1, 1, 1 );
  28675. /**
  28676. * A float that scales the amount of specular reflection for non-metals only.
  28677. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28678. *
  28679. * @type {number}
  28680. * @default 1
  28681. */
  28682. this.specularIntensity = 1.0;
  28683. /**
  28684. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28685. * for per-pixel control over specular intensity.
  28686. *
  28687. * @type {?Texture}
  28688. * @default null
  28689. */
  28690. this.specularIntensityMap = null;
  28691. /**
  28692. * Tints the specular reflection at normal incidence for non-metals only.
  28693. *
  28694. * @type {Color}
  28695. * @default (1,1,1)
  28696. */
  28697. this.specularColor = new Color( 1, 1, 1 );
  28698. /**
  28699. * The RGB channels of this texture are multiplied against `specularColor`,
  28700. * for per-pixel control over specular color.
  28701. *
  28702. * @type {?Texture}
  28703. * @default null
  28704. */
  28705. this.specularColorMap = null;
  28706. this._anisotropy = 0;
  28707. this._clearcoat = 0;
  28708. this._dispersion = 0;
  28709. this._iridescence = 0;
  28710. this._sheen = 0.0;
  28711. this._transmission = 0;
  28712. this.setValues( parameters );
  28713. }
  28714. /**
  28715. * The anisotropy strength, from `0.0` to `1.0`.
  28716. *
  28717. * @type {number}
  28718. * @default 0
  28719. */
  28720. get anisotropy() {
  28721. return this._anisotropy;
  28722. }
  28723. set anisotropy( value ) {
  28724. if ( this._anisotropy > 0 !== value > 0 ) {
  28725. this.version ++;
  28726. }
  28727. this._anisotropy = value;
  28728. }
  28729. /**
  28730. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28731. * clear coat related properties to enable multilayer materials that have a
  28732. * thin translucent layer over the base layer.
  28733. *
  28734. * @type {number}
  28735. * @default 0
  28736. */
  28737. get clearcoat() {
  28738. return this._clearcoat;
  28739. }
  28740. set clearcoat( value ) {
  28741. if ( this._clearcoat > 0 !== value > 0 ) {
  28742. this.version ++;
  28743. }
  28744. this._clearcoat = value;
  28745. }
  28746. /**
  28747. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28748. * the surface and the viewer, from `0.0` to `1.0`.
  28749. *
  28750. * @type {number}
  28751. * @default 0
  28752. */
  28753. get iridescence() {
  28754. return this._iridescence;
  28755. }
  28756. set iridescence( value ) {
  28757. if ( this._iridescence > 0 !== value > 0 ) {
  28758. this.version ++;
  28759. }
  28760. this._iridescence = value;
  28761. }
  28762. /**
  28763. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28764. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28765. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28766. *
  28767. * @type {number}
  28768. * @default 0
  28769. */
  28770. get dispersion() {
  28771. return this._dispersion;
  28772. }
  28773. set dispersion( value ) {
  28774. if ( this._dispersion > 0 !== value > 0 ) {
  28775. this.version ++;
  28776. }
  28777. this._dispersion = value;
  28778. }
  28779. /**
  28780. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28781. *
  28782. * @type {number}
  28783. * @default 0
  28784. */
  28785. get sheen() {
  28786. return this._sheen;
  28787. }
  28788. set sheen( value ) {
  28789. if ( this._sheen > 0 !== value > 0 ) {
  28790. this.version ++;
  28791. }
  28792. this._sheen = value;
  28793. }
  28794. /**
  28795. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28796. *
  28797. * Thin, transparent or semitransparent, plastic or glass materials remain
  28798. * largely reflective even if they are fully transmissive. The transmission
  28799. * property can be used to model these materials.
  28800. *
  28801. * When transmission is non-zero, `opacity` should be set to `1`.
  28802. *
  28803. * @type {number}
  28804. * @default 0
  28805. */
  28806. get transmission() {
  28807. return this._transmission;
  28808. }
  28809. set transmission( value ) {
  28810. if ( this._transmission > 0 !== value > 0 ) {
  28811. this.version ++;
  28812. }
  28813. this._transmission = value;
  28814. }
  28815. copy( source ) {
  28816. super.copy( source );
  28817. this.defines = {
  28818. 'STANDARD': '',
  28819. 'PHYSICAL': ''
  28820. };
  28821. this.anisotropy = source.anisotropy;
  28822. this.anisotropyRotation = source.anisotropyRotation;
  28823. this.anisotropyMap = source.anisotropyMap;
  28824. this.clearcoat = source.clearcoat;
  28825. this.clearcoatMap = source.clearcoatMap;
  28826. this.clearcoatRoughness = source.clearcoatRoughness;
  28827. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28828. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28829. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28830. this.dispersion = source.dispersion;
  28831. this.ior = source.ior;
  28832. this.iridescence = source.iridescence;
  28833. this.iridescenceMap = source.iridescenceMap;
  28834. this.iridescenceIOR = source.iridescenceIOR;
  28835. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28836. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28837. this.sheen = source.sheen;
  28838. this.sheenColor.copy( source.sheenColor );
  28839. this.sheenColorMap = source.sheenColorMap;
  28840. this.sheenRoughness = source.sheenRoughness;
  28841. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28842. this.transmission = source.transmission;
  28843. this.transmissionMap = source.transmissionMap;
  28844. this.thickness = source.thickness;
  28845. this.thicknessMap = source.thicknessMap;
  28846. this.attenuationDistance = source.attenuationDistance;
  28847. this.attenuationColor.copy( source.attenuationColor );
  28848. this.specularIntensity = source.specularIntensity;
  28849. this.specularIntensityMap = source.specularIntensityMap;
  28850. this.specularColor.copy( source.specularColor );
  28851. this.specularColorMap = source.specularColorMap;
  28852. return this;
  28853. }
  28854. }
  28855. /**
  28856. * A material for shiny surfaces with specular highlights.
  28857. *
  28858. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28859. * model for calculating reflectance. Unlike the Lambertian model used in the
  28860. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28861. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28862. *
  28863. * Performance will generally be greater when using this material over the
  28864. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28865. * some graphical accuracy.
  28866. *
  28867. * @augments Material
  28868. * @demo scenes/material-browser.html#MeshPhongMaterial
  28869. */
  28870. class MeshPhongMaterial extends Material {
  28871. /**
  28872. * Constructs a new mesh phong material.
  28873. *
  28874. * @param {Object} [parameters] - An object with one or more properties
  28875. * defining the material's appearance. Any property of the material
  28876. * (including any property from inherited materials) can be passed
  28877. * in here. Color values can be passed any type of value accepted
  28878. * by {@link Color#set}.
  28879. */
  28880. constructor( parameters ) {
  28881. super();
  28882. /**
  28883. * This flag can be used for type testing.
  28884. *
  28885. * @type {boolean}
  28886. * @readonly
  28887. * @default true
  28888. */
  28889. this.isMeshPhongMaterial = true;
  28890. this.type = 'MeshPhongMaterial';
  28891. /**
  28892. * Color of the material.
  28893. *
  28894. * @type {Color}
  28895. * @default (1,1,1)
  28896. */
  28897. this.color = new Color( 0xffffff ); // diffuse
  28898. /**
  28899. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28900. *
  28901. * This defines how shiny the material is and the color of its shine.
  28902. *
  28903. * @type {Color}
  28904. */
  28905. this.specular = new Color( 0x111111 );
  28906. /**
  28907. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28908. *
  28909. * @type {number}
  28910. * @default 30
  28911. */
  28912. this.shininess = 30;
  28913. /**
  28914. * The color map. May optionally include an alpha channel, typically combined
  28915. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28916. * color is modulated by the diffuse `color`.
  28917. *
  28918. * @type {?Texture}
  28919. * @default null
  28920. */
  28921. this.map = null;
  28922. /**
  28923. * The light map. Requires a second set of UVs.
  28924. *
  28925. * @type {?Texture}
  28926. * @default null
  28927. */
  28928. this.lightMap = null;
  28929. /**
  28930. * Intensity of the baked light.
  28931. *
  28932. * @type {number}
  28933. * @default 1
  28934. */
  28935. this.lightMapIntensity = 1.0;
  28936. /**
  28937. * The red channel of this texture is used as the ambient occlusion map.
  28938. * Requires a second set of UVs.
  28939. *
  28940. * @type {?Texture}
  28941. * @default null
  28942. */
  28943. this.aoMap = null;
  28944. /**
  28945. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28946. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28947. * red channel is also `1`, ambient light is fully occluded on a surface.
  28948. *
  28949. * @type {number}
  28950. * @default 1
  28951. */
  28952. this.aoMapIntensity = 1.0;
  28953. /**
  28954. * Emissive (light) color of the material, essentially a solid color
  28955. * unaffected by other lighting.
  28956. *
  28957. * @type {Color}
  28958. * @default (0,0,0)
  28959. */
  28960. this.emissive = new Color( 0x000000 );
  28961. /**
  28962. * Intensity of the emissive light. Modulates the emissive color.
  28963. *
  28964. * @type {number}
  28965. * @default 1
  28966. */
  28967. this.emissiveIntensity = 1.0;
  28968. /**
  28969. * Set emissive (glow) map. The emissive map color is modulated by the
  28970. * emissive color and the emissive intensity. If you have an emissive map,
  28971. * be sure to set the emissive color to something other than black.
  28972. *
  28973. * @type {?Texture}
  28974. * @default null
  28975. */
  28976. this.emissiveMap = null;
  28977. /**
  28978. * The texture to create a bump map. The black and white values map to the
  28979. * perceived depth in relation to the lights. Bump doesn't actually affect
  28980. * the geometry of the object, only the lighting. If a normal map is defined
  28981. * this will be ignored.
  28982. *
  28983. * @type {?Texture}
  28984. * @default null
  28985. */
  28986. this.bumpMap = null;
  28987. /**
  28988. * How much the bump map affects the material. Typical range is `[0,1]`.
  28989. *
  28990. * @type {number}
  28991. * @default 1
  28992. */
  28993. this.bumpScale = 1;
  28994. /**
  28995. * The texture to create a normal map. The RGB values affect the surface
  28996. * normal for each pixel fragment and change the way the color is lit. Normal
  28997. * maps do not change the actual shape of the surface, only the lighting. In
  28998. * case the material has a normal map authored using the left handed
  28999. * convention, the `y` component of `normalScale` should be negated to compensate
  29000. * for the different handedness.
  29001. *
  29002. * @type {?Texture}
  29003. * @default null
  29004. */
  29005. this.normalMap = null;
  29006. /**
  29007. * The type of normal map.
  29008. *
  29009. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29010. * @default TangentSpaceNormalMap
  29011. */
  29012. this.normalMapType = TangentSpaceNormalMap;
  29013. /**
  29014. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29015. *
  29016. * @type {Vector2}
  29017. * @default (1,1)
  29018. */
  29019. this.normalScale = new Vector2( 1, 1 );
  29020. /**
  29021. * The displacement map affects the position of the mesh's vertices. Unlike
  29022. * other maps which only affect the light and shade of the material the
  29023. * displaced vertices can cast shadows, block other objects, and otherwise
  29024. * act as real geometry. The displacement texture is an image where the value
  29025. * of each pixel (white being the highest) is mapped against, and
  29026. * repositions, the vertices of the mesh.
  29027. *
  29028. * @type {?Texture}
  29029. * @default null
  29030. */
  29031. this.displacementMap = null;
  29032. /**
  29033. * How much the displacement map affects the mesh (where black is no
  29034. * displacement, and white is maximum displacement). Without a displacement
  29035. * map set, this value is not applied.
  29036. *
  29037. * @type {number}
  29038. * @default 0
  29039. */
  29040. this.displacementScale = 1;
  29041. /**
  29042. * The offset of the displacement map's values on the mesh's vertices.
  29043. * The bias is added to the scaled sample of the displacement map.
  29044. * Without a displacement map set, this value is not applied.
  29045. *
  29046. * @type {number}
  29047. * @default 0
  29048. */
  29049. this.displacementBias = 0;
  29050. /**
  29051. * The specular map value affects both how much the specular surface
  29052. * highlight contributes and how much of the environment map affects the
  29053. * surface.
  29054. *
  29055. * @type {?Texture}
  29056. * @default null
  29057. */
  29058. this.specularMap = null;
  29059. /**
  29060. * The alpha map is a grayscale texture that controls the opacity across the
  29061. * surface (black: fully transparent; white: fully opaque).
  29062. *
  29063. * Only the color of the texture is used, ignoring the alpha channel if one
  29064. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29065. * when sampling this texture due to the extra bit of precision provided for
  29066. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29067. * luminance/alpha textures will also still work as expected.
  29068. *
  29069. * @type {?Texture}
  29070. * @default null
  29071. */
  29072. this.alphaMap = null;
  29073. /**
  29074. * The environment map.
  29075. *
  29076. * @type {?Texture}
  29077. * @default null
  29078. */
  29079. this.envMap = null;
  29080. /**
  29081. * The rotation of the environment map in radians.
  29082. *
  29083. * @type {Euler}
  29084. * @default (0,0,0)
  29085. */
  29086. this.envMapRotation = new Euler();
  29087. /**
  29088. * How to combine the result of the surface's color with the environment map, if any.
  29089. *
  29090. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29091. * blend between the two colors.
  29092. *
  29093. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29094. * @default MultiplyOperation
  29095. */
  29096. this.combine = MultiplyOperation;
  29097. /**
  29098. * How much the environment map affects the surface.
  29099. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29100. *
  29101. * @type {number}
  29102. * @default 1
  29103. */
  29104. this.reflectivity = 1;
  29105. /**
  29106. * The index of refraction (IOR) of air (approximately 1) divided by the
  29107. * index of refraction of the material. It is used with environment mapping
  29108. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29109. * The refraction ratio should not exceed `1`.
  29110. *
  29111. * @type {number}
  29112. * @default 0.98
  29113. */
  29114. this.refractionRatio = 0.98;
  29115. /**
  29116. * Renders the geometry as a wireframe.
  29117. *
  29118. * @type {boolean}
  29119. * @default false
  29120. */
  29121. this.wireframe = false;
  29122. /**
  29123. * Controls the thickness of the wireframe.
  29124. *
  29125. * Can only be used with {@link SVGRenderer}.
  29126. *
  29127. * @type {number}
  29128. * @default 1
  29129. */
  29130. this.wireframeLinewidth = 1;
  29131. /**
  29132. * Defines appearance of wireframe ends.
  29133. *
  29134. * Can only be used with {@link SVGRenderer}.
  29135. *
  29136. * @type {('round'|'bevel'|'miter')}
  29137. * @default 'round'
  29138. */
  29139. this.wireframeLinecap = 'round';
  29140. /**
  29141. * Defines appearance of wireframe joints.
  29142. *
  29143. * Can only be used with {@link SVGRenderer}.
  29144. *
  29145. * @type {('round'|'bevel'|'miter')}
  29146. * @default 'round'
  29147. */
  29148. this.wireframeLinejoin = 'round';
  29149. /**
  29150. * Whether the material is rendered with flat shading or not.
  29151. *
  29152. * @type {boolean}
  29153. * @default false
  29154. */
  29155. this.flatShading = false;
  29156. /**
  29157. * Whether the material is affected by fog or not.
  29158. *
  29159. * @type {boolean}
  29160. * @default true
  29161. */
  29162. this.fog = true;
  29163. this.setValues( parameters );
  29164. }
  29165. copy( source ) {
  29166. super.copy( source );
  29167. this.color.copy( source.color );
  29168. this.specular.copy( source.specular );
  29169. this.shininess = source.shininess;
  29170. this.map = source.map;
  29171. this.lightMap = source.lightMap;
  29172. this.lightMapIntensity = source.lightMapIntensity;
  29173. this.aoMap = source.aoMap;
  29174. this.aoMapIntensity = source.aoMapIntensity;
  29175. this.emissive.copy( source.emissive );
  29176. this.emissiveMap = source.emissiveMap;
  29177. this.emissiveIntensity = source.emissiveIntensity;
  29178. this.bumpMap = source.bumpMap;
  29179. this.bumpScale = source.bumpScale;
  29180. this.normalMap = source.normalMap;
  29181. this.normalMapType = source.normalMapType;
  29182. this.normalScale.copy( source.normalScale );
  29183. this.displacementMap = source.displacementMap;
  29184. this.displacementScale = source.displacementScale;
  29185. this.displacementBias = source.displacementBias;
  29186. this.specularMap = source.specularMap;
  29187. this.alphaMap = source.alphaMap;
  29188. this.envMap = source.envMap;
  29189. this.envMapRotation.copy( source.envMapRotation );
  29190. this.combine = source.combine;
  29191. this.reflectivity = source.reflectivity;
  29192. this.refractionRatio = source.refractionRatio;
  29193. this.wireframe = source.wireframe;
  29194. this.wireframeLinewidth = source.wireframeLinewidth;
  29195. this.wireframeLinecap = source.wireframeLinecap;
  29196. this.wireframeLinejoin = source.wireframeLinejoin;
  29197. this.flatShading = source.flatShading;
  29198. this.fog = source.fog;
  29199. return this;
  29200. }
  29201. }
  29202. /**
  29203. * A material implementing toon shading.
  29204. *
  29205. * @augments Material
  29206. * @demo scenes/material-browser.html#MeshToonMaterial
  29207. */
  29208. class MeshToonMaterial extends Material {
  29209. /**
  29210. * Constructs a new mesh toon material.
  29211. *
  29212. * @param {Object} [parameters] - An object with one or more properties
  29213. * defining the material's appearance. Any property of the material
  29214. * (including any property from inherited materials) can be passed
  29215. * in here. Color values can be passed any type of value accepted
  29216. * by {@link Color#set}.
  29217. */
  29218. constructor( parameters ) {
  29219. super();
  29220. /**
  29221. * This flag can be used for type testing.
  29222. *
  29223. * @type {boolean}
  29224. * @readonly
  29225. * @default true
  29226. */
  29227. this.isMeshToonMaterial = true;
  29228. this.defines = { 'TOON': '' };
  29229. this.type = 'MeshToonMaterial';
  29230. /**
  29231. * Color of the material.
  29232. *
  29233. * @type {Color}
  29234. * @default (1,1,1)
  29235. */
  29236. this.color = new Color( 0xffffff );
  29237. /**
  29238. * The color map. May optionally include an alpha channel, typically combined
  29239. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29240. * color is modulated by the diffuse `color`.
  29241. *
  29242. * @type {?Texture}
  29243. * @default null
  29244. */
  29245. this.map = null;
  29246. /**
  29247. * Gradient map for toon shading. It's required to set
  29248. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29249. * when using this type of texture.
  29250. *
  29251. * @type {?Texture}
  29252. * @default null
  29253. */
  29254. this.gradientMap = null;
  29255. /**
  29256. * The light map. Requires a second set of UVs.
  29257. *
  29258. * @type {?Texture}
  29259. * @default null
  29260. */
  29261. this.lightMap = null;
  29262. /**
  29263. * Intensity of the baked light.
  29264. *
  29265. * @type {number}
  29266. * @default 1
  29267. */
  29268. this.lightMapIntensity = 1.0;
  29269. /**
  29270. * The red channel of this texture is used as the ambient occlusion map.
  29271. * Requires a second set of UVs.
  29272. *
  29273. * @type {?Texture}
  29274. * @default null
  29275. */
  29276. this.aoMap = null;
  29277. /**
  29278. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29279. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29280. * red channel is also `1`, ambient light is fully occluded on a surface.
  29281. *
  29282. * @type {number}
  29283. * @default 1
  29284. */
  29285. this.aoMapIntensity = 1.0;
  29286. /**
  29287. * Emissive (light) color of the material, essentially a solid color
  29288. * unaffected by other lighting.
  29289. *
  29290. * @type {Color}
  29291. * @default (0,0,0)
  29292. */
  29293. this.emissive = new Color( 0x000000 );
  29294. /**
  29295. * Intensity of the emissive light. Modulates the emissive color.
  29296. *
  29297. * @type {number}
  29298. * @default 1
  29299. */
  29300. this.emissiveIntensity = 1.0;
  29301. /**
  29302. * Set emissive (glow) map. The emissive map color is modulated by the
  29303. * emissive color and the emissive intensity. If you have an emissive map,
  29304. * be sure to set the emissive color to something other than black.
  29305. *
  29306. * @type {?Texture}
  29307. * @default null
  29308. */
  29309. this.emissiveMap = null;
  29310. /**
  29311. * The texture to create a bump map. The black and white values map to the
  29312. * perceived depth in relation to the lights. Bump doesn't actually affect
  29313. * the geometry of the object, only the lighting. If a normal map is defined
  29314. * this will be ignored.
  29315. *
  29316. * @type {?Texture}
  29317. * @default null
  29318. */
  29319. this.bumpMap = null;
  29320. /**
  29321. * How much the bump map affects the material. Typical range is `[0,1]`.
  29322. *
  29323. * @type {number}
  29324. * @default 1
  29325. */
  29326. this.bumpScale = 1;
  29327. /**
  29328. * The texture to create a normal map. The RGB values affect the surface
  29329. * normal for each pixel fragment and change the way the color is lit. Normal
  29330. * maps do not change the actual shape of the surface, only the lighting. In
  29331. * case the material has a normal map authored using the left handed
  29332. * convention, the `y` component of `normalScale` should be negated to compensate
  29333. * for the different handedness.
  29334. *
  29335. * @type {?Texture}
  29336. * @default null
  29337. */
  29338. this.normalMap = null;
  29339. /**
  29340. * The type of normal map.
  29341. *
  29342. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29343. * @default TangentSpaceNormalMap
  29344. */
  29345. this.normalMapType = TangentSpaceNormalMap;
  29346. /**
  29347. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29348. *
  29349. * @type {Vector2}
  29350. * @default (1,1)
  29351. */
  29352. this.normalScale = new Vector2( 1, 1 );
  29353. /**
  29354. * The displacement map affects the position of the mesh's vertices. Unlike
  29355. * other maps which only affect the light and shade of the material the
  29356. * displaced vertices can cast shadows, block other objects, and otherwise
  29357. * act as real geometry. The displacement texture is an image where the value
  29358. * of each pixel (white being the highest) is mapped against, and
  29359. * repositions, the vertices of the mesh.
  29360. *
  29361. * @type {?Texture}
  29362. * @default null
  29363. */
  29364. this.displacementMap = null;
  29365. /**
  29366. * How much the displacement map affects the mesh (where black is no
  29367. * displacement, and white is maximum displacement). Without a displacement
  29368. * map set, this value is not applied.
  29369. *
  29370. * @type {number}
  29371. * @default 0
  29372. */
  29373. this.displacementScale = 1;
  29374. /**
  29375. * The offset of the displacement map's values on the mesh's vertices.
  29376. * The bias is added to the scaled sample of the displacement map.
  29377. * Without a displacement map set, this value is not applied.
  29378. *
  29379. * @type {number}
  29380. * @default 0
  29381. */
  29382. this.displacementBias = 0;
  29383. /**
  29384. * The alpha map is a grayscale texture that controls the opacity across the
  29385. * surface (black: fully transparent; white: fully opaque).
  29386. *
  29387. * Only the color of the texture is used, ignoring the alpha channel if one
  29388. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29389. * when sampling this texture due to the extra bit of precision provided for
  29390. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29391. * luminance/alpha textures will also still work as expected.
  29392. *
  29393. * @type {?Texture}
  29394. * @default null
  29395. */
  29396. this.alphaMap = null;
  29397. /**
  29398. * Renders the geometry as a wireframe.
  29399. *
  29400. * @type {boolean}
  29401. * @default false
  29402. */
  29403. this.wireframe = false;
  29404. /**
  29405. * Controls the thickness of the wireframe.
  29406. *
  29407. * Can only be used with {@link SVGRenderer}.
  29408. *
  29409. * @type {number}
  29410. * @default 1
  29411. */
  29412. this.wireframeLinewidth = 1;
  29413. /**
  29414. * Defines appearance of wireframe ends.
  29415. *
  29416. * Can only be used with {@link SVGRenderer}.
  29417. *
  29418. * @type {('round'|'bevel'|'miter')}
  29419. * @default 'round'
  29420. */
  29421. this.wireframeLinecap = 'round';
  29422. /**
  29423. * Defines appearance of wireframe joints.
  29424. *
  29425. * Can only be used with {@link SVGRenderer}.
  29426. *
  29427. * @type {('round'|'bevel'|'miter')}
  29428. * @default 'round'
  29429. */
  29430. this.wireframeLinejoin = 'round';
  29431. /**
  29432. * Whether the material is affected by fog or not.
  29433. *
  29434. * @type {boolean}
  29435. * @default true
  29436. */
  29437. this.fog = true;
  29438. this.setValues( parameters );
  29439. }
  29440. copy( source ) {
  29441. super.copy( source );
  29442. this.color.copy( source.color );
  29443. this.map = source.map;
  29444. this.gradientMap = source.gradientMap;
  29445. this.lightMap = source.lightMap;
  29446. this.lightMapIntensity = source.lightMapIntensity;
  29447. this.aoMap = source.aoMap;
  29448. this.aoMapIntensity = source.aoMapIntensity;
  29449. this.emissive.copy( source.emissive );
  29450. this.emissiveMap = source.emissiveMap;
  29451. this.emissiveIntensity = source.emissiveIntensity;
  29452. this.bumpMap = source.bumpMap;
  29453. this.bumpScale = source.bumpScale;
  29454. this.normalMap = source.normalMap;
  29455. this.normalMapType = source.normalMapType;
  29456. this.normalScale.copy( source.normalScale );
  29457. this.displacementMap = source.displacementMap;
  29458. this.displacementScale = source.displacementScale;
  29459. this.displacementBias = source.displacementBias;
  29460. this.alphaMap = source.alphaMap;
  29461. this.wireframe = source.wireframe;
  29462. this.wireframeLinewidth = source.wireframeLinewidth;
  29463. this.wireframeLinecap = source.wireframeLinecap;
  29464. this.wireframeLinejoin = source.wireframeLinejoin;
  29465. this.fog = source.fog;
  29466. return this;
  29467. }
  29468. }
  29469. /**
  29470. * A material that maps the normal vectors to RGB colors.
  29471. *
  29472. * @augments Material
  29473. * @demo scenes/material-browser.html#MeshNormalMaterial
  29474. */
  29475. class MeshNormalMaterial extends Material {
  29476. /**
  29477. * Constructs a new mesh normal material.
  29478. *
  29479. * @param {Object} [parameters] - An object with one or more properties
  29480. * defining the material's appearance. Any property of the material
  29481. * (including any property from inherited materials) can be passed
  29482. * in here. Color values can be passed any type of value accepted
  29483. * by {@link Color#set}.
  29484. */
  29485. constructor( parameters ) {
  29486. super();
  29487. /**
  29488. * This flag can be used for type testing.
  29489. *
  29490. * @type {boolean}
  29491. * @readonly
  29492. * @default true
  29493. */
  29494. this.isMeshNormalMaterial = true;
  29495. this.type = 'MeshNormalMaterial';
  29496. /**
  29497. * The texture to create a bump map. The black and white values map to the
  29498. * perceived depth in relation to the lights. Bump doesn't actually affect
  29499. * the geometry of the object, only the lighting. If a normal map is defined
  29500. * this will be ignored.
  29501. *
  29502. * @type {?Texture}
  29503. * @default null
  29504. */
  29505. this.bumpMap = null;
  29506. /**
  29507. * How much the bump map affects the material. Typical range is `[0,1]`.
  29508. *
  29509. * @type {number}
  29510. * @default 1
  29511. */
  29512. this.bumpScale = 1;
  29513. /**
  29514. * The texture to create a normal map. The RGB values affect the surface
  29515. * normal for each pixel fragment and change the way the color is lit. Normal
  29516. * maps do not change the actual shape of the surface, only the lighting. In
  29517. * case the material has a normal map authored using the left handed
  29518. * convention, the `y` component of `normalScale` should be negated to compensate
  29519. * for the different handedness.
  29520. *
  29521. * @type {?Texture}
  29522. * @default null
  29523. */
  29524. this.normalMap = null;
  29525. /**
  29526. * The type of normal map.
  29527. *
  29528. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29529. * @default TangentSpaceNormalMap
  29530. */
  29531. this.normalMapType = TangentSpaceNormalMap;
  29532. /**
  29533. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29534. *
  29535. * @type {Vector2}
  29536. * @default (1,1)
  29537. */
  29538. this.normalScale = new Vector2( 1, 1 );
  29539. /**
  29540. * The displacement map affects the position of the mesh's vertices. Unlike
  29541. * other maps which only affect the light and shade of the material the
  29542. * displaced vertices can cast shadows, block other objects, and otherwise
  29543. * act as real geometry. The displacement texture is an image where the value
  29544. * of each pixel (white being the highest) is mapped against, and
  29545. * repositions, the vertices of the mesh.
  29546. *
  29547. * @type {?Texture}
  29548. * @default null
  29549. */
  29550. this.displacementMap = null;
  29551. /**
  29552. * How much the displacement map affects the mesh (where black is no
  29553. * displacement, and white is maximum displacement). Without a displacement
  29554. * map set, this value is not applied.
  29555. *
  29556. * @type {number}
  29557. * @default 0
  29558. */
  29559. this.displacementScale = 1;
  29560. /**
  29561. * The offset of the displacement map's values on the mesh's vertices.
  29562. * The bias is added to the scaled sample of the displacement map.
  29563. * Without a displacement map set, this value is not applied.
  29564. *
  29565. * @type {number}
  29566. * @default 0
  29567. */
  29568. this.displacementBias = 0;
  29569. /**
  29570. * Renders the geometry as a wireframe.
  29571. *
  29572. * @type {boolean}
  29573. * @default false
  29574. */
  29575. this.wireframe = false;
  29576. /**
  29577. * Controls the thickness of the wireframe.
  29578. *
  29579. * WebGL and WebGPU ignore this property and always render
  29580. * 1 pixel wide lines.
  29581. *
  29582. * @type {number}
  29583. * @default 1
  29584. */
  29585. this.wireframeLinewidth = 1;
  29586. /**
  29587. * Whether the material is rendered with flat shading or not.
  29588. *
  29589. * @type {boolean}
  29590. * @default false
  29591. */
  29592. this.flatShading = false;
  29593. this.setValues( parameters );
  29594. }
  29595. copy( source ) {
  29596. super.copy( source );
  29597. this.bumpMap = source.bumpMap;
  29598. this.bumpScale = source.bumpScale;
  29599. this.normalMap = source.normalMap;
  29600. this.normalMapType = source.normalMapType;
  29601. this.normalScale.copy( source.normalScale );
  29602. this.displacementMap = source.displacementMap;
  29603. this.displacementScale = source.displacementScale;
  29604. this.displacementBias = source.displacementBias;
  29605. this.wireframe = source.wireframe;
  29606. this.wireframeLinewidth = source.wireframeLinewidth;
  29607. this.flatShading = source.flatShading;
  29608. return this;
  29609. }
  29610. }
  29611. /**
  29612. * A material for non-shiny surfaces, without specular highlights.
  29613. *
  29614. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29615. * model for calculating reflectance. This can simulate some surfaces (such
  29616. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29617. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29618. * shading.
  29619. *
  29620. * Due to the simplicity of the reflectance and illumination models,
  29621. * performance will be greater when using this material over the
  29622. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29623. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29624. *
  29625. * @augments Material
  29626. * @demo scenes/material-browser.html#MeshLambertMaterial
  29627. */
  29628. class MeshLambertMaterial extends Material {
  29629. /**
  29630. * Constructs a new mesh lambert material.
  29631. *
  29632. * @param {Object} [parameters] - An object with one or more properties
  29633. * defining the material's appearance. Any property of the material
  29634. * (including any property from inherited materials) can be passed
  29635. * in here. Color values can be passed any type of value accepted
  29636. * by {@link Color#set}.
  29637. */
  29638. constructor( parameters ) {
  29639. super();
  29640. /**
  29641. * This flag can be used for type testing.
  29642. *
  29643. * @type {boolean}
  29644. * @readonly
  29645. * @default true
  29646. */
  29647. this.isMeshLambertMaterial = true;
  29648. this.type = 'MeshLambertMaterial';
  29649. /**
  29650. * Color of the material.
  29651. *
  29652. * @type {Color}
  29653. * @default (1,1,1)
  29654. */
  29655. this.color = new Color( 0xffffff ); // diffuse
  29656. /**
  29657. * The color map. May optionally include an alpha channel, typically combined
  29658. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29659. * color is modulated by the diffuse `color`.
  29660. *
  29661. * @type {?Texture}
  29662. * @default null
  29663. */
  29664. this.map = null;
  29665. /**
  29666. * The light map. Requires a second set of UVs.
  29667. *
  29668. * @type {?Texture}
  29669. * @default null
  29670. */
  29671. this.lightMap = null;
  29672. /**
  29673. * Intensity of the baked light.
  29674. *
  29675. * @type {number}
  29676. * @default 1
  29677. */
  29678. this.lightMapIntensity = 1.0;
  29679. /**
  29680. * The red channel of this texture is used as the ambient occlusion map.
  29681. * Requires a second set of UVs.
  29682. *
  29683. * @type {?Texture}
  29684. * @default null
  29685. */
  29686. this.aoMap = null;
  29687. /**
  29688. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29689. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29690. * red channel is also `1`, ambient light is fully occluded on a surface.
  29691. *
  29692. * @type {number}
  29693. * @default 1
  29694. */
  29695. this.aoMapIntensity = 1.0;
  29696. /**
  29697. * Emissive (light) color of the material, essentially a solid color
  29698. * unaffected by other lighting.
  29699. *
  29700. * @type {Color}
  29701. * @default (0,0,0)
  29702. */
  29703. this.emissive = new Color( 0x000000 );
  29704. /**
  29705. * Intensity of the emissive light. Modulates the emissive color.
  29706. *
  29707. * @type {number}
  29708. * @default 1
  29709. */
  29710. this.emissiveIntensity = 1.0;
  29711. /**
  29712. * Set emissive (glow) map. The emissive map color is modulated by the
  29713. * emissive color and the emissive intensity. If you have an emissive map,
  29714. * be sure to set the emissive color to something other than black.
  29715. *
  29716. * @type {?Texture}
  29717. * @default null
  29718. */
  29719. this.emissiveMap = null;
  29720. /**
  29721. * The texture to create a bump map. The black and white values map to the
  29722. * perceived depth in relation to the lights. Bump doesn't actually affect
  29723. * the geometry of the object, only the lighting. If a normal map is defined
  29724. * this will be ignored.
  29725. *
  29726. * @type {?Texture}
  29727. * @default null
  29728. */
  29729. this.bumpMap = null;
  29730. /**
  29731. * How much the bump map affects the material. Typical range is `[0,1]`.
  29732. *
  29733. * @type {number}
  29734. * @default 1
  29735. */
  29736. this.bumpScale = 1;
  29737. /**
  29738. * The texture to create a normal map. The RGB values affect the surface
  29739. * normal for each pixel fragment and change the way the color is lit. Normal
  29740. * maps do not change the actual shape of the surface, only the lighting. In
  29741. * case the material has a normal map authored using the left handed
  29742. * convention, the `y` component of `normalScale` should be negated to compensate
  29743. * for the different handedness.
  29744. *
  29745. * @type {?Texture}
  29746. * @default null
  29747. */
  29748. this.normalMap = null;
  29749. /**
  29750. * The type of normal map.
  29751. *
  29752. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29753. * @default TangentSpaceNormalMap
  29754. */
  29755. this.normalMapType = TangentSpaceNormalMap;
  29756. /**
  29757. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29758. *
  29759. * @type {Vector2}
  29760. * @default (1,1)
  29761. */
  29762. this.normalScale = new Vector2( 1, 1 );
  29763. /**
  29764. * The displacement map affects the position of the mesh's vertices. Unlike
  29765. * other maps which only affect the light and shade of the material the
  29766. * displaced vertices can cast shadows, block other objects, and otherwise
  29767. * act as real geometry. The displacement texture is an image where the value
  29768. * of each pixel (white being the highest) is mapped against, and
  29769. * repositions, the vertices of the mesh.
  29770. *
  29771. * @type {?Texture}
  29772. * @default null
  29773. */
  29774. this.displacementMap = null;
  29775. /**
  29776. * How much the displacement map affects the mesh (where black is no
  29777. * displacement, and white is maximum displacement). Without a displacement
  29778. * map set, this value is not applied.
  29779. *
  29780. * @type {number}
  29781. * @default 0
  29782. */
  29783. this.displacementScale = 1;
  29784. /**
  29785. * The offset of the displacement map's values on the mesh's vertices.
  29786. * The bias is added to the scaled sample of the displacement map.
  29787. * Without a displacement map set, this value is not applied.
  29788. *
  29789. * @type {number}
  29790. * @default 0
  29791. */
  29792. this.displacementBias = 0;
  29793. /**
  29794. * Specular map used by the material.
  29795. *
  29796. * @type {?Texture}
  29797. * @default null
  29798. */
  29799. this.specularMap = null;
  29800. /**
  29801. * The alpha map is a grayscale texture that controls the opacity across the
  29802. * surface (black: fully transparent; white: fully opaque).
  29803. *
  29804. * Only the color of the texture is used, ignoring the alpha channel if one
  29805. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29806. * when sampling this texture due to the extra bit of precision provided for
  29807. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29808. * luminance/alpha textures will also still work as expected.
  29809. *
  29810. * @type {?Texture}
  29811. * @default null
  29812. */
  29813. this.alphaMap = null;
  29814. /**
  29815. * The environment map.
  29816. *
  29817. * @type {?Texture}
  29818. * @default null
  29819. */
  29820. this.envMap = null;
  29821. /**
  29822. * The rotation of the environment map in radians.
  29823. *
  29824. * @type {Euler}
  29825. * @default (0,0,0)
  29826. */
  29827. this.envMapRotation = new Euler();
  29828. /**
  29829. * How to combine the result of the surface's color with the environment map, if any.
  29830. *
  29831. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29832. * blend between the two colors.
  29833. *
  29834. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29835. * @default MultiplyOperation
  29836. */
  29837. this.combine = MultiplyOperation;
  29838. /**
  29839. * How much the environment map affects the surface.
  29840. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29841. *
  29842. * @type {number}
  29843. * @default 1
  29844. */
  29845. this.reflectivity = 1;
  29846. /**
  29847. * The index of refraction (IOR) of air (approximately 1) divided by the
  29848. * index of refraction of the material. It is used with environment mapping
  29849. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29850. * The refraction ratio should not exceed `1`.
  29851. *
  29852. * @type {number}
  29853. * @default 0.98
  29854. */
  29855. this.refractionRatio = 0.98;
  29856. /**
  29857. * Renders the geometry as a wireframe.
  29858. *
  29859. * @type {boolean}
  29860. * @default false
  29861. */
  29862. this.wireframe = false;
  29863. /**
  29864. * Controls the thickness of the wireframe.
  29865. *
  29866. * Can only be used with {@link SVGRenderer}.
  29867. *
  29868. * @type {number}
  29869. * @default 1
  29870. */
  29871. this.wireframeLinewidth = 1;
  29872. /**
  29873. * Defines appearance of wireframe ends.
  29874. *
  29875. * Can only be used with {@link SVGRenderer}.
  29876. *
  29877. * @type {('round'|'bevel'|'miter')}
  29878. * @default 'round'
  29879. */
  29880. this.wireframeLinecap = 'round';
  29881. /**
  29882. * Defines appearance of wireframe joints.
  29883. *
  29884. * Can only be used with {@link SVGRenderer}.
  29885. *
  29886. * @type {('round'|'bevel'|'miter')}
  29887. * @default 'round'
  29888. */
  29889. this.wireframeLinejoin = 'round';
  29890. /**
  29891. * Whether the material is rendered with flat shading or not.
  29892. *
  29893. * @type {boolean}
  29894. * @default false
  29895. */
  29896. this.flatShading = false;
  29897. /**
  29898. * Whether the material is affected by fog or not.
  29899. *
  29900. * @type {boolean}
  29901. * @default true
  29902. */
  29903. this.fog = true;
  29904. this.setValues( parameters );
  29905. }
  29906. copy( source ) {
  29907. super.copy( source );
  29908. this.color.copy( source.color );
  29909. this.map = source.map;
  29910. this.lightMap = source.lightMap;
  29911. this.lightMapIntensity = source.lightMapIntensity;
  29912. this.aoMap = source.aoMap;
  29913. this.aoMapIntensity = source.aoMapIntensity;
  29914. this.emissive.copy( source.emissive );
  29915. this.emissiveMap = source.emissiveMap;
  29916. this.emissiveIntensity = source.emissiveIntensity;
  29917. this.bumpMap = source.bumpMap;
  29918. this.bumpScale = source.bumpScale;
  29919. this.normalMap = source.normalMap;
  29920. this.normalMapType = source.normalMapType;
  29921. this.normalScale.copy( source.normalScale );
  29922. this.displacementMap = source.displacementMap;
  29923. this.displacementScale = source.displacementScale;
  29924. this.displacementBias = source.displacementBias;
  29925. this.specularMap = source.specularMap;
  29926. this.alphaMap = source.alphaMap;
  29927. this.envMap = source.envMap;
  29928. this.envMapRotation.copy( source.envMapRotation );
  29929. this.combine = source.combine;
  29930. this.reflectivity = source.reflectivity;
  29931. this.refractionRatio = source.refractionRatio;
  29932. this.wireframe = source.wireframe;
  29933. this.wireframeLinewidth = source.wireframeLinewidth;
  29934. this.wireframeLinecap = source.wireframeLinecap;
  29935. this.wireframeLinejoin = source.wireframeLinejoin;
  29936. this.flatShading = source.flatShading;
  29937. this.fog = source.fog;
  29938. return this;
  29939. }
  29940. }
  29941. /**
  29942. * A material for drawing geometry by depth. Depth is based off of the camera
  29943. * near and far plane. White is nearest, black is farthest.
  29944. *
  29945. * @augments Material
  29946. * @demo scenes/material-browser.html#MeshDepthMaterial
  29947. */
  29948. class MeshDepthMaterial extends Material {
  29949. /**
  29950. * Constructs a new mesh depth material.
  29951. *
  29952. * @param {Object} [parameters] - An object with one or more properties
  29953. * defining the material's appearance. Any property of the material
  29954. * (including any property from inherited materials) can be passed
  29955. * in here. Color values can be passed any type of value accepted
  29956. * by {@link Color#set}.
  29957. */
  29958. constructor( parameters ) {
  29959. super();
  29960. /**
  29961. * This flag can be used for type testing.
  29962. *
  29963. * @type {boolean}
  29964. * @readonly
  29965. * @default true
  29966. */
  29967. this.isMeshDepthMaterial = true;
  29968. this.type = 'MeshDepthMaterial';
  29969. /**
  29970. * Type for depth packing.
  29971. *
  29972. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29973. * @default BasicDepthPacking
  29974. */
  29975. this.depthPacking = BasicDepthPacking;
  29976. /**
  29977. * The color map. May optionally include an alpha channel, typically combined
  29978. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29979. *
  29980. * @type {?Texture}
  29981. * @default null
  29982. */
  29983. this.map = null;
  29984. /**
  29985. * The alpha map is a grayscale texture that controls the opacity across the
  29986. * surface (black: fully transparent; white: fully opaque).
  29987. *
  29988. * Only the color of the texture is used, ignoring the alpha channel if one
  29989. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29990. * when sampling this texture due to the extra bit of precision provided for
  29991. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29992. * luminance/alpha textures will also still work as expected.
  29993. *
  29994. * @type {?Texture}
  29995. * @default null
  29996. */
  29997. this.alphaMap = null;
  29998. /**
  29999. * The displacement map affects the position of the mesh's vertices. Unlike
  30000. * other maps which only affect the light and shade of the material the
  30001. * displaced vertices can cast shadows, block other objects, and otherwise
  30002. * act as real geometry. The displacement texture is an image where the value
  30003. * of each pixel (white being the highest) is mapped against, and
  30004. * repositions, the vertices of the mesh.
  30005. *
  30006. * @type {?Texture}
  30007. * @default null
  30008. */
  30009. this.displacementMap = null;
  30010. /**
  30011. * How much the displacement map affects the mesh (where black is no
  30012. * displacement, and white is maximum displacement). Without a displacement
  30013. * map set, this value is not applied.
  30014. *
  30015. * @type {number}
  30016. * @default 0
  30017. */
  30018. this.displacementScale = 1;
  30019. /**
  30020. * The offset of the displacement map's values on the mesh's vertices.
  30021. * The bias is added to the scaled sample of the displacement map.
  30022. * Without a displacement map set, this value is not applied.
  30023. *
  30024. * @type {number}
  30025. * @default 0
  30026. */
  30027. this.displacementBias = 0;
  30028. /**
  30029. * Renders the geometry as a wireframe.
  30030. *
  30031. * @type {boolean}
  30032. * @default false
  30033. */
  30034. this.wireframe = false;
  30035. /**
  30036. * Controls the thickness of the wireframe.
  30037. *
  30038. * WebGL and WebGPU ignore this property and always render
  30039. * 1 pixel wide lines.
  30040. *
  30041. * @type {number}
  30042. * @default 1
  30043. */
  30044. this.wireframeLinewidth = 1;
  30045. this.setValues( parameters );
  30046. }
  30047. copy( source ) {
  30048. super.copy( source );
  30049. this.depthPacking = source.depthPacking;
  30050. this.map = source.map;
  30051. this.alphaMap = source.alphaMap;
  30052. this.displacementMap = source.displacementMap;
  30053. this.displacementScale = source.displacementScale;
  30054. this.displacementBias = source.displacementBias;
  30055. this.wireframe = source.wireframe;
  30056. this.wireframeLinewidth = source.wireframeLinewidth;
  30057. return this;
  30058. }
  30059. }
  30060. /**
  30061. * A material used internally for implementing shadow mapping with
  30062. * point lights.
  30063. *
  30064. * Can also be used to customize the shadow casting of an object by assigning
  30065. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  30066. * The following examples demonstrates this approach in order to ensure
  30067. * transparent parts of objects do not cast shadows.
  30068. *
  30069. * @augments Material
  30070. */
  30071. class MeshDistanceMaterial extends Material {
  30072. /**
  30073. * Constructs a new mesh distance material.
  30074. *
  30075. * @param {Object} [parameters] - An object with one or more properties
  30076. * defining the material's appearance. Any property of the material
  30077. * (including any property from inherited materials) can be passed
  30078. * in here. Color values can be passed any type of value accepted
  30079. * by {@link Color#set}.
  30080. */
  30081. constructor( parameters ) {
  30082. super();
  30083. /**
  30084. * This flag can be used for type testing.
  30085. *
  30086. * @type {boolean}
  30087. * @readonly
  30088. * @default true
  30089. */
  30090. this.isMeshDistanceMaterial = true;
  30091. this.type = 'MeshDistanceMaterial';
  30092. /**
  30093. * The color map. May optionally include an alpha channel, typically combined
  30094. * with {@link Material#transparent} or {@link Material#alphaTest}.
  30095. *
  30096. * @type {?Texture}
  30097. * @default null
  30098. */
  30099. this.map = null;
  30100. /**
  30101. * The alpha map is a grayscale texture that controls the opacity across the
  30102. * surface (black: fully transparent; white: fully opaque).
  30103. *
  30104. * Only the color of the texture is used, ignoring the alpha channel if one
  30105. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30106. * when sampling this texture due to the extra bit of precision provided for
  30107. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30108. * luminance/alpha textures will also still work as expected.
  30109. *
  30110. * @type {?Texture}
  30111. * @default null
  30112. */
  30113. this.alphaMap = null;
  30114. /**
  30115. * The displacement map affects the position of the mesh's vertices. Unlike
  30116. * other maps which only affect the light and shade of the material the
  30117. * displaced vertices can cast shadows, block other objects, and otherwise
  30118. * act as real geometry. The displacement texture is an image where the value
  30119. * of each pixel (white being the highest) is mapped against, and
  30120. * repositions, the vertices of the mesh.
  30121. *
  30122. * @type {?Texture}
  30123. * @default null
  30124. */
  30125. this.displacementMap = null;
  30126. /**
  30127. * How much the displacement map affects the mesh (where black is no
  30128. * displacement, and white is maximum displacement). Without a displacement
  30129. * map set, this value is not applied.
  30130. *
  30131. * @type {number}
  30132. * @default 0
  30133. */
  30134. this.displacementScale = 1;
  30135. /**
  30136. * The offset of the displacement map's values on the mesh's vertices.
  30137. * The bias is added to the scaled sample of the displacement map.
  30138. * Without a displacement map set, this value is not applied.
  30139. *
  30140. * @type {number}
  30141. * @default 0
  30142. */
  30143. this.displacementBias = 0;
  30144. this.setValues( parameters );
  30145. }
  30146. copy( source ) {
  30147. super.copy( source );
  30148. this.map = source.map;
  30149. this.alphaMap = source.alphaMap;
  30150. this.displacementMap = source.displacementMap;
  30151. this.displacementScale = source.displacementScale;
  30152. this.displacementBias = source.displacementBias;
  30153. return this;
  30154. }
  30155. }
  30156. /**
  30157. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  30158. * material color and shading.
  30159. *
  30160. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  30161. * baked lighting. It will cast a shadow onto an object that receives shadows
  30162. * (and shadow clipping works), but it will not self-shadow or receive
  30163. * shadows.
  30164. *
  30165. * @augments Material
  30166. * @demo scenes/material-browser.html#MeshMatcapMaterial
  30167. */
  30168. class MeshMatcapMaterial extends Material {
  30169. /**
  30170. * Constructs a new mesh matcap material.
  30171. *
  30172. * @param {Object} [parameters] - An object with one or more properties
  30173. * defining the material's appearance. Any property of the material
  30174. * (including any property from inherited materials) can be passed
  30175. * in here. Color values can be passed any type of value accepted
  30176. * by {@link Color#set}.
  30177. */
  30178. constructor( parameters ) {
  30179. super();
  30180. /**
  30181. * This flag can be used for type testing.
  30182. *
  30183. * @type {boolean}
  30184. * @readonly
  30185. * @default true
  30186. */
  30187. this.isMeshMatcapMaterial = true;
  30188. this.defines = { 'MATCAP': '' };
  30189. this.type = 'MeshMatcapMaterial';
  30190. /**
  30191. * Color of the material.
  30192. *
  30193. * @type {Color}
  30194. * @default (1,1,1)
  30195. */
  30196. this.color = new Color( 0xffffff ); // diffuse
  30197. /**
  30198. * The matcap map.
  30199. *
  30200. * @type {?Texture}
  30201. * @default null
  30202. */
  30203. this.matcap = null;
  30204. /**
  30205. * The color map. May optionally include an alpha channel, typically combined
  30206. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30207. * color is modulated by the diffuse `color`.
  30208. *
  30209. * @type {?Texture}
  30210. * @default null
  30211. */
  30212. this.map = null;
  30213. /**
  30214. * The texture to create a bump map. The black and white values map to the
  30215. * perceived depth in relation to the lights. Bump doesn't actually affect
  30216. * the geometry of the object, only the lighting. If a normal map is defined
  30217. * this will be ignored.
  30218. *
  30219. * @type {?Texture}
  30220. * @default null
  30221. */
  30222. this.bumpMap = null;
  30223. /**
  30224. * How much the bump map affects the material. Typical range is `[0,1]`.
  30225. *
  30226. * @type {number}
  30227. * @default 1
  30228. */
  30229. this.bumpScale = 1;
  30230. /**
  30231. * The texture to create a normal map. The RGB values affect the surface
  30232. * normal for each pixel fragment and change the way the color is lit. Normal
  30233. * maps do not change the actual shape of the surface, only the lighting. In
  30234. * case the material has a normal map authored using the left handed
  30235. * convention, the `y` component of `normalScale` should be negated to compensate
  30236. * for the different handedness.
  30237. *
  30238. * @type {?Texture}
  30239. * @default null
  30240. */
  30241. this.normalMap = null;
  30242. /**
  30243. * The type of normal map.
  30244. *
  30245. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30246. * @default TangentSpaceNormalMap
  30247. */
  30248. this.normalMapType = TangentSpaceNormalMap;
  30249. /**
  30250. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30251. *
  30252. * @type {Vector2}
  30253. * @default (1,1)
  30254. */
  30255. this.normalScale = new Vector2( 1, 1 );
  30256. /**
  30257. * The displacement map affects the position of the mesh's vertices. Unlike
  30258. * other maps which only affect the light and shade of the material the
  30259. * displaced vertices can cast shadows, block other objects, and otherwise
  30260. * act as real geometry. The displacement texture is an image where the value
  30261. * of each pixel (white being the highest) is mapped against, and
  30262. * repositions, the vertices of the mesh.
  30263. *
  30264. * @type {?Texture}
  30265. * @default null
  30266. */
  30267. this.displacementMap = null;
  30268. /**
  30269. * How much the displacement map affects the mesh (where black is no
  30270. * displacement, and white is maximum displacement). Without a displacement
  30271. * map set, this value is not applied.
  30272. *
  30273. * @type {number}
  30274. * @default 0
  30275. */
  30276. this.displacementScale = 1;
  30277. /**
  30278. * The offset of the displacement map's values on the mesh's vertices.
  30279. * The bias is added to the scaled sample of the displacement map.
  30280. * Without a displacement map set, this value is not applied.
  30281. *
  30282. * @type {number}
  30283. * @default 0
  30284. */
  30285. this.displacementBias = 0;
  30286. /**
  30287. * The alpha map is a grayscale texture that controls the opacity across the
  30288. * surface (black: fully transparent; white: fully opaque).
  30289. *
  30290. * Only the color of the texture is used, ignoring the alpha channel if one
  30291. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30292. * when sampling this texture due to the extra bit of precision provided for
  30293. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30294. * luminance/alpha textures will also still work as expected.
  30295. *
  30296. * @type {?Texture}
  30297. * @default null
  30298. */
  30299. this.alphaMap = null;
  30300. /**
  30301. * Renders the geometry as a wireframe.
  30302. *
  30303. * @type {boolean}
  30304. * @default false
  30305. */
  30306. this.wireframe = false;
  30307. /**
  30308. * Controls the thickness of the wireframe.
  30309. *
  30310. * Can only be used with {@link SVGRenderer}.
  30311. *
  30312. * @type {number}
  30313. * @default 1
  30314. */
  30315. this.wireframeLinewidth = 1;
  30316. /**
  30317. * Whether the material is rendered with flat shading or not.
  30318. *
  30319. * @type {boolean}
  30320. * @default false
  30321. */
  30322. this.flatShading = false;
  30323. /**
  30324. * Whether the material is affected by fog or not.
  30325. *
  30326. * @type {boolean}
  30327. * @default true
  30328. */
  30329. this.fog = true;
  30330. this.setValues( parameters );
  30331. }
  30332. copy( source ) {
  30333. super.copy( source );
  30334. this.defines = { 'MATCAP': '' };
  30335. this.color.copy( source.color );
  30336. this.matcap = source.matcap;
  30337. this.map = source.map;
  30338. this.bumpMap = source.bumpMap;
  30339. this.bumpScale = source.bumpScale;
  30340. this.normalMap = source.normalMap;
  30341. this.normalMapType = source.normalMapType;
  30342. this.normalScale.copy( source.normalScale );
  30343. this.displacementMap = source.displacementMap;
  30344. this.displacementScale = source.displacementScale;
  30345. this.displacementBias = source.displacementBias;
  30346. this.alphaMap = source.alphaMap;
  30347. this.wireframe = source.wireframe;
  30348. this.wireframeLinewidth = source.wireframeLinewidth;
  30349. this.flatShading = source.flatShading;
  30350. this.fog = source.fog;
  30351. return this;
  30352. }
  30353. }
  30354. /**
  30355. * A material for rendering line primitives.
  30356. *
  30357. * Materials define the appearance of renderable 3D objects.
  30358. *
  30359. * ```js
  30360. * const material = new THREE.LineDashedMaterial( {
  30361. * color: 0xffffff,
  30362. * scale: 1,
  30363. * dashSize: 3,
  30364. * gapSize: 1,
  30365. * } );
  30366. * ```
  30367. *
  30368. * @augments LineBasicMaterial
  30369. */
  30370. class LineDashedMaterial extends LineBasicMaterial {
  30371. /**
  30372. * Constructs a new line dashed material.
  30373. *
  30374. * @param {Object} [parameters] - An object with one or more properties
  30375. * defining the material's appearance. Any property of the material
  30376. * (including any property from inherited materials) can be passed
  30377. * in here. Color values can be passed any type of value accepted
  30378. * by {@link Color#set}.
  30379. */
  30380. constructor( parameters ) {
  30381. super();
  30382. /**
  30383. * This flag can be used for type testing.
  30384. *
  30385. * @type {boolean}
  30386. * @readonly
  30387. * @default true
  30388. */
  30389. this.isLineDashedMaterial = true;
  30390. this.type = 'LineDashedMaterial';
  30391. /**
  30392. * The scale of the dashed part of a line.
  30393. *
  30394. * @type {number}
  30395. * @default 1
  30396. */
  30397. this.scale = 1;
  30398. /**
  30399. * The size of the dash. This is both the gap with the stroke.
  30400. *
  30401. * @type {number}
  30402. * @default 3
  30403. */
  30404. this.dashSize = 3;
  30405. /**
  30406. * The size of the gap.
  30407. *
  30408. * @type {number}
  30409. * @default 1
  30410. */
  30411. this.gapSize = 1;
  30412. this.setValues( parameters );
  30413. }
  30414. copy( source ) {
  30415. super.copy( source );
  30416. this.scale = source.scale;
  30417. this.dashSize = source.dashSize;
  30418. this.gapSize = source.gapSize;
  30419. return this;
  30420. }
  30421. }
  30422. /**
  30423. * Converts an array to a specific type.
  30424. *
  30425. * @param {TypedArray|Array} array - The array to convert.
  30426. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30427. * @return {TypedArray} The converted array.
  30428. */
  30429. function convertArray( array, type ) {
  30430. if ( ! array || array.constructor === type ) return array;
  30431. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30432. return new type( array ); // create typed array
  30433. }
  30434. return Array.prototype.slice.call( array ); // create Array
  30435. }
  30436. /**
  30437. * Returns an array by which times and values can be sorted.
  30438. *
  30439. * @param {Array<number>} times - The keyframe time values.
  30440. * @return {Array<number>} The array.
  30441. */
  30442. function getKeyframeOrder( times ) {
  30443. function compareTime( i, j ) {
  30444. return times[ i ] - times[ j ];
  30445. }
  30446. const n = times.length;
  30447. const result = new Array( n );
  30448. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30449. result.sort( compareTime );
  30450. return result;
  30451. }
  30452. /**
  30453. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30454. *
  30455. * @param {Array<number>} values - The values to sort.
  30456. * @param {number} stride - The stride.
  30457. * @param {Array<number>} order - The sort order.
  30458. * @return {Array<number>} The sorted values.
  30459. */
  30460. function sortedArray( values, stride, order ) {
  30461. const nValues = values.length;
  30462. const result = new values.constructor( nValues );
  30463. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30464. const srcOffset = order[ i ] * stride;
  30465. for ( let j = 0; j !== stride; ++ j ) {
  30466. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30467. }
  30468. }
  30469. return result;
  30470. }
  30471. /**
  30472. * Used for parsing AOS keyframe formats.
  30473. *
  30474. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30475. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30476. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30477. * @param {string} valuePropertyName - The name of the property to use.
  30478. */
  30479. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30480. let i = 1, key = jsonKeys[ 0 ];
  30481. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30482. key = jsonKeys[ i ++ ];
  30483. }
  30484. if ( key === undefined ) return; // no data
  30485. let value = key[ valuePropertyName ];
  30486. if ( value === undefined ) return; // no data
  30487. if ( Array.isArray( value ) ) {
  30488. do {
  30489. value = key[ valuePropertyName ];
  30490. if ( value !== undefined ) {
  30491. times.push( key.time );
  30492. values.push( ...value ); // push all elements
  30493. }
  30494. key = jsonKeys[ i ++ ];
  30495. } while ( key !== undefined );
  30496. } else if ( value.toArray !== undefined ) {
  30497. // ...assume THREE.Math-ish
  30498. do {
  30499. value = key[ valuePropertyName ];
  30500. if ( value !== undefined ) {
  30501. times.push( key.time );
  30502. value.toArray( values, values.length );
  30503. }
  30504. key = jsonKeys[ i ++ ];
  30505. } while ( key !== undefined );
  30506. } else {
  30507. // otherwise push as-is
  30508. do {
  30509. value = key[ valuePropertyName ];
  30510. if ( value !== undefined ) {
  30511. times.push( key.time );
  30512. values.push( value );
  30513. }
  30514. key = jsonKeys[ i ++ ];
  30515. } while ( key !== undefined );
  30516. }
  30517. }
  30518. /**
  30519. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30520. *
  30521. * @param {AnimationClip} sourceClip - The values to sort.
  30522. * @param {string} name - The name of the clip.
  30523. * @param {number} startFrame - The start frame.
  30524. * @param {number} endFrame - The end frame.
  30525. * @param {number} [fps=30] - The FPS.
  30526. * @return {AnimationClip} The new sub clip.
  30527. */
  30528. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30529. const clip = sourceClip.clone();
  30530. clip.name = name;
  30531. const tracks = [];
  30532. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30533. const track = clip.tracks[ i ];
  30534. const valueSize = track.getValueSize();
  30535. const times = [];
  30536. const values = [];
  30537. for ( let j = 0; j < track.times.length; ++ j ) {
  30538. const frame = track.times[ j ] * fps;
  30539. if ( frame < startFrame || frame >= endFrame ) continue;
  30540. times.push( track.times[ j ] );
  30541. for ( let k = 0; k < valueSize; ++ k ) {
  30542. values.push( track.values[ j * valueSize + k ] );
  30543. }
  30544. }
  30545. if ( times.length === 0 ) continue;
  30546. track.times = convertArray( times, track.times.constructor );
  30547. track.values = convertArray( values, track.values.constructor );
  30548. tracks.push( track );
  30549. }
  30550. clip.tracks = tracks;
  30551. // find minimum .times value across all tracks in the trimmed clip
  30552. let minStartTime = Infinity;
  30553. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30554. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30555. minStartTime = clip.tracks[ i ].times[ 0 ];
  30556. }
  30557. }
  30558. // shift all tracks such that clip begins at t=0
  30559. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30560. clip.tracks[ i ].shift( -1 * minStartTime );
  30561. }
  30562. clip.resetDuration();
  30563. return clip;
  30564. }
  30565. /**
  30566. * Converts the keyframes of the given animation clip to an additive format.
  30567. *
  30568. * @param {AnimationClip} targetClip - The clip to make additive.
  30569. * @param {number} [referenceFrame=0] - The reference frame.
  30570. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30571. * @param {number} [fps=30] - The FPS.
  30572. * @return {AnimationClip} The updated clip which is now additive.
  30573. */
  30574. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30575. if ( fps <= 0 ) fps = 30;
  30576. const numTracks = referenceClip.tracks.length;
  30577. const referenceTime = referenceFrame / fps;
  30578. // Make each track's values relative to the values at the reference frame
  30579. for ( let i = 0; i < numTracks; ++ i ) {
  30580. const referenceTrack = referenceClip.tracks[ i ];
  30581. const referenceTrackType = referenceTrack.ValueTypeName;
  30582. // Skip this track if it's non-numeric
  30583. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30584. // Find the track in the target clip whose name and type matches the reference track
  30585. const targetTrack = targetClip.tracks.find( function ( track ) {
  30586. return track.name === referenceTrack.name
  30587. && track.ValueTypeName === referenceTrackType;
  30588. } );
  30589. if ( targetTrack === undefined ) continue;
  30590. let referenceOffset = 0;
  30591. const referenceValueSize = referenceTrack.getValueSize();
  30592. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30593. referenceOffset = referenceValueSize / 3;
  30594. }
  30595. let targetOffset = 0;
  30596. const targetValueSize = targetTrack.getValueSize();
  30597. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30598. targetOffset = targetValueSize / 3;
  30599. }
  30600. const lastIndex = referenceTrack.times.length - 1;
  30601. let referenceValue;
  30602. // Find the value to subtract out of the track
  30603. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30604. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30605. const startIndex = referenceOffset;
  30606. const endIndex = referenceValueSize - referenceOffset;
  30607. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30608. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30609. // Reference frame is after the last keyframe, so just use the last keyframe
  30610. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30611. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30612. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30613. } else {
  30614. // Interpolate to the reference value
  30615. const interpolant = referenceTrack.createInterpolant();
  30616. const startIndex = referenceOffset;
  30617. const endIndex = referenceValueSize - referenceOffset;
  30618. interpolant.evaluate( referenceTime );
  30619. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30620. }
  30621. // Conjugate the quaternion
  30622. if ( referenceTrackType === 'quaternion' ) {
  30623. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30624. referenceQuat.toArray( referenceValue );
  30625. }
  30626. // Subtract the reference value from all of the track values
  30627. const numTimes = targetTrack.times.length;
  30628. for ( let j = 0; j < numTimes; ++ j ) {
  30629. const valueStart = j * targetValueSize + targetOffset;
  30630. if ( referenceTrackType === 'quaternion' ) {
  30631. // Multiply the conjugate for quaternion track types
  30632. Quaternion.multiplyQuaternionsFlat(
  30633. targetTrack.values,
  30634. valueStart,
  30635. referenceValue,
  30636. 0,
  30637. targetTrack.values,
  30638. valueStart
  30639. );
  30640. } else {
  30641. const valueEnd = targetValueSize - targetOffset * 2;
  30642. // Subtract each value for all other numeric track types
  30643. for ( let k = 0; k < valueEnd; ++ k ) {
  30644. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30645. }
  30646. }
  30647. }
  30648. }
  30649. targetClip.blendMode = AdditiveAnimationBlendMode;
  30650. return targetClip;
  30651. }
  30652. /**
  30653. * A class with various methods to assist with animations.
  30654. *
  30655. * @hideconstructor
  30656. */
  30657. class AnimationUtils {
  30658. /**
  30659. * Converts an array to a specific type
  30660. *
  30661. * @static
  30662. * @param {TypedArray|Array} array - The array to convert.
  30663. * @param {TypedArray.constructor} type - The constructor of a type array.
  30664. * @return {TypedArray} The converted array
  30665. */
  30666. static convertArray( array, type ) {
  30667. return convertArray( array, type );
  30668. }
  30669. /**
  30670. * Returns `true` if the given object is a typed array.
  30671. *
  30672. * @static
  30673. * @param {any} object - The object to check.
  30674. * @return {boolean} Whether the given object is a typed array.
  30675. */
  30676. static isTypedArray( object ) {
  30677. return isTypedArray( object );
  30678. }
  30679. /**
  30680. * Returns an array by which times and values can be sorted.
  30681. *
  30682. * @static
  30683. * @param {Array<number>} times - The keyframe time values.
  30684. * @return {Array<number>} The array.
  30685. */
  30686. static getKeyframeOrder( times ) {
  30687. return getKeyframeOrder( times );
  30688. }
  30689. /**
  30690. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30691. *
  30692. * @static
  30693. * @param {Array<number>} values - The values to sort.
  30694. * @param {number} stride - The stride.
  30695. * @param {Array<number>} order - The sort order.
  30696. * @return {Array<number>} The sorted values.
  30697. */
  30698. static sortedArray( values, stride, order ) {
  30699. return sortedArray( values, stride, order );
  30700. }
  30701. /**
  30702. * Used for parsing AOS keyframe formats.
  30703. *
  30704. * @static
  30705. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30706. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30707. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30708. * @param {string} valuePropertyName - The name of the property to use.
  30709. */
  30710. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30711. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30712. }
  30713. /**
  30714. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30715. *
  30716. * @static
  30717. * @param {AnimationClip} sourceClip - The values to sort.
  30718. * @param {string} name - The name of the clip.
  30719. * @param {number} startFrame - The start frame.
  30720. * @param {number} endFrame - The end frame.
  30721. * @param {number} [fps=30] - The FPS.
  30722. * @return {AnimationClip} The new sub clip.
  30723. */
  30724. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30725. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30726. }
  30727. /**
  30728. * Converts the keyframes of the given animation clip to an additive format.
  30729. *
  30730. * @static
  30731. * @param {AnimationClip} targetClip - The clip to make additive.
  30732. * @param {number} [referenceFrame=0] - The reference frame.
  30733. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30734. * @param {number} [fps=30] - The FPS.
  30735. * @return {AnimationClip} The updated clip which is now additive.
  30736. */
  30737. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30738. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30739. }
  30740. }
  30741. /**
  30742. * Abstract base class of interpolants over parametric samples.
  30743. *
  30744. * The parameter domain is one dimensional, typically the time or a path
  30745. * along a curve defined by the data.
  30746. *
  30747. * The sample values can have any dimensionality and derived classes may
  30748. * apply special interpretations to the data.
  30749. *
  30750. * This class provides the interval seek in a Template Method, deferring
  30751. * the actual interpolation to derived classes.
  30752. *
  30753. * Time complexity is O(1) for linear access crossing at most two points
  30754. * and O(log N) for random access, where N is the number of positions.
  30755. *
  30756. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30757. *
  30758. * @abstract
  30759. */
  30760. class Interpolant {
  30761. /**
  30762. * Constructs a new 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. /**
  30771. * The parameter positions.
  30772. *
  30773. * @type {TypedArray}
  30774. */
  30775. this.parameterPositions = parameterPositions;
  30776. /**
  30777. * A cache index.
  30778. *
  30779. * @private
  30780. * @type {number}
  30781. * @default 0
  30782. */
  30783. this._cachedIndex = 0;
  30784. /**
  30785. * The result buffer.
  30786. *
  30787. * @type {TypedArray}
  30788. */
  30789. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30790. /**
  30791. * The sample values.
  30792. *
  30793. * @type {TypedArray}
  30794. */
  30795. this.sampleValues = sampleValues;
  30796. /**
  30797. * The value size.
  30798. *
  30799. * @type {TypedArray}
  30800. */
  30801. this.valueSize = sampleSize;
  30802. /**
  30803. * The interpolation settings.
  30804. *
  30805. * @type {?Object}
  30806. * @default null
  30807. */
  30808. this.settings = null;
  30809. /**
  30810. * The default settings object.
  30811. *
  30812. * @type {Object}
  30813. */
  30814. this.DefaultSettings_ = {};
  30815. }
  30816. /**
  30817. * Evaluate the interpolant at position `t`.
  30818. *
  30819. * @param {number} t - The interpolation factor.
  30820. * @return {TypedArray} The result buffer.
  30821. */
  30822. evaluate( t ) {
  30823. const pp = this.parameterPositions;
  30824. let i1 = this._cachedIndex,
  30825. t1 = pp[ i1 ],
  30826. t0 = pp[ i1 - 1 ];
  30827. validate_interval: {
  30828. seek: {
  30829. let right;
  30830. linear_scan: {
  30831. //- See http://jsperf.com/comparison-to-undefined/3
  30832. //- slower code:
  30833. //-
  30834. //- if ( t >= t1 || t1 === undefined ) {
  30835. forward_scan: if ( ! ( t < t1 ) ) {
  30836. for ( let giveUpAt = i1 + 2; ; ) {
  30837. if ( t1 === undefined ) {
  30838. if ( t < t0 ) break forward_scan;
  30839. // after end
  30840. i1 = pp.length;
  30841. this._cachedIndex = i1;
  30842. return this.copySampleValue_( i1 - 1 );
  30843. }
  30844. if ( i1 === giveUpAt ) break; // this loop
  30845. t0 = t1;
  30846. t1 = pp[ ++ i1 ];
  30847. if ( t < t1 ) {
  30848. // we have arrived at the sought interval
  30849. break seek;
  30850. }
  30851. }
  30852. // prepare binary search on the right side of the index
  30853. right = pp.length;
  30854. break linear_scan;
  30855. }
  30856. //- slower code:
  30857. //- if ( t < t0 || t0 === undefined ) {
  30858. if ( ! ( t >= t0 ) ) {
  30859. // looping?
  30860. const t1global = pp[ 1 ];
  30861. if ( t < t1global ) {
  30862. i1 = 2; // + 1, using the scan for the details
  30863. t0 = t1global;
  30864. }
  30865. // linear reverse scan
  30866. for ( let giveUpAt = i1 - 2; ; ) {
  30867. if ( t0 === undefined ) {
  30868. // before start
  30869. this._cachedIndex = 0;
  30870. return this.copySampleValue_( 0 );
  30871. }
  30872. if ( i1 === giveUpAt ) break; // this loop
  30873. t1 = t0;
  30874. t0 = pp[ -- i1 - 1 ];
  30875. if ( t >= t0 ) {
  30876. // we have arrived at the sought interval
  30877. break seek;
  30878. }
  30879. }
  30880. // prepare binary search on the left side of the index
  30881. right = i1;
  30882. i1 = 0;
  30883. break linear_scan;
  30884. }
  30885. // the interval is valid
  30886. break validate_interval;
  30887. } // linear scan
  30888. // binary search
  30889. while ( i1 < right ) {
  30890. const mid = ( i1 + right ) >>> 1;
  30891. if ( t < pp[ mid ] ) {
  30892. right = mid;
  30893. } else {
  30894. i1 = mid + 1;
  30895. }
  30896. }
  30897. t1 = pp[ i1 ];
  30898. t0 = pp[ i1 - 1 ];
  30899. // check boundary cases, again
  30900. if ( t0 === undefined ) {
  30901. this._cachedIndex = 0;
  30902. return this.copySampleValue_( 0 );
  30903. }
  30904. if ( t1 === undefined ) {
  30905. i1 = pp.length;
  30906. this._cachedIndex = i1;
  30907. return this.copySampleValue_( i1 - 1 );
  30908. }
  30909. } // seek
  30910. this._cachedIndex = i1;
  30911. this.intervalChanged_( i1, t0, t1 );
  30912. } // validate_interval
  30913. return this.interpolate_( i1, t0, t, t1 );
  30914. }
  30915. /**
  30916. * Returns the interpolation settings.
  30917. *
  30918. * @return {Object} The interpolation settings.
  30919. */
  30920. getSettings_() {
  30921. return this.settings || this.DefaultSettings_;
  30922. }
  30923. /**
  30924. * Copies a sample value to the result buffer.
  30925. *
  30926. * @param {number} index - An index into the sample value buffer.
  30927. * @return {TypedArray} The result buffer.
  30928. */
  30929. copySampleValue_( index ) {
  30930. // copies a sample value to the result buffer
  30931. const result = this.resultBuffer,
  30932. values = this.sampleValues,
  30933. stride = this.valueSize,
  30934. offset = index * stride;
  30935. for ( let i = 0; i !== stride; ++ i ) {
  30936. result[ i ] = values[ offset + i ];
  30937. }
  30938. return result;
  30939. }
  30940. /**
  30941. * Copies a sample value to the result buffer.
  30942. *
  30943. * @abstract
  30944. * @param {number} i1 - An index into the sample value buffer.
  30945. * @param {number} t0 - The previous interpolation factor.
  30946. * @param {number} t - The current interpolation factor.
  30947. * @param {number} t1 - The next interpolation factor.
  30948. * @return {TypedArray} The result buffer.
  30949. */
  30950. interpolate_( /* i1, t0, t, t1 */ ) {
  30951. throw new Error( 'call to abstract method' );
  30952. // implementations shall return this.resultBuffer
  30953. }
  30954. /**
  30955. * Optional method that is executed when the interval has changed.
  30956. *
  30957. * @param {number} i1 - An index into the sample value buffer.
  30958. * @param {number} t0 - The previous interpolation factor.
  30959. * @param {number} t - The current interpolation factor.
  30960. */
  30961. intervalChanged_( /* i1, t0, t1 */ ) {
  30962. // empty
  30963. }
  30964. }
  30965. /**
  30966. * Fast and simple cubic spline interpolant.
  30967. *
  30968. * It was derived from a Hermitian construction setting the first derivative
  30969. * at each sample position to the linear slope between neighboring positions
  30970. * over their parameter interval.
  30971. *
  30972. * @augments Interpolant
  30973. */
  30974. class CubicInterpolant extends Interpolant {
  30975. /**
  30976. * Constructs a new cubic interpolant.
  30977. *
  30978. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30979. * @param {TypedArray} sampleValues - The sample values.
  30980. * @param {number} sampleSize - The sample size
  30981. * @param {TypedArray} [resultBuffer] - The result buffer.
  30982. */
  30983. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30984. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30985. this._weightPrev = -0;
  30986. this._offsetPrev = -0;
  30987. this._weightNext = -0;
  30988. this._offsetNext = -0;
  30989. this.DefaultSettings_ = {
  30990. endingStart: ZeroCurvatureEnding,
  30991. endingEnd: ZeroCurvatureEnding
  30992. };
  30993. }
  30994. intervalChanged_( i1, t0, t1 ) {
  30995. const pp = this.parameterPositions;
  30996. let iPrev = i1 - 2,
  30997. iNext = i1 + 1,
  30998. tPrev = pp[ iPrev ],
  30999. tNext = pp[ iNext ];
  31000. if ( tPrev === undefined ) {
  31001. switch ( this.getSettings_().endingStart ) {
  31002. case ZeroSlopeEnding:
  31003. // f'(t0) = 0
  31004. iPrev = i1;
  31005. tPrev = 2 * t0 - t1;
  31006. break;
  31007. case WrapAroundEnding:
  31008. // use the other end of the curve
  31009. iPrev = pp.length - 2;
  31010. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  31011. break;
  31012. default: // ZeroCurvatureEnding
  31013. // f''(t0) = 0 a.k.a. Natural Spline
  31014. iPrev = i1;
  31015. tPrev = t1;
  31016. }
  31017. }
  31018. if ( tNext === undefined ) {
  31019. switch ( this.getSettings_().endingEnd ) {
  31020. case ZeroSlopeEnding:
  31021. // f'(tN) = 0
  31022. iNext = i1;
  31023. tNext = 2 * t1 - t0;
  31024. break;
  31025. case WrapAroundEnding:
  31026. // use the other end of the curve
  31027. iNext = 1;
  31028. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  31029. break;
  31030. default: // ZeroCurvatureEnding
  31031. // f''(tN) = 0, a.k.a. Natural Spline
  31032. iNext = i1 - 1;
  31033. tNext = t0;
  31034. }
  31035. }
  31036. const halfDt = ( t1 - t0 ) * 0.5,
  31037. stride = this.valueSize;
  31038. this._weightPrev = halfDt / ( t0 - tPrev );
  31039. this._weightNext = halfDt / ( tNext - t1 );
  31040. this._offsetPrev = iPrev * stride;
  31041. this._offsetNext = iNext * stride;
  31042. }
  31043. interpolate_( i1, t0, t, t1 ) {
  31044. const result = this.resultBuffer,
  31045. values = this.sampleValues,
  31046. stride = this.valueSize,
  31047. o1 = i1 * stride, o0 = o1 - stride,
  31048. oP = this._offsetPrev, oN = this._offsetNext,
  31049. wP = this._weightPrev, wN = this._weightNext,
  31050. p = ( t - t0 ) / ( t1 - t0 ),
  31051. pp = p * p,
  31052. ppp = pp * p;
  31053. // evaluate polynomials
  31054. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  31055. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  31056. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  31057. const sN = wN * ppp - wN * pp;
  31058. // combine data linearly
  31059. for ( let i = 0; i !== stride; ++ i ) {
  31060. result[ i ] =
  31061. sP * values[ oP + i ] +
  31062. s0 * values[ o0 + i ] +
  31063. s1 * values[ o1 + i ] +
  31064. sN * values[ oN + i ];
  31065. }
  31066. return result;
  31067. }
  31068. }
  31069. /**
  31070. * A basic linear interpolant.
  31071. *
  31072. * @augments Interpolant
  31073. */
  31074. class LinearInterpolant extends Interpolant {
  31075. /**
  31076. * Constructs a new linear interpolant.
  31077. *
  31078. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31079. * @param {TypedArray} sampleValues - The sample values.
  31080. * @param {number} sampleSize - The sample size
  31081. * @param {TypedArray} [resultBuffer] - The result buffer.
  31082. */
  31083. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31084. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31085. }
  31086. interpolate_( i1, t0, t, t1 ) {
  31087. const result = this.resultBuffer,
  31088. values = this.sampleValues,
  31089. stride = this.valueSize,
  31090. offset1 = i1 * stride,
  31091. offset0 = offset1 - stride,
  31092. weight1 = ( t - t0 ) / ( t1 - t0 ),
  31093. weight0 = 1 - weight1;
  31094. for ( let i = 0; i !== stride; ++ i ) {
  31095. result[ i ] =
  31096. values[ offset0 + i ] * weight0 +
  31097. values[ offset1 + i ] * weight1;
  31098. }
  31099. return result;
  31100. }
  31101. }
  31102. /**
  31103. * Interpolant that evaluates to the sample value at the position preceding
  31104. * the parameter.
  31105. *
  31106. * @augments Interpolant
  31107. */
  31108. class DiscreteInterpolant extends Interpolant {
  31109. /**
  31110. * Constructs a new discrete interpolant.
  31111. *
  31112. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31113. * @param {TypedArray} sampleValues - The sample values.
  31114. * @param {number} sampleSize - The sample size
  31115. * @param {TypedArray} [resultBuffer] - The result buffer.
  31116. */
  31117. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31118. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31119. }
  31120. interpolate_( i1 /*, t0, t, t1 */ ) {
  31121. return this.copySampleValue_( i1 - 1 );
  31122. }
  31123. }
  31124. /**
  31125. * Represents a timed sequence of keyframes, which are composed of lists of
  31126. * times and related values, and which are used to animate a specific property
  31127. * of an object.
  31128. */
  31129. class KeyframeTrack {
  31130. /**
  31131. * Constructs a new keyframe track.
  31132. *
  31133. * @param {string} name - The keyframe track's name.
  31134. * @param {Array<number>} times - A list of keyframe times.
  31135. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  31136. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31137. */
  31138. constructor( name, times, values, interpolation ) {
  31139. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  31140. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  31141. /**
  31142. * The track's name can refer to morph targets or bones or
  31143. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  31144. * for the forms of strings that can be parsed for property binding.
  31145. *
  31146. * @type {string}
  31147. */
  31148. this.name = name;
  31149. /**
  31150. * The keyframe times.
  31151. *
  31152. * @type {Float32Array}
  31153. */
  31154. this.times = convertArray( times, this.TimeBufferType );
  31155. /**
  31156. * The keyframe values.
  31157. *
  31158. * @type {Float32Array}
  31159. */
  31160. this.values = convertArray( values, this.ValueBufferType );
  31161. this.setInterpolation( interpolation || this.DefaultInterpolation );
  31162. }
  31163. /**
  31164. * Converts the keyframe track to JSON.
  31165. *
  31166. * @static
  31167. * @param {KeyframeTrack} track - The keyframe track to serialize.
  31168. * @return {Object} The serialized keyframe track as JSON.
  31169. */
  31170. static toJSON( track ) {
  31171. const trackType = track.constructor;
  31172. let json;
  31173. // derived classes can define a static toJSON method
  31174. if ( trackType.toJSON !== this.toJSON ) {
  31175. json = trackType.toJSON( track );
  31176. } else {
  31177. // by default, we assume the data can be serialized as-is
  31178. json = {
  31179. 'name': track.name,
  31180. 'times': convertArray( track.times, Array ),
  31181. 'values': convertArray( track.values, Array )
  31182. };
  31183. const interpolation = track.getInterpolation();
  31184. if ( interpolation !== track.DefaultInterpolation ) {
  31185. json.interpolation = interpolation;
  31186. }
  31187. }
  31188. json.type = track.ValueTypeName; // mandatory
  31189. return json;
  31190. }
  31191. /**
  31192. * Factory method for creating a new discrete interpolant.
  31193. *
  31194. * @static
  31195. * @param {TypedArray} [result] - The result buffer.
  31196. * @return {DiscreteInterpolant} The new interpolant.
  31197. */
  31198. InterpolantFactoryMethodDiscrete( result ) {
  31199. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  31200. }
  31201. /**
  31202. * Factory method for creating a new linear interpolant.
  31203. *
  31204. * @static
  31205. * @param {TypedArray} [result] - The result buffer.
  31206. * @return {LinearInterpolant} The new interpolant.
  31207. */
  31208. InterpolantFactoryMethodLinear( result ) {
  31209. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31210. }
  31211. /**
  31212. * Factory method for creating a new smooth interpolant.
  31213. *
  31214. * @static
  31215. * @param {TypedArray} [result] - The result buffer.
  31216. * @return {CubicInterpolant} The new interpolant.
  31217. */
  31218. InterpolantFactoryMethodSmooth( result ) {
  31219. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31220. }
  31221. /**
  31222. * Defines the interpolation factor method for this keyframe track.
  31223. *
  31224. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31225. * @return {KeyframeTrack} A reference to this keyframe track.
  31226. */
  31227. setInterpolation( interpolation ) {
  31228. let factoryMethod;
  31229. switch ( interpolation ) {
  31230. case InterpolateDiscrete:
  31231. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31232. break;
  31233. case InterpolateLinear:
  31234. factoryMethod = this.InterpolantFactoryMethodLinear;
  31235. break;
  31236. case InterpolateSmooth:
  31237. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31238. break;
  31239. }
  31240. if ( factoryMethod === undefined ) {
  31241. const message = 'unsupported interpolation for ' +
  31242. this.ValueTypeName + ' keyframe track named ' + this.name;
  31243. if ( this.createInterpolant === undefined ) {
  31244. // fall back to default, unless the default itself is messed up
  31245. if ( interpolation !== this.DefaultInterpolation ) {
  31246. this.setInterpolation( this.DefaultInterpolation );
  31247. } else {
  31248. throw new Error( message ); // fatal, in this case
  31249. }
  31250. }
  31251. warn( 'KeyframeTrack:', message );
  31252. return this;
  31253. }
  31254. this.createInterpolant = factoryMethod;
  31255. return this;
  31256. }
  31257. /**
  31258. * Returns the current interpolation type.
  31259. *
  31260. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31261. */
  31262. getInterpolation() {
  31263. switch ( this.createInterpolant ) {
  31264. case this.InterpolantFactoryMethodDiscrete:
  31265. return InterpolateDiscrete;
  31266. case this.InterpolantFactoryMethodLinear:
  31267. return InterpolateLinear;
  31268. case this.InterpolantFactoryMethodSmooth:
  31269. return InterpolateSmooth;
  31270. }
  31271. }
  31272. /**
  31273. * Returns the value size.
  31274. *
  31275. * @return {number} The value size.
  31276. */
  31277. getValueSize() {
  31278. return this.values.length / this.times.length;
  31279. }
  31280. /**
  31281. * Moves all keyframes either forward or backward in time.
  31282. *
  31283. * @param {number} timeOffset - The offset to move the time values.
  31284. * @return {KeyframeTrack} A reference to this keyframe track.
  31285. */
  31286. shift( timeOffset ) {
  31287. if ( timeOffset !== 0.0 ) {
  31288. const times = this.times;
  31289. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31290. times[ i ] += timeOffset;
  31291. }
  31292. }
  31293. return this;
  31294. }
  31295. /**
  31296. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31297. *
  31298. * @param {number} timeScale - The time scale.
  31299. * @return {KeyframeTrack} A reference to this keyframe track.
  31300. */
  31301. scale( timeScale ) {
  31302. if ( timeScale !== 1.0 ) {
  31303. const times = this.times;
  31304. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31305. times[ i ] *= timeScale;
  31306. }
  31307. }
  31308. return this;
  31309. }
  31310. /**
  31311. * Removes keyframes before and after animation without changing any values within the defined time range.
  31312. *
  31313. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31314. * keys this will change their values
  31315. *
  31316. * @param {number} startTime - The start time.
  31317. * @param {number} endTime - The end time.
  31318. * @return {KeyframeTrack} A reference to this keyframe track.
  31319. */
  31320. trim( startTime, endTime ) {
  31321. const times = this.times,
  31322. nKeys = times.length;
  31323. let from = 0,
  31324. to = nKeys - 1;
  31325. while ( from !== nKeys && times[ from ] < startTime ) {
  31326. ++ from;
  31327. }
  31328. while ( to !== -1 && times[ to ] > endTime ) {
  31329. -- to;
  31330. }
  31331. ++ to; // inclusive -> exclusive bound
  31332. if ( from !== 0 || to !== nKeys ) {
  31333. // empty tracks are forbidden, so keep at least one keyframe
  31334. if ( from >= to ) {
  31335. to = Math.max( to, 1 );
  31336. from = to - 1;
  31337. }
  31338. const stride = this.getValueSize();
  31339. this.times = times.slice( from, to );
  31340. this.values = this.values.slice( from * stride, to * stride );
  31341. }
  31342. return this;
  31343. }
  31344. /**
  31345. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31346. * are valid.
  31347. *
  31348. * @return {boolean} Whether the keyframes are valid or not.
  31349. */
  31350. validate() {
  31351. let valid = true;
  31352. const valueSize = this.getValueSize();
  31353. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31354. error( 'KeyframeTrack: Invalid value size in track.', this );
  31355. valid = false;
  31356. }
  31357. const times = this.times,
  31358. values = this.values,
  31359. nKeys = times.length;
  31360. if ( nKeys === 0 ) {
  31361. error( 'KeyframeTrack: Track is empty.', this );
  31362. valid = false;
  31363. }
  31364. let prevTime = null;
  31365. for ( let i = 0; i !== nKeys; i ++ ) {
  31366. const currTime = times[ i ];
  31367. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31368. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31369. valid = false;
  31370. break;
  31371. }
  31372. if ( prevTime !== null && prevTime > currTime ) {
  31373. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31374. valid = false;
  31375. break;
  31376. }
  31377. prevTime = currTime;
  31378. }
  31379. if ( values !== undefined ) {
  31380. if ( isTypedArray( values ) ) {
  31381. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31382. const value = values[ i ];
  31383. if ( isNaN( value ) ) {
  31384. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31385. valid = false;
  31386. break;
  31387. }
  31388. }
  31389. }
  31390. }
  31391. return valid;
  31392. }
  31393. /**
  31394. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31395. * common in morph target sequences).
  31396. *
  31397. * @return {KeyframeTrack} A reference to this keyframe track.
  31398. */
  31399. optimize() {
  31400. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31401. // times or values may be shared with other tracks, so overwriting is unsafe
  31402. const times = this.times.slice(),
  31403. values = this.values.slice(),
  31404. stride = this.getValueSize(),
  31405. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31406. lastIndex = times.length - 1;
  31407. let writeIndex = 1;
  31408. for ( let i = 1; i < lastIndex; ++ i ) {
  31409. let keep = false;
  31410. const time = times[ i ];
  31411. const timeNext = times[ i + 1 ];
  31412. // remove adjacent keyframes scheduled at the same time
  31413. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31414. if ( ! smoothInterpolation ) {
  31415. // remove unnecessary keyframes same as their neighbors
  31416. const offset = i * stride,
  31417. offsetP = offset - stride,
  31418. offsetN = offset + stride;
  31419. for ( let j = 0; j !== stride; ++ j ) {
  31420. const value = values[ offset + j ];
  31421. if ( value !== values[ offsetP + j ] ||
  31422. value !== values[ offsetN + j ] ) {
  31423. keep = true;
  31424. break;
  31425. }
  31426. }
  31427. } else {
  31428. keep = true;
  31429. }
  31430. }
  31431. // in-place compaction
  31432. if ( keep ) {
  31433. if ( i !== writeIndex ) {
  31434. times[ writeIndex ] = times[ i ];
  31435. const readOffset = i * stride,
  31436. writeOffset = writeIndex * stride;
  31437. for ( let j = 0; j !== stride; ++ j ) {
  31438. values[ writeOffset + j ] = values[ readOffset + j ];
  31439. }
  31440. }
  31441. ++ writeIndex;
  31442. }
  31443. }
  31444. // flush last keyframe (compaction looks ahead)
  31445. if ( lastIndex > 0 ) {
  31446. times[ writeIndex ] = times[ lastIndex ];
  31447. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31448. values[ writeOffset + j ] = values[ readOffset + j ];
  31449. }
  31450. ++ writeIndex;
  31451. }
  31452. if ( writeIndex !== times.length ) {
  31453. this.times = times.slice( 0, writeIndex );
  31454. this.values = values.slice( 0, writeIndex * stride );
  31455. } else {
  31456. this.times = times;
  31457. this.values = values;
  31458. }
  31459. return this;
  31460. }
  31461. /**
  31462. * Returns a new keyframe track with copied values from this instance.
  31463. *
  31464. * @return {KeyframeTrack} A clone of this instance.
  31465. */
  31466. clone() {
  31467. const times = this.times.slice();
  31468. const values = this.values.slice();
  31469. const TypedKeyframeTrack = this.constructor;
  31470. const track = new TypedKeyframeTrack( this.name, times, values );
  31471. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31472. track.createInterpolant = this.createInterpolant;
  31473. return track;
  31474. }
  31475. }
  31476. /**
  31477. * The value type name.
  31478. *
  31479. * @type {string}
  31480. * @default ''
  31481. */
  31482. KeyframeTrack.prototype.ValueTypeName = '';
  31483. /**
  31484. * The time buffer type of this keyframe track.
  31485. *
  31486. * @type {TypedArray|Array}
  31487. * @default Float32Array.constructor
  31488. */
  31489. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31490. /**
  31491. * The value buffer type of this keyframe track.
  31492. *
  31493. * @type {TypedArray|Array}
  31494. * @default Float32Array.constructor
  31495. */
  31496. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31497. /**
  31498. * The default interpolation type of this keyframe track.
  31499. *
  31500. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31501. * @default InterpolateLinear
  31502. */
  31503. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31504. /**
  31505. * A track for boolean keyframe values.
  31506. *
  31507. * @augments KeyframeTrack
  31508. */
  31509. class BooleanKeyframeTrack extends KeyframeTrack {
  31510. /**
  31511. * Constructs a new boolean keyframe track.
  31512. *
  31513. * This keyframe track type has no `interpolation` parameter because the
  31514. * interpolation is always discrete.
  31515. *
  31516. * @param {string} name - The keyframe track's name.
  31517. * @param {Array<number>} times - A list of keyframe times.
  31518. * @param {Array<boolean>} values - A list of keyframe values.
  31519. */
  31520. constructor( name, times, values ) {
  31521. super( name, times, values );
  31522. }
  31523. }
  31524. /**
  31525. * The value type name.
  31526. *
  31527. * @type {string}
  31528. * @default 'bool'
  31529. */
  31530. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31531. /**
  31532. * The value buffer type of this keyframe track.
  31533. *
  31534. * @type {TypedArray|Array}
  31535. * @default Array.constructor
  31536. */
  31537. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31538. /**
  31539. * The default interpolation type of this keyframe track.
  31540. *
  31541. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31542. * @default InterpolateDiscrete
  31543. */
  31544. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31545. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31546. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31547. /**
  31548. * A track for color keyframe values.
  31549. *
  31550. * @augments KeyframeTrack
  31551. */
  31552. class ColorKeyframeTrack extends KeyframeTrack {
  31553. /**
  31554. * Constructs a new color keyframe track.
  31555. *
  31556. * @param {string} name - The keyframe track's name.
  31557. * @param {Array<number>} times - A list of keyframe times.
  31558. * @param {Array<number>} values - A list of keyframe values.
  31559. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31560. */
  31561. constructor( name, times, values, interpolation ) {
  31562. super( name, times, values, interpolation );
  31563. }
  31564. }
  31565. /**
  31566. * The value type name.
  31567. *
  31568. * @type {string}
  31569. * @default 'color'
  31570. */
  31571. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31572. /**
  31573. * A track for numeric keyframe values.
  31574. *
  31575. * @augments KeyframeTrack
  31576. */
  31577. class NumberKeyframeTrack extends KeyframeTrack {
  31578. /**
  31579. * Constructs a new number keyframe track.
  31580. *
  31581. * @param {string} name - The keyframe track's name.
  31582. * @param {Array<number>} times - A list of keyframe times.
  31583. * @param {Array<number>} values - A list of keyframe values.
  31584. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31585. */
  31586. constructor( name, times, values, interpolation ) {
  31587. super( name, times, values, interpolation );
  31588. }
  31589. }
  31590. /**
  31591. * The value type name.
  31592. *
  31593. * @type {string}
  31594. * @default 'number'
  31595. */
  31596. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31597. /**
  31598. * Spherical linear unit quaternion interpolant.
  31599. *
  31600. * @augments Interpolant
  31601. */
  31602. class QuaternionLinearInterpolant extends Interpolant {
  31603. /**
  31604. * Constructs a new SLERP interpolant.
  31605. *
  31606. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31607. * @param {TypedArray} sampleValues - The sample values.
  31608. * @param {number} sampleSize - The sample size
  31609. * @param {TypedArray} [resultBuffer] - The result buffer.
  31610. */
  31611. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31612. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31613. }
  31614. interpolate_( i1, t0, t, t1 ) {
  31615. const result = this.resultBuffer,
  31616. values = this.sampleValues,
  31617. stride = this.valueSize,
  31618. alpha = ( t - t0 ) / ( t1 - t0 );
  31619. let offset = i1 * stride;
  31620. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31621. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31622. }
  31623. return result;
  31624. }
  31625. }
  31626. /**
  31627. * A track for Quaternion keyframe values.
  31628. *
  31629. * @augments KeyframeTrack
  31630. */
  31631. class QuaternionKeyframeTrack extends KeyframeTrack {
  31632. /**
  31633. * Constructs a new Quaternion keyframe track.
  31634. *
  31635. * @param {string} name - The keyframe track's name.
  31636. * @param {Array<number>} times - A list of keyframe times.
  31637. * @param {Array<number>} values - A list of keyframe values.
  31638. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31639. */
  31640. constructor( name, times, values, interpolation ) {
  31641. super( name, times, values, interpolation );
  31642. }
  31643. /**
  31644. * Overwritten so the method returns Quaternion based interpolant.
  31645. *
  31646. * @static
  31647. * @param {TypedArray} [result] - The result buffer.
  31648. * @return {QuaternionLinearInterpolant} The new interpolant.
  31649. */
  31650. InterpolantFactoryMethodLinear( result ) {
  31651. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31652. }
  31653. }
  31654. /**
  31655. * The value type name.
  31656. *
  31657. * @type {string}
  31658. * @default 'quaternion'
  31659. */
  31660. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31661. // ValueBufferType is inherited
  31662. // DefaultInterpolation is inherited;
  31663. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31664. /**
  31665. * A track for string keyframe values.
  31666. *
  31667. * @augments KeyframeTrack
  31668. */
  31669. class StringKeyframeTrack extends KeyframeTrack {
  31670. /**
  31671. * Constructs a new string keyframe track.
  31672. *
  31673. * This keyframe track type has no `interpolation` parameter because the
  31674. * interpolation is always discrete.
  31675. *
  31676. * @param {string} name - The keyframe track's name.
  31677. * @param {Array<number>} times - A list of keyframe times.
  31678. * @param {Array<string>} values - A list of keyframe values.
  31679. */
  31680. constructor( name, times, values ) {
  31681. super( name, times, values );
  31682. }
  31683. }
  31684. /**
  31685. * The value type name.
  31686. *
  31687. * @type {string}
  31688. * @default 'string'
  31689. */
  31690. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31691. /**
  31692. * The value buffer type of this keyframe track.
  31693. *
  31694. * @type {TypedArray|Array}
  31695. * @default Array.constructor
  31696. */
  31697. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31698. /**
  31699. * The default interpolation type of this keyframe track.
  31700. *
  31701. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31702. * @default InterpolateDiscrete
  31703. */
  31704. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31705. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31706. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31707. /**
  31708. * A track for vector keyframe values.
  31709. *
  31710. * @augments KeyframeTrack
  31711. */
  31712. class VectorKeyframeTrack extends KeyframeTrack {
  31713. /**
  31714. * Constructs a new vector keyframe track.
  31715. *
  31716. * @param {string} name - The keyframe track's name.
  31717. * @param {Array<number>} times - A list of keyframe times.
  31718. * @param {Array<number>} values - A list of keyframe values.
  31719. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31720. */
  31721. constructor( name, times, values, interpolation ) {
  31722. super( name, times, values, interpolation );
  31723. }
  31724. }
  31725. /**
  31726. * The value type name.
  31727. *
  31728. * @type {string}
  31729. * @default 'vector'
  31730. */
  31731. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31732. /**
  31733. * A reusable set of keyframe tracks which represent an animation.
  31734. */
  31735. class AnimationClip {
  31736. /**
  31737. * Constructs a new animation clip.
  31738. *
  31739. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31740. * use the static interface of this class for creating clips. In most cases though, animation clips
  31741. * will automatically be created by loaders when importing animated 3D assets.
  31742. *
  31743. * @param {string} [name=''] - The clip's name.
  31744. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31745. * the duration will be calculated from the passed keyframes.
  31746. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31747. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31748. * is blended/combined when two or more animations are simultaneously played.
  31749. */
  31750. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31751. /**
  31752. * The clip's name.
  31753. *
  31754. * @type {string}
  31755. */
  31756. this.name = name;
  31757. /**
  31758. * An array of keyframe tracks.
  31759. *
  31760. * @type {Array<KeyframeTrack>}
  31761. */
  31762. this.tracks = tracks;
  31763. /**
  31764. * The clip's duration in seconds.
  31765. *
  31766. * @type {number}
  31767. */
  31768. this.duration = duration;
  31769. /**
  31770. * Defines how the animation is blended/combined when two or more animations
  31771. * are simultaneously played.
  31772. *
  31773. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31774. */
  31775. this.blendMode = blendMode;
  31776. /**
  31777. * The UUID of the animation clip.
  31778. *
  31779. * @type {string}
  31780. * @readonly
  31781. */
  31782. this.uuid = generateUUID();
  31783. /**
  31784. * An object that can be used to store custom data about the animation clip.
  31785. * It should not hold references to functions as these will not be cloned.
  31786. *
  31787. * @type {Object}
  31788. */
  31789. this.userData = {};
  31790. // this means it should figure out its duration by scanning the tracks
  31791. if ( this.duration < 0 ) {
  31792. this.resetDuration();
  31793. }
  31794. }
  31795. /**
  31796. * Factory method for creating an animation clip from the given JSON.
  31797. *
  31798. * @static
  31799. * @param {Object} json - The serialized animation clip.
  31800. * @return {AnimationClip} The new animation clip.
  31801. */
  31802. static parse( json ) {
  31803. const tracks = [],
  31804. jsonTracks = json.tracks,
  31805. frameTime = 1.0 / ( json.fps || 1.0 );
  31806. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31807. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31808. }
  31809. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31810. clip.uuid = json.uuid;
  31811. clip.userData = JSON.parse( json.userData || '{}' );
  31812. return clip;
  31813. }
  31814. /**
  31815. * Serializes the given animation clip into JSON.
  31816. *
  31817. * @static
  31818. * @param {AnimationClip} clip - The animation clip to serialize.
  31819. * @return {Object} The JSON object.
  31820. */
  31821. static toJSON( clip ) {
  31822. const tracks = [],
  31823. clipTracks = clip.tracks;
  31824. const json = {
  31825. 'name': clip.name,
  31826. 'duration': clip.duration,
  31827. 'tracks': tracks,
  31828. 'uuid': clip.uuid,
  31829. 'blendMode': clip.blendMode,
  31830. 'userData': JSON.stringify( clip.userData ),
  31831. };
  31832. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31833. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31834. }
  31835. return json;
  31836. }
  31837. /**
  31838. * Returns a new animation clip from the passed morph targets array of a
  31839. * geometry, taking a name and the number of frames per second.
  31840. *
  31841. * Note: The fps parameter is required, but the animation speed can be
  31842. * overridden via {@link AnimationAction#setDuration}.
  31843. *
  31844. * @static
  31845. * @param {string} name - The name of the animation clip.
  31846. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31847. * @param {number} fps - The Frames-Per-Second value.
  31848. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31849. * @return {AnimationClip} The new animation clip.
  31850. */
  31851. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31852. const numMorphTargets = morphTargetSequence.length;
  31853. const tracks = [];
  31854. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31855. let times = [];
  31856. let values = [];
  31857. times.push(
  31858. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31859. i,
  31860. ( i + 1 ) % numMorphTargets );
  31861. values.push( 0, 1, 0 );
  31862. const order = getKeyframeOrder( times );
  31863. times = sortedArray( times, 1, order );
  31864. values = sortedArray( values, 1, order );
  31865. // if there is a key at the first frame, duplicate it as the
  31866. // last frame as well for perfect loop.
  31867. if ( ! noLoop && times[ 0 ] === 0 ) {
  31868. times.push( numMorphTargets );
  31869. values.push( values[ 0 ] );
  31870. }
  31871. tracks.push(
  31872. new NumberKeyframeTrack(
  31873. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31874. times, values
  31875. ).scale( 1.0 / fps ) );
  31876. }
  31877. return new this( name, -1, tracks );
  31878. }
  31879. /**
  31880. * Searches for an animation clip by name, taking as its first parameter
  31881. * either an array of clips, or a mesh or geometry that contains an
  31882. * array named "animations" property.
  31883. *
  31884. * @static
  31885. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31886. * @param {string} name - The name to search for.
  31887. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31888. */
  31889. static findByName( objectOrClipArray, name ) {
  31890. let clipArray = objectOrClipArray;
  31891. if ( ! Array.isArray( objectOrClipArray ) ) {
  31892. const o = objectOrClipArray;
  31893. clipArray = o.geometry && o.geometry.animations || o.animations;
  31894. }
  31895. for ( let i = 0; i < clipArray.length; i ++ ) {
  31896. if ( clipArray[ i ].name === name ) {
  31897. return clipArray[ i ];
  31898. }
  31899. }
  31900. return null;
  31901. }
  31902. /**
  31903. * Returns an array of new AnimationClips created from the morph target
  31904. * sequences of a geometry, trying to sort morph target names into
  31905. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31906. *
  31907. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31908. *
  31909. * @static
  31910. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31911. * @param {number} fps - The Frames-Per-Second value.
  31912. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31913. * @return {Array<AnimationClip>} An array of new animation clips.
  31914. */
  31915. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31916. const animationToMorphTargets = {};
  31917. // tested with https://regex101.com/ on trick sequences
  31918. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31919. const pattern = /^([\w-]*?)([\d]+)$/;
  31920. // sort morph target names into animation groups based
  31921. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31922. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31923. const morphTarget = morphTargets[ i ];
  31924. const parts = morphTarget.name.match( pattern );
  31925. if ( parts && parts.length > 1 ) {
  31926. const name = parts[ 1 ];
  31927. let animationMorphTargets = animationToMorphTargets[ name ];
  31928. if ( ! animationMorphTargets ) {
  31929. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31930. }
  31931. animationMorphTargets.push( morphTarget );
  31932. }
  31933. }
  31934. const clips = [];
  31935. for ( const name in animationToMorphTargets ) {
  31936. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31937. }
  31938. return clips;
  31939. }
  31940. /**
  31941. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31942. *
  31943. * @static
  31944. * @deprecated since r175.
  31945. * @param {Object} animation - A serialized animation clip as JSON.
  31946. * @param {Array<Bone>} bones - An array of bones.
  31947. * @return {?AnimationClip} The new animation clip.
  31948. */
  31949. static parseAnimation( animation, bones ) {
  31950. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31951. if ( ! animation ) {
  31952. error( 'AnimationClip: No animation in JSONLoader data.' );
  31953. return null;
  31954. }
  31955. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31956. // only return track if there are actually keys.
  31957. if ( animationKeys.length !== 0 ) {
  31958. const times = [];
  31959. const values = [];
  31960. flattenJSON( animationKeys, times, values, propertyName );
  31961. // empty keys are filtered out, so check again
  31962. if ( times.length !== 0 ) {
  31963. destTracks.push( new trackType( trackName, times, values ) );
  31964. }
  31965. }
  31966. };
  31967. const tracks = [];
  31968. const clipName = animation.name || 'default';
  31969. const fps = animation.fps || 30;
  31970. const blendMode = animation.blendMode;
  31971. // automatic length determination in AnimationClip.
  31972. let duration = animation.length || -1;
  31973. const hierarchyTracks = animation.hierarchy || [];
  31974. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31975. const animationKeys = hierarchyTracks[ h ].keys;
  31976. // skip empty tracks
  31977. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31978. // process morph targets
  31979. if ( animationKeys[ 0 ].morphTargets ) {
  31980. // figure out all morph targets used in this track
  31981. const morphTargetNames = {};
  31982. let k;
  31983. for ( k = 0; k < animationKeys.length; k ++ ) {
  31984. if ( animationKeys[ k ].morphTargets ) {
  31985. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31986. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31987. }
  31988. }
  31989. }
  31990. // create a track for each morph target with all zero
  31991. // morphTargetInfluences except for the keys in which
  31992. // the morphTarget is named.
  31993. for ( const morphTargetName in morphTargetNames ) {
  31994. const times = [];
  31995. const values = [];
  31996. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31997. const animationKey = animationKeys[ k ];
  31998. times.push( animationKey.time );
  31999. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  32000. }
  32001. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  32002. }
  32003. duration = morphTargetNames.length * fps;
  32004. } else {
  32005. // ...assume skeletal animation
  32006. const boneName = '.bones[' + bones[ h ].name + ']';
  32007. addNonemptyTrack(
  32008. VectorKeyframeTrack, boneName + '.position',
  32009. animationKeys, 'pos', tracks );
  32010. addNonemptyTrack(
  32011. QuaternionKeyframeTrack, boneName + '.quaternion',
  32012. animationKeys, 'rot', tracks );
  32013. addNonemptyTrack(
  32014. VectorKeyframeTrack, boneName + '.scale',
  32015. animationKeys, 'scl', tracks );
  32016. }
  32017. }
  32018. if ( tracks.length === 0 ) {
  32019. return null;
  32020. }
  32021. const clip = new this( clipName, duration, tracks, blendMode );
  32022. return clip;
  32023. }
  32024. /**
  32025. * Sets the duration of this clip to the duration of its longest keyframe track.
  32026. *
  32027. * @return {AnimationClip} A reference to this animation clip.
  32028. */
  32029. resetDuration() {
  32030. const tracks = this.tracks;
  32031. let duration = 0;
  32032. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  32033. const track = this.tracks[ i ];
  32034. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  32035. }
  32036. this.duration = duration;
  32037. return this;
  32038. }
  32039. /**
  32040. * Trims all tracks to the clip's duration.
  32041. *
  32042. * @return {AnimationClip} A reference to this animation clip.
  32043. */
  32044. trim() {
  32045. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32046. this.tracks[ i ].trim( 0, this.duration );
  32047. }
  32048. return this;
  32049. }
  32050. /**
  32051. * Performs minimal validation on each track in the clip. Returns `true` if all
  32052. * tracks are valid.
  32053. *
  32054. * @return {boolean} Whether the clip's keyframes are valid or not.
  32055. */
  32056. validate() {
  32057. let valid = true;
  32058. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32059. valid = valid && this.tracks[ i ].validate();
  32060. }
  32061. return valid;
  32062. }
  32063. /**
  32064. * Optimizes each track by removing equivalent sequential keys (which are
  32065. * common in morph target sequences).
  32066. *
  32067. * @return {AnimationClip} A reference to this animation clip.
  32068. */
  32069. optimize() {
  32070. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32071. this.tracks[ i ].optimize();
  32072. }
  32073. return this;
  32074. }
  32075. /**
  32076. * Returns a new animation clip with copied values from this instance.
  32077. *
  32078. * @return {AnimationClip} A clone of this instance.
  32079. */
  32080. clone() {
  32081. const tracks = [];
  32082. for ( let i = 0; i < this.tracks.length; i ++ ) {
  32083. tracks.push( this.tracks[ i ].clone() );
  32084. }
  32085. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  32086. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  32087. return clip;
  32088. }
  32089. /**
  32090. * Serializes this animation clip into JSON.
  32091. *
  32092. * @return {Object} The JSON object.
  32093. */
  32094. toJSON() {
  32095. return this.constructor.toJSON( this );
  32096. }
  32097. }
  32098. function getTrackTypeForValueTypeName( typeName ) {
  32099. switch ( typeName.toLowerCase() ) {
  32100. case 'scalar':
  32101. case 'double':
  32102. case 'float':
  32103. case 'number':
  32104. case 'integer':
  32105. return NumberKeyframeTrack;
  32106. case 'vector':
  32107. case 'vector2':
  32108. case 'vector3':
  32109. case 'vector4':
  32110. return VectorKeyframeTrack;
  32111. case 'color':
  32112. return ColorKeyframeTrack;
  32113. case 'quaternion':
  32114. return QuaternionKeyframeTrack;
  32115. case 'bool':
  32116. case 'boolean':
  32117. return BooleanKeyframeTrack;
  32118. case 'string':
  32119. return StringKeyframeTrack;
  32120. }
  32121. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  32122. }
  32123. function parseKeyframeTrack( json ) {
  32124. if ( json.type === undefined ) {
  32125. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  32126. }
  32127. const trackType = getTrackTypeForValueTypeName( json.type );
  32128. if ( json.times === undefined ) {
  32129. const times = [], values = [];
  32130. flattenJSON( json.keys, times, values, 'value' );
  32131. json.times = times;
  32132. json.values = values;
  32133. }
  32134. // derived classes can define a static parse method
  32135. if ( trackType.parse !== undefined ) {
  32136. return trackType.parse( json );
  32137. } else {
  32138. // by default, we assume a constructor compatible with the base
  32139. return new trackType( json.name, json.times, json.values, json.interpolation );
  32140. }
  32141. }
  32142. /**
  32143. * @class
  32144. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  32145. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  32146. * @hideconstructor
  32147. */
  32148. const Cache = {
  32149. /**
  32150. * Whether caching is enabled or not.
  32151. *
  32152. * @static
  32153. * @type {boolean}
  32154. * @default false
  32155. */
  32156. enabled: false,
  32157. /**
  32158. * A dictionary that holds cached files.
  32159. *
  32160. * @static
  32161. * @type {Object<string,Object>}
  32162. */
  32163. files: {},
  32164. /**
  32165. * Adds a cache entry with a key to reference the file. If this key already
  32166. * holds a file, it is overwritten.
  32167. *
  32168. * @static
  32169. * @param {string} key - The key to reference the cached file.
  32170. * @param {Object} file - The file to be cached.
  32171. */
  32172. add: function ( key, file ) {
  32173. if ( this.enabled === false ) return;
  32174. // log( 'Cache', 'Adding key:', key );
  32175. this.files[ key ] = file;
  32176. },
  32177. /**
  32178. * Gets the cached value for the given key.
  32179. *
  32180. * @static
  32181. * @param {string} key - The key to reference the cached file.
  32182. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  32183. */
  32184. get: function ( key ) {
  32185. if ( this.enabled === false ) return;
  32186. // log( 'Cache', 'Checking key:', key );
  32187. return this.files[ key ];
  32188. },
  32189. /**
  32190. * Removes the cached file associated with the given key.
  32191. *
  32192. * @static
  32193. * @param {string} key - The key to reference the cached file.
  32194. */
  32195. remove: function ( key ) {
  32196. delete this.files[ key ];
  32197. },
  32198. /**
  32199. * Remove all values from the cache.
  32200. *
  32201. * @static
  32202. */
  32203. clear: function () {
  32204. this.files = {};
  32205. }
  32206. };
  32207. /**
  32208. * Handles and keeps track of loaded and pending data. A default global
  32209. * instance of this class is created and used by loaders if not supplied
  32210. * manually.
  32211. *
  32212. * In general that should be sufficient, however there are times when it can
  32213. * be useful to have separate loaders - for example if you want to show
  32214. * separate loading bars for objects and textures.
  32215. *
  32216. * ```js
  32217. * const manager = new THREE.LoadingManager();
  32218. * manager.onLoad = () => console.log( 'Loading complete!' );
  32219. *
  32220. * const loader1 = new OBJLoader( manager );
  32221. * const loader2 = new ColladaLoader( manager );
  32222. * ```
  32223. */
  32224. class LoadingManager {
  32225. /**
  32226. * Constructs a new loading manager.
  32227. *
  32228. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32229. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32230. * @param {Function} [onError] - Executes when an error occurs.
  32231. */
  32232. constructor( onLoad, onProgress, onError ) {
  32233. const scope = this;
  32234. let isLoading = false;
  32235. let itemsLoaded = 0;
  32236. let itemsTotal = 0;
  32237. let urlModifier = undefined;
  32238. const handlers = [];
  32239. // Refer to #5689 for the reason why we don't set .onStart
  32240. // in the constructor
  32241. /**
  32242. * Executes when an item starts loading.
  32243. *
  32244. * @type {Function|undefined}
  32245. * @default undefined
  32246. */
  32247. this.onStart = undefined;
  32248. /**
  32249. * Executes when all items have been loaded.
  32250. *
  32251. * @type {Function|undefined}
  32252. * @default undefined
  32253. */
  32254. this.onLoad = onLoad;
  32255. /**
  32256. * Executes when single items have been loaded.
  32257. *
  32258. * @type {Function|undefined}
  32259. * @default undefined
  32260. */
  32261. this.onProgress = onProgress;
  32262. /**
  32263. * Executes when an error occurs.
  32264. *
  32265. * @type {Function|undefined}
  32266. * @default undefined
  32267. */
  32268. this.onError = onError;
  32269. /**
  32270. * Used for aborting ongoing requests in loaders using this manager.
  32271. *
  32272. * @private
  32273. * @type {AbortController | null}
  32274. */
  32275. this._abortController = null;
  32276. /**
  32277. * This should be called by any loader using the manager when the loader
  32278. * starts loading an item.
  32279. *
  32280. * @param {string} url - The URL to load.
  32281. */
  32282. this.itemStart = function ( url ) {
  32283. itemsTotal ++;
  32284. if ( isLoading === false ) {
  32285. if ( scope.onStart !== undefined ) {
  32286. scope.onStart( url, itemsLoaded, itemsTotal );
  32287. }
  32288. }
  32289. isLoading = true;
  32290. };
  32291. /**
  32292. * This should be called by any loader using the manager when the loader
  32293. * ended loading an item.
  32294. *
  32295. * @param {string} url - The URL of the loaded item.
  32296. */
  32297. this.itemEnd = function ( url ) {
  32298. itemsLoaded ++;
  32299. if ( scope.onProgress !== undefined ) {
  32300. scope.onProgress( url, itemsLoaded, itemsTotal );
  32301. }
  32302. if ( itemsLoaded === itemsTotal ) {
  32303. isLoading = false;
  32304. if ( scope.onLoad !== undefined ) {
  32305. scope.onLoad();
  32306. }
  32307. }
  32308. };
  32309. /**
  32310. * This should be called by any loader using the manager when the loader
  32311. * encounters an error when loading an item.
  32312. *
  32313. * @param {string} url - The URL of the item that produces an error.
  32314. */
  32315. this.itemError = function ( url ) {
  32316. if ( scope.onError !== undefined ) {
  32317. scope.onError( url );
  32318. }
  32319. };
  32320. /**
  32321. * Given a URL, uses the URL modifier callback (if any) and returns a
  32322. * resolved URL. If no URL modifier is set, returns the original URL.
  32323. *
  32324. * @param {string} url - The URL to load.
  32325. * @return {string} The resolved URL.
  32326. */
  32327. this.resolveURL = function ( url ) {
  32328. if ( urlModifier ) {
  32329. return urlModifier( url );
  32330. }
  32331. return url;
  32332. };
  32333. /**
  32334. * If provided, the callback will be passed each resource URL before a
  32335. * request is sent. The callback may return the original URL, or a new URL to
  32336. * override loading behavior. This behavior can be used to load assets from
  32337. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32338. *
  32339. * ```js
  32340. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32341. *
  32342. * const manager = new THREE.LoadingManager();
  32343. *
  32344. * // Initialize loading manager with URL callback.
  32345. * const objectURLs = [];
  32346. * manager.setURLModifier( ( url ) => {
  32347. *
  32348. * url = URL.createObjectURL( blobs[ url ] );
  32349. * objectURLs.push( url );
  32350. * return url;
  32351. *
  32352. * } );
  32353. *
  32354. * // Load as usual, then revoke the blob URLs.
  32355. * const loader = new GLTFLoader( manager );
  32356. * loader.load( 'fish.gltf', (gltf) => {
  32357. *
  32358. * scene.add( gltf.scene );
  32359. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32360. *
  32361. * } );
  32362. * ```
  32363. *
  32364. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32365. * @return {LoadingManager} A reference to this loading manager.
  32366. */
  32367. this.setURLModifier = function ( transform ) {
  32368. urlModifier = transform;
  32369. return this;
  32370. };
  32371. /**
  32372. * Registers a loader with the given regular expression. Can be used to
  32373. * define what loader should be used in order to load specific files. A
  32374. * typical use case is to overwrite the default loader for textures.
  32375. *
  32376. * ```js
  32377. * // add handler for TGA textures
  32378. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32379. * ```
  32380. *
  32381. * @param {string} regex - A regular expression.
  32382. * @param {Loader} loader - A loader that should handle matched cases.
  32383. * @return {LoadingManager} A reference to this loading manager.
  32384. */
  32385. this.addHandler = function ( regex, loader ) {
  32386. handlers.push( regex, loader );
  32387. return this;
  32388. };
  32389. /**
  32390. * Removes the loader for the given regular expression.
  32391. *
  32392. * @param {string} regex - A regular expression.
  32393. * @return {LoadingManager} A reference to this loading manager.
  32394. */
  32395. this.removeHandler = function ( regex ) {
  32396. const index = handlers.indexOf( regex );
  32397. if ( index !== -1 ) {
  32398. handlers.splice( index, 2 );
  32399. }
  32400. return this;
  32401. };
  32402. /**
  32403. * Can be used to retrieve the registered loader for the given file path.
  32404. *
  32405. * @param {string} file - The file path.
  32406. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32407. */
  32408. this.getHandler = function ( file ) {
  32409. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32410. const regex = handlers[ i ];
  32411. const loader = handlers[ i + 1 ];
  32412. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32413. if ( regex.test( file ) ) {
  32414. return loader;
  32415. }
  32416. }
  32417. return null;
  32418. };
  32419. /**
  32420. * Can be used to abort ongoing loading requests in loaders using this manager.
  32421. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32422. * is supported in the browser.
  32423. *
  32424. * @return {LoadingManager} A reference to this loading manager.
  32425. */
  32426. this.abort = function () {
  32427. this.abortController.abort();
  32428. this._abortController = null;
  32429. return this;
  32430. };
  32431. }
  32432. // TODO: Revert this back to a single member variable once this issue has been fixed
  32433. // https://github.com/cloudflare/workerd/issues/3657
  32434. /**
  32435. * Used for aborting ongoing requests in loaders using this manager.
  32436. *
  32437. * @type {AbortController}
  32438. */
  32439. get abortController() {
  32440. if ( ! this._abortController ) {
  32441. this._abortController = new AbortController();
  32442. }
  32443. return this._abortController;
  32444. }
  32445. }
  32446. /**
  32447. * The global default loading manager.
  32448. *
  32449. * @constant
  32450. * @type {LoadingManager}
  32451. */
  32452. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32453. /**
  32454. * Abstract base class for loaders.
  32455. *
  32456. * @abstract
  32457. */
  32458. class Loader {
  32459. /**
  32460. * Constructs a new loader.
  32461. *
  32462. * @param {LoadingManager} [manager] - The loading manager.
  32463. */
  32464. constructor( manager ) {
  32465. /**
  32466. * The loading manager.
  32467. *
  32468. * @type {LoadingManager}
  32469. * @default DefaultLoadingManager
  32470. */
  32471. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32472. /**
  32473. * The crossOrigin string to implement CORS for loading the url from a
  32474. * different domain that allows CORS.
  32475. *
  32476. * @type {string}
  32477. * @default 'anonymous'
  32478. */
  32479. this.crossOrigin = 'anonymous';
  32480. /**
  32481. * Whether the XMLHttpRequest uses credentials.
  32482. *
  32483. * @type {boolean}
  32484. * @default false
  32485. */
  32486. this.withCredentials = false;
  32487. /**
  32488. * The base path from which the asset will be loaded.
  32489. *
  32490. * @type {string}
  32491. */
  32492. this.path = '';
  32493. /**
  32494. * The base path from which additional resources like textures will be loaded.
  32495. *
  32496. * @type {string}
  32497. */
  32498. this.resourcePath = '';
  32499. /**
  32500. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32501. * used in HTTP request.
  32502. *
  32503. * @type {Object<string, any>}
  32504. */
  32505. this.requestHeader = {};
  32506. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  32507. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  32508. }
  32509. }
  32510. /**
  32511. * This method needs to be implemented by all concrete loaders. It holds the
  32512. * logic for loading assets from the backend.
  32513. *
  32514. * @abstract
  32515. * @param {string} url - The path/URL of the file to be loaded.
  32516. * @param {Function} onLoad - Executed when the loading process has been finished.
  32517. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32518. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32519. */
  32520. load( /* url, onLoad, onProgress, onError */ ) {}
  32521. /**
  32522. * A async version of {@link Loader#load}.
  32523. *
  32524. * @param {string} url - The path/URL of the file to be loaded.
  32525. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32526. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32527. */
  32528. loadAsync( url, onProgress ) {
  32529. const scope = this;
  32530. return new Promise( function ( resolve, reject ) {
  32531. scope.load( url, resolve, onProgress, reject );
  32532. } );
  32533. }
  32534. /**
  32535. * This method needs to be implemented by all concrete loaders. It holds the
  32536. * logic for parsing the asset into three.js entities.
  32537. *
  32538. * @abstract
  32539. * @param {any} data - The data to parse.
  32540. */
  32541. parse( /* data */ ) {}
  32542. /**
  32543. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32544. * from a different domain that allows CORS.
  32545. *
  32546. * @param {string} crossOrigin - The `crossOrigin` value.
  32547. * @return {Loader} A reference to this instance.
  32548. */
  32549. setCrossOrigin( crossOrigin ) {
  32550. this.crossOrigin = crossOrigin;
  32551. return this;
  32552. }
  32553. /**
  32554. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32555. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32556. *
  32557. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32558. *
  32559. * @param {boolean} value - The `withCredentials` value.
  32560. * @return {Loader} A reference to this instance.
  32561. */
  32562. setWithCredentials( value ) {
  32563. this.withCredentials = value;
  32564. return this;
  32565. }
  32566. /**
  32567. * Sets the base path for the asset.
  32568. *
  32569. * @param {string} path - The base path.
  32570. * @return {Loader} A reference to this instance.
  32571. */
  32572. setPath( path ) {
  32573. this.path = path;
  32574. return this;
  32575. }
  32576. /**
  32577. * Sets the base path for dependent resources like textures.
  32578. *
  32579. * @param {string} resourcePath - The resource path.
  32580. * @return {Loader} A reference to this instance.
  32581. */
  32582. setResourcePath( resourcePath ) {
  32583. this.resourcePath = resourcePath;
  32584. return this;
  32585. }
  32586. /**
  32587. * Sets the given request header.
  32588. *
  32589. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32590. * for configuring the HTTP request.
  32591. * @return {Loader} A reference to this instance.
  32592. */
  32593. setRequestHeader( requestHeader ) {
  32594. this.requestHeader = requestHeader;
  32595. return this;
  32596. }
  32597. /**
  32598. * This method can be implemented in loaders for aborting ongoing requests.
  32599. *
  32600. * @abstract
  32601. * @return {Loader} A reference to this instance.
  32602. */
  32603. abort() {
  32604. return this;
  32605. }
  32606. }
  32607. /**
  32608. * Callback for onProgress in loaders.
  32609. *
  32610. * @callback onProgressCallback
  32611. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32612. */
  32613. /**
  32614. * Callback for onError in loaders.
  32615. *
  32616. * @callback onErrorCallback
  32617. * @param {Error} error - The error which occurred during the loading process.
  32618. */
  32619. /**
  32620. * The default material name that is used by loaders
  32621. * when creating materials for loaded 3D objects.
  32622. *
  32623. * Note: Not all loaders might honor this setting.
  32624. *
  32625. * @static
  32626. * @type {string}
  32627. * @default '__DEFAULT'
  32628. */
  32629. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32630. const loading = {};
  32631. class HttpError extends Error {
  32632. constructor( message, response ) {
  32633. super( message );
  32634. this.response = response;
  32635. }
  32636. }
  32637. /**
  32638. * A low level class for loading resources with the Fetch API, used internally by
  32639. * most loaders. It can also be used directly to load any file type that does
  32640. * not have a loader.
  32641. *
  32642. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32643. * once to your application.
  32644. *
  32645. * ```js
  32646. * const loader = new THREE.FileLoader();
  32647. * const data = await loader.loadAsync( 'example.txt' );
  32648. * ```
  32649. *
  32650. * @augments Loader
  32651. */
  32652. class FileLoader extends Loader {
  32653. /**
  32654. * Constructs a new file loader.
  32655. *
  32656. * @param {LoadingManager} [manager] - The loading manager.
  32657. */
  32658. constructor( manager ) {
  32659. super( manager );
  32660. /**
  32661. * The expected mime type. Valid values can be found
  32662. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32663. *
  32664. * @type {string}
  32665. */
  32666. this.mimeType = '';
  32667. /**
  32668. * The expected response type.
  32669. *
  32670. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32671. * @default ''
  32672. */
  32673. this.responseType = '';
  32674. /**
  32675. * Used for aborting requests.
  32676. *
  32677. * @private
  32678. * @type {AbortController}
  32679. */
  32680. this._abortController = new AbortController();
  32681. }
  32682. /**
  32683. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32684. *
  32685. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32686. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32687. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32688. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32689. * @return {any|undefined} The cached resource if available.
  32690. */
  32691. load( url, onLoad, onProgress, onError ) {
  32692. if ( url === undefined ) url = '';
  32693. if ( this.path !== undefined ) url = this.path + url;
  32694. url = this.manager.resolveURL( url );
  32695. const cached = Cache.get( `file:${url}` );
  32696. if ( cached !== undefined ) {
  32697. this.manager.itemStart( url );
  32698. setTimeout( () => {
  32699. if ( onLoad ) onLoad( cached );
  32700. this.manager.itemEnd( url );
  32701. }, 0 );
  32702. return cached;
  32703. }
  32704. // Check if request is duplicate
  32705. if ( loading[ url ] !== undefined ) {
  32706. loading[ url ].push( {
  32707. onLoad: onLoad,
  32708. onProgress: onProgress,
  32709. onError: onError
  32710. } );
  32711. return;
  32712. }
  32713. // Initialise array for duplicate requests
  32714. loading[ url ] = [];
  32715. loading[ url ].push( {
  32716. onLoad: onLoad,
  32717. onProgress: onProgress,
  32718. onError: onError,
  32719. } );
  32720. // create request
  32721. const req = new Request( url, {
  32722. headers: new Headers( this.requestHeader ),
  32723. credentials: this.withCredentials ? 'include' : 'same-origin',
  32724. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32725. } );
  32726. // record states ( avoid data race )
  32727. const mimeType = this.mimeType;
  32728. const responseType = this.responseType;
  32729. // start the fetch
  32730. fetch( req )
  32731. .then( response => {
  32732. if ( response.status === 200 || response.status === 0 ) {
  32733. // Some browsers return HTTP Status 0 when using non-http protocol
  32734. // e.g. 'file://' or 'data://'. Handle as success.
  32735. if ( response.status === 0 ) {
  32736. warn( 'FileLoader: HTTP Status 0 received.' );
  32737. }
  32738. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32739. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32740. return response;
  32741. }
  32742. const callbacks = loading[ url ];
  32743. const reader = response.body.getReader();
  32744. // Nginx needs X-File-Size check
  32745. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32746. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32747. const total = contentLength ? parseInt( contentLength ) : 0;
  32748. const lengthComputable = total !== 0;
  32749. let loaded = 0;
  32750. // periodically read data into the new stream tracking while download progress
  32751. const stream = new ReadableStream( {
  32752. start( controller ) {
  32753. readData();
  32754. function readData() {
  32755. reader.read().then( ( { done, value } ) => {
  32756. if ( done ) {
  32757. controller.close();
  32758. } else {
  32759. loaded += value.byteLength;
  32760. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32761. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32762. const callback = callbacks[ i ];
  32763. if ( callback.onProgress ) callback.onProgress( event );
  32764. }
  32765. controller.enqueue( value );
  32766. readData();
  32767. }
  32768. }, ( e ) => {
  32769. controller.error( e );
  32770. } );
  32771. }
  32772. }
  32773. } );
  32774. return new Response( stream );
  32775. } else {
  32776. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32777. }
  32778. } )
  32779. .then( response => {
  32780. switch ( responseType ) {
  32781. case 'arraybuffer':
  32782. return response.arrayBuffer();
  32783. case 'blob':
  32784. return response.blob();
  32785. case 'document':
  32786. return response.text()
  32787. .then( text => {
  32788. const parser = new DOMParser();
  32789. return parser.parseFromString( text, mimeType );
  32790. } );
  32791. case 'json':
  32792. return response.json();
  32793. default:
  32794. if ( mimeType === '' ) {
  32795. return response.text();
  32796. } else {
  32797. // sniff encoding
  32798. const re = /charset="?([^;"\s]*)"?/i;
  32799. const exec = re.exec( mimeType );
  32800. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32801. const decoder = new TextDecoder( label );
  32802. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32803. }
  32804. }
  32805. } )
  32806. .then( data => {
  32807. // Add to cache only on HTTP success, so that we do not cache
  32808. // error response bodies as proper responses to requests.
  32809. Cache.add( `file:${url}`, data );
  32810. const callbacks = loading[ url ];
  32811. delete loading[ url ];
  32812. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32813. const callback = callbacks[ i ];
  32814. if ( callback.onLoad ) callback.onLoad( data );
  32815. }
  32816. } )
  32817. .catch( err => {
  32818. // Abort errors and other errors are handled the same
  32819. const callbacks = loading[ url ];
  32820. if ( callbacks === undefined ) {
  32821. // When onLoad was called and url was deleted in `loading`
  32822. this.manager.itemError( url );
  32823. throw err;
  32824. }
  32825. delete loading[ url ];
  32826. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32827. const callback = callbacks[ i ];
  32828. if ( callback.onError ) callback.onError( err );
  32829. }
  32830. this.manager.itemError( url );
  32831. } )
  32832. .finally( () => {
  32833. this.manager.itemEnd( url );
  32834. } );
  32835. this.manager.itemStart( url );
  32836. }
  32837. /**
  32838. * Sets the expected response type.
  32839. *
  32840. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32841. * @return {FileLoader} A reference to this file loader.
  32842. */
  32843. setResponseType( value ) {
  32844. this.responseType = value;
  32845. return this;
  32846. }
  32847. /**
  32848. * Sets the expected mime type of the loaded file.
  32849. *
  32850. * @param {string} value - The mime type.
  32851. * @return {FileLoader} A reference to this file loader.
  32852. */
  32853. setMimeType( value ) {
  32854. this.mimeType = value;
  32855. return this;
  32856. }
  32857. /**
  32858. * Aborts ongoing fetch requests.
  32859. *
  32860. * @return {FileLoader} A reference to this instance.
  32861. */
  32862. abort() {
  32863. this._abortController.abort();
  32864. this._abortController = new AbortController();
  32865. return this;
  32866. }
  32867. }
  32868. /**
  32869. * Class for loading animation clips in the JSON format. The files are internally
  32870. * loaded via {@link FileLoader}.
  32871. *
  32872. * ```js
  32873. * const loader = new THREE.AnimationLoader();
  32874. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32875. * ```
  32876. *
  32877. * @augments Loader
  32878. */
  32879. class AnimationLoader extends Loader {
  32880. /**
  32881. * Constructs a new animation loader.
  32882. *
  32883. * @param {LoadingManager} [manager] - The loading manager.
  32884. */
  32885. constructor( manager ) {
  32886. super( manager );
  32887. }
  32888. /**
  32889. * Starts loading from the given URL and pass the loaded animations as an array
  32890. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32891. *
  32892. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32893. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32894. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32895. * @param {onErrorCallback} onError - Executed when errors occur.
  32896. */
  32897. load( url, onLoad, onProgress, onError ) {
  32898. const scope = this;
  32899. const loader = new FileLoader( this.manager );
  32900. loader.setPath( this.path );
  32901. loader.setRequestHeader( this.requestHeader );
  32902. loader.setWithCredentials( this.withCredentials );
  32903. loader.load( url, function ( text ) {
  32904. try {
  32905. onLoad( scope.parse( JSON.parse( text ) ) );
  32906. } catch ( e ) {
  32907. if ( onError ) {
  32908. onError( e );
  32909. } else {
  32910. error( e );
  32911. }
  32912. scope.manager.itemError( url );
  32913. }
  32914. }, onProgress, onError );
  32915. }
  32916. /**
  32917. * Parses the given JSON object and returns an array of animation clips.
  32918. *
  32919. * @param {Object} json - The serialized animation clips.
  32920. * @return {Array<AnimationClip>} The parsed animation clips.
  32921. */
  32922. parse( json ) {
  32923. const animations = [];
  32924. for ( let i = 0; i < json.length; i ++ ) {
  32925. const clip = AnimationClip.parse( json[ i ] );
  32926. animations.push( clip );
  32927. }
  32928. return animations;
  32929. }
  32930. }
  32931. /**
  32932. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32933. * Textures are internally loaded via {@link FileLoader}.
  32934. *
  32935. * Derived classes have to implement the `parse()` method which holds the parsing
  32936. * for the respective format.
  32937. *
  32938. * @abstract
  32939. * @augments Loader
  32940. */
  32941. class CompressedTextureLoader extends Loader {
  32942. /**
  32943. * Constructs a new compressed texture loader.
  32944. *
  32945. * @param {LoadingManager} [manager] - The loading manager.
  32946. */
  32947. constructor( manager ) {
  32948. super( manager );
  32949. }
  32950. /**
  32951. * Starts loading from the given URL and passes the loaded compressed texture
  32952. * to the `onLoad()` callback. The method also returns a new texture object which can
  32953. * directly be used for material creation. If you do it this way, the texture
  32954. * may pop up in your scene once the respective loading process is finished.
  32955. *
  32956. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32957. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32958. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32959. * @param {onErrorCallback} onError - Executed when errors occur.
  32960. * @return {CompressedTexture} The compressed texture.
  32961. */
  32962. load( url, onLoad, onProgress, onError ) {
  32963. const scope = this;
  32964. const images = [];
  32965. const texture = new CompressedTexture();
  32966. const loader = new FileLoader( this.manager );
  32967. loader.setPath( this.path );
  32968. loader.setResponseType( 'arraybuffer' );
  32969. loader.setRequestHeader( this.requestHeader );
  32970. loader.setWithCredentials( scope.withCredentials );
  32971. let loaded = 0;
  32972. function loadTexture( i ) {
  32973. loader.load( url[ i ], function ( buffer ) {
  32974. const texDatas = scope.parse( buffer, true );
  32975. images[ i ] = {
  32976. width: texDatas.width,
  32977. height: texDatas.height,
  32978. format: texDatas.format,
  32979. mipmaps: texDatas.mipmaps
  32980. };
  32981. loaded += 1;
  32982. if ( loaded === 6 ) {
  32983. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32984. texture.image = images;
  32985. texture.format = texDatas.format;
  32986. texture.needsUpdate = true;
  32987. if ( onLoad ) onLoad( texture );
  32988. }
  32989. }, onProgress, onError );
  32990. }
  32991. if ( Array.isArray( url ) ) {
  32992. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32993. loadTexture( i );
  32994. }
  32995. } else {
  32996. // compressed cubemap texture stored in a single DDS file
  32997. loader.load( url, function ( buffer ) {
  32998. const texDatas = scope.parse( buffer, true );
  32999. if ( texDatas.isCubemap ) {
  33000. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  33001. for ( let f = 0; f < faces; f ++ ) {
  33002. images[ f ] = { mipmaps: [] };
  33003. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  33004. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  33005. images[ f ].format = texDatas.format;
  33006. images[ f ].width = texDatas.width;
  33007. images[ f ].height = texDatas.height;
  33008. }
  33009. }
  33010. texture.image = images;
  33011. } else {
  33012. texture.image.width = texDatas.width;
  33013. texture.image.height = texDatas.height;
  33014. texture.mipmaps = texDatas.mipmaps;
  33015. }
  33016. if ( texDatas.mipmapCount === 1 ) {
  33017. texture.minFilter = LinearFilter;
  33018. }
  33019. texture.format = texDatas.format;
  33020. texture.needsUpdate = true;
  33021. if ( onLoad ) onLoad( texture );
  33022. }, onProgress, onError );
  33023. }
  33024. return texture;
  33025. }
  33026. }
  33027. const _loading = new WeakMap();
  33028. /**
  33029. * A loader for loading images. The class loads images with the HTML `Image` API.
  33030. *
  33031. * ```js
  33032. * const loader = new THREE.ImageLoader();
  33033. * const image = await loader.loadAsync( 'image.png' );
  33034. * ```
  33035. * Please note that `ImageLoader` has dropped support for progress
  33036. * events in `r84`. For an `ImageLoader` that supports progress events, see
  33037. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  33038. *
  33039. * @augments Loader
  33040. */
  33041. class ImageLoader extends Loader {
  33042. /**
  33043. * Constructs a new image loader.
  33044. *
  33045. * @param {LoadingManager} [manager] - The loading manager.
  33046. */
  33047. constructor( manager ) {
  33048. super( manager );
  33049. }
  33050. /**
  33051. * Starts loading from the given URL and passes the loaded image
  33052. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  33053. * directly be used for texture creation. If you do it this way, the texture
  33054. * may pop up in your scene once the respective loading process is finished.
  33055. *
  33056. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33057. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  33058. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33059. * @param {onErrorCallback} onError - Executed when errors occur.
  33060. * @return {Image} The image.
  33061. */
  33062. load( url, onLoad, onProgress, onError ) {
  33063. if ( this.path !== undefined ) url = this.path + url;
  33064. url = this.manager.resolveURL( url );
  33065. const scope = this;
  33066. const cached = Cache.get( `image:${url}` );
  33067. if ( cached !== undefined ) {
  33068. if ( cached.complete === true ) {
  33069. scope.manager.itemStart( url );
  33070. setTimeout( function () {
  33071. if ( onLoad ) onLoad( cached );
  33072. scope.manager.itemEnd( url );
  33073. }, 0 );
  33074. } else {
  33075. let arr = _loading.get( cached );
  33076. if ( arr === undefined ) {
  33077. arr = [];
  33078. _loading.set( cached, arr );
  33079. }
  33080. arr.push( { onLoad, onError } );
  33081. }
  33082. return cached;
  33083. }
  33084. const image = createElementNS( 'img' );
  33085. function onImageLoad() {
  33086. removeEventListeners();
  33087. if ( onLoad ) onLoad( this );
  33088. //
  33089. const callbacks = _loading.get( this ) || [];
  33090. for ( let i = 0; i < callbacks.length; i ++ ) {
  33091. const callback = callbacks[ i ];
  33092. if ( callback.onLoad ) callback.onLoad( this );
  33093. }
  33094. _loading.delete( this );
  33095. scope.manager.itemEnd( url );
  33096. }
  33097. function onImageError( event ) {
  33098. removeEventListeners();
  33099. if ( onError ) onError( event );
  33100. Cache.remove( `image:${url}` );
  33101. //
  33102. const callbacks = _loading.get( this ) || [];
  33103. for ( let i = 0; i < callbacks.length; i ++ ) {
  33104. const callback = callbacks[ i ];
  33105. if ( callback.onError ) callback.onError( event );
  33106. }
  33107. _loading.delete( this );
  33108. scope.manager.itemError( url );
  33109. scope.manager.itemEnd( url );
  33110. }
  33111. function removeEventListeners() {
  33112. image.removeEventListener( 'load', onImageLoad, false );
  33113. image.removeEventListener( 'error', onImageError, false );
  33114. }
  33115. image.addEventListener( 'load', onImageLoad, false );
  33116. image.addEventListener( 'error', onImageError, false );
  33117. if ( url.slice( 0, 5 ) !== 'data:' ) {
  33118. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  33119. }
  33120. Cache.add( `image:${url}`, image );
  33121. scope.manager.itemStart( url );
  33122. image.src = url;
  33123. return image;
  33124. }
  33125. }
  33126. /**
  33127. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  33128. *
  33129. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  33130. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  33131. * like vertical and horizontal cross, column and row layouts are not supported.
  33132. *
  33133. * Note that, by convention, cube maps are specified in a coordinate system
  33134. * in which positive-x is to the right when looking up the positive-z axis --
  33135. * in other words, using a left-handed coordinate system. Since three.js uses
  33136. * a right-handed coordinate system, environment maps used in three.js will
  33137. * have pos-x and neg-x swapped.
  33138. *
  33139. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  33140. * is set to `SRGBColorSpace` by default.
  33141. *
  33142. * ```js
  33143. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  33144. * const cubeTexture = await loader.loadAsync( [
  33145. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  33146. * ] );
  33147. * scene.background = cubeTexture;
  33148. * ```
  33149. *
  33150. * @augments Loader
  33151. */
  33152. class CubeTextureLoader extends Loader {
  33153. /**
  33154. * Constructs a new cube texture loader.
  33155. *
  33156. * @param {LoadingManager} [manager] - The loading manager.
  33157. */
  33158. constructor( manager ) {
  33159. super( manager );
  33160. }
  33161. /**
  33162. * Starts loading from the given URL and pass the fully loaded cube texture
  33163. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  33164. * directly be used for material creation. If you do it this way, the cube texture
  33165. * may pop up in your scene once the respective loading process is finished.
  33166. *
  33167. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  33168. * cube texture. The urls should be specified in the following order: pos-x,
  33169. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  33170. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  33171. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33172. * @param {onErrorCallback} onError - Executed when errors occur.
  33173. * @return {CubeTexture} The cube texture.
  33174. */
  33175. load( urls, onLoad, onProgress, onError ) {
  33176. const texture = new CubeTexture();
  33177. texture.colorSpace = SRGBColorSpace;
  33178. const loader = new ImageLoader( this.manager );
  33179. loader.setCrossOrigin( this.crossOrigin );
  33180. loader.setPath( this.path );
  33181. let loaded = 0;
  33182. function loadTexture( i ) {
  33183. loader.load( urls[ i ], function ( image ) {
  33184. texture.images[ i ] = image;
  33185. loaded ++;
  33186. if ( loaded === 6 ) {
  33187. texture.needsUpdate = true;
  33188. if ( onLoad ) onLoad( texture );
  33189. }
  33190. }, undefined, onError );
  33191. }
  33192. for ( let i = 0; i < urls.length; ++ i ) {
  33193. loadTexture( i );
  33194. }
  33195. return texture;
  33196. }
  33197. }
  33198. /**
  33199. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  33200. * Textures are internally loaded via {@link FileLoader}.
  33201. *
  33202. * Derived classes have to implement the `parse()` method which holds the parsing
  33203. * for the respective format.
  33204. *
  33205. * @abstract
  33206. * @augments Loader
  33207. */
  33208. class DataTextureLoader extends Loader {
  33209. /**
  33210. * Constructs a new data texture loader.
  33211. *
  33212. * @param {LoadingManager} [manager] - The loading manager.
  33213. */
  33214. constructor( manager ) {
  33215. super( manager );
  33216. }
  33217. /**
  33218. * Starts loading from the given URL and passes the loaded data texture
  33219. * to the `onLoad()` callback. The method also returns a new texture object which can
  33220. * directly be used for material creation. If you do it this way, the texture
  33221. * may pop up in your scene once the respective loading process is finished.
  33222. *
  33223. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33224. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33225. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33226. * @param {onErrorCallback} onError - Executed when errors occur.
  33227. * @return {DataTexture} The data texture.
  33228. */
  33229. load( url, onLoad, onProgress, onError ) {
  33230. const scope = this;
  33231. const texture = new DataTexture();
  33232. const loader = new FileLoader( this.manager );
  33233. loader.setResponseType( 'arraybuffer' );
  33234. loader.setRequestHeader( this.requestHeader );
  33235. loader.setPath( this.path );
  33236. loader.setWithCredentials( scope.withCredentials );
  33237. loader.load( url, function ( buffer ) {
  33238. let texData;
  33239. try {
  33240. texData = scope.parse( buffer );
  33241. } catch ( error ) {
  33242. if ( onError !== undefined ) {
  33243. onError( error );
  33244. } else {
  33245. error( error );
  33246. return;
  33247. }
  33248. }
  33249. if ( texData.image !== undefined ) {
  33250. texture.image = texData.image;
  33251. } else if ( texData.data !== undefined ) {
  33252. texture.image.width = texData.width;
  33253. texture.image.height = texData.height;
  33254. texture.image.data = texData.data;
  33255. }
  33256. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33257. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33258. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33259. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33260. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33261. if ( texData.colorSpace !== undefined ) {
  33262. texture.colorSpace = texData.colorSpace;
  33263. }
  33264. if ( texData.flipY !== undefined ) {
  33265. texture.flipY = texData.flipY;
  33266. }
  33267. if ( texData.format !== undefined ) {
  33268. texture.format = texData.format;
  33269. }
  33270. if ( texData.type !== undefined ) {
  33271. texture.type = texData.type;
  33272. }
  33273. if ( texData.mipmaps !== undefined ) {
  33274. texture.mipmaps = texData.mipmaps;
  33275. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33276. }
  33277. if ( texData.mipmapCount === 1 ) {
  33278. texture.minFilter = LinearFilter;
  33279. }
  33280. if ( texData.generateMipmaps !== undefined ) {
  33281. texture.generateMipmaps = texData.generateMipmaps;
  33282. }
  33283. texture.needsUpdate = true;
  33284. if ( onLoad ) onLoad( texture, texData );
  33285. }, onProgress, onError );
  33286. return texture;
  33287. }
  33288. }
  33289. /**
  33290. * Class for loading textures. Images are internally
  33291. * loaded via {@link ImageLoader}.
  33292. *
  33293. * ```js
  33294. * const loader = new THREE.TextureLoader();
  33295. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33296. *
  33297. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33298. * ```
  33299. * Please note that `TextureLoader` has dropped support for progress
  33300. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33301. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33302. *
  33303. * @augments Loader
  33304. */
  33305. class TextureLoader extends Loader {
  33306. /**
  33307. * Constructs a new texture loader.
  33308. *
  33309. * @param {LoadingManager} [manager] - The loading manager.
  33310. */
  33311. constructor( manager ) {
  33312. super( manager );
  33313. }
  33314. /**
  33315. * Starts loading from the given URL and pass the fully loaded texture
  33316. * to the `onLoad()` callback. The method also returns a new texture object which can
  33317. * directly be used for material creation. If you do it this way, the texture
  33318. * may pop up in your scene once the respective loading process is finished.
  33319. *
  33320. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33321. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33322. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33323. * @param {onErrorCallback} onError - Executed when errors occur.
  33324. * @return {Texture} The texture.
  33325. */
  33326. load( url, onLoad, onProgress, onError ) {
  33327. const texture = new Texture();
  33328. const loader = new ImageLoader( this.manager );
  33329. loader.setCrossOrigin( this.crossOrigin );
  33330. loader.setPath( this.path );
  33331. loader.load( url, function ( image ) {
  33332. texture.image = image;
  33333. texture.needsUpdate = true;
  33334. if ( onLoad !== undefined ) {
  33335. onLoad( texture );
  33336. }
  33337. }, onProgress, onError );
  33338. return texture;
  33339. }
  33340. }
  33341. /**
  33342. * Abstract base class for lights - all other light types inherit the
  33343. * properties and methods described here.
  33344. *
  33345. * @abstract
  33346. * @augments Object3D
  33347. */
  33348. class Light extends Object3D {
  33349. /**
  33350. * Constructs a new light.
  33351. *
  33352. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33353. * @param {number} [intensity=1] - The light's strength/intensity.
  33354. */
  33355. constructor( color, intensity = 1 ) {
  33356. super();
  33357. /**
  33358. * This flag can be used for type testing.
  33359. *
  33360. * @type {boolean}
  33361. * @readonly
  33362. * @default true
  33363. */
  33364. this.isLight = true;
  33365. this.type = 'Light';
  33366. /**
  33367. * The light's color.
  33368. *
  33369. * @type {Color}
  33370. */
  33371. this.color = new Color( color );
  33372. /**
  33373. * The light's intensity.
  33374. *
  33375. * @type {number}
  33376. * @default 1
  33377. */
  33378. this.intensity = intensity;
  33379. }
  33380. /**
  33381. * Frees the GPU-related resources allocated by this instance. Call this
  33382. * method whenever this instance is no longer used in your app.
  33383. */
  33384. dispose() {
  33385. this.dispatchEvent( { type: 'dispose' } );
  33386. }
  33387. copy( source, recursive ) {
  33388. super.copy( source, recursive );
  33389. this.color.copy( source.color );
  33390. this.intensity = source.intensity;
  33391. return this;
  33392. }
  33393. toJSON( meta ) {
  33394. const data = super.toJSON( meta );
  33395. data.object.color = this.color.getHex();
  33396. data.object.intensity = this.intensity;
  33397. return data;
  33398. }
  33399. }
  33400. /**
  33401. * A light source positioned directly above the scene, with color fading from
  33402. * the sky color to the ground color.
  33403. *
  33404. * This light cannot be used to cast shadows.
  33405. *
  33406. * ```js
  33407. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33408. * scene.add( light );
  33409. * ```
  33410. *
  33411. * @augments Light
  33412. */
  33413. class HemisphereLight extends Light {
  33414. /**
  33415. * Constructs a new hemisphere light.
  33416. *
  33417. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33418. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33419. * @param {number} [intensity=1] - The light's strength/intensity.
  33420. */
  33421. constructor( skyColor, groundColor, intensity ) {
  33422. super( skyColor, intensity );
  33423. /**
  33424. * This flag can be used for type testing.
  33425. *
  33426. * @type {boolean}
  33427. * @readonly
  33428. * @default true
  33429. */
  33430. this.isHemisphereLight = true;
  33431. this.type = 'HemisphereLight';
  33432. this.position.copy( Object3D.DEFAULT_UP );
  33433. this.updateMatrix();
  33434. /**
  33435. * The light's ground color.
  33436. *
  33437. * @type {Color}
  33438. */
  33439. this.groundColor = new Color( groundColor );
  33440. }
  33441. copy( source, recursive ) {
  33442. super.copy( source, recursive );
  33443. this.groundColor.copy( source.groundColor );
  33444. return this;
  33445. }
  33446. toJSON( meta ) {
  33447. const data = super.toJSON( meta );
  33448. data.object.groundColor = this.groundColor.getHex();
  33449. return data;
  33450. }
  33451. }
  33452. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33453. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33454. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33455. /**
  33456. * Abstract base class for light shadow classes. These classes
  33457. * represent the shadow configuration for different light types.
  33458. *
  33459. * @abstract
  33460. */
  33461. class LightShadow {
  33462. /**
  33463. * Constructs a new light shadow.
  33464. *
  33465. * @param {Camera} camera - The light's view of the world.
  33466. */
  33467. constructor( camera ) {
  33468. /**
  33469. * The light's view of the world.
  33470. *
  33471. * @type {Camera}
  33472. */
  33473. this.camera = camera;
  33474. /**
  33475. * The intensity of the shadow. The default is `1`.
  33476. * Valid values are in the range `[0, 1]`.
  33477. *
  33478. * @type {number}
  33479. * @default 1
  33480. */
  33481. this.intensity = 1;
  33482. /**
  33483. * Shadow map bias, how much to add or subtract from the normalized depth
  33484. * when deciding whether a surface is in shadow.
  33485. *
  33486. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33487. * may help reduce artifacts in shadows.
  33488. *
  33489. * @type {number}
  33490. * @default 0
  33491. */
  33492. this.bias = 0;
  33493. /**
  33494. * Defines how much the position used to query the shadow map is offset along
  33495. * the object normal. The default is `0`. Increasing this value can be used to
  33496. * reduce shadow acne especially in large scenes where light shines onto
  33497. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33498. *
  33499. * @type {number}
  33500. * @default 0
  33501. */
  33502. this.normalBias = 0;
  33503. /**
  33504. * Setting this to values greater than 1 will blur the edges of the shadow.
  33505. * High values will cause unwanted banding effects in the shadows - a greater
  33506. * map size will allow for a higher value to be used here before these effects
  33507. * become visible.
  33508. *
  33509. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33510. *
  33511. * @type {number}
  33512. * @default 1
  33513. */
  33514. this.radius = 1;
  33515. /**
  33516. * The amount of samples to use when blurring a VSM shadow map.
  33517. *
  33518. * @type {number}
  33519. * @default 8
  33520. */
  33521. this.blurSamples = 8;
  33522. /**
  33523. * Defines the width and height of the shadow map. Higher values give better quality
  33524. * shadows at the cost of computation time. Values must be powers of two.
  33525. *
  33526. * @type {Vector2}
  33527. * @default (512,512)
  33528. */
  33529. this.mapSize = new Vector2( 512, 512 );
  33530. /**
  33531. * The type of shadow texture. The default is `UnsignedByteType`.
  33532. *
  33533. * @type {number}
  33534. * @default UnsignedByteType
  33535. */
  33536. this.mapType = UnsignedByteType;
  33537. /**
  33538. * The depth map generated using the internal camera; a location beyond a
  33539. * pixel's depth is in shadow. Computed internally during rendering.
  33540. *
  33541. * @type {?RenderTarget}
  33542. * @default null
  33543. */
  33544. this.map = null;
  33545. /**
  33546. * The distribution map generated using the internal camera; an occlusion is
  33547. * calculated based on the distribution of depths. Computed internally during
  33548. * rendering.
  33549. *
  33550. * @type {?RenderTarget}
  33551. * @default null
  33552. */
  33553. this.mapPass = null;
  33554. /**
  33555. * Model to shadow camera space, to compute location and depth in shadow map.
  33556. * This is computed internally during rendering.
  33557. *
  33558. * @type {Matrix4}
  33559. */
  33560. this.matrix = new Matrix4();
  33561. /**
  33562. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33563. * lighting / shadows, you may set this to `false`.
  33564. *
  33565. * @type {boolean}
  33566. * @default true
  33567. */
  33568. this.autoUpdate = true;
  33569. /**
  33570. * When set to `true`, shadow maps will be updated in the next `render` call.
  33571. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33572. * set this property to `true` and then make a render call to update the light's shadow.
  33573. *
  33574. * @type {boolean}
  33575. * @default false
  33576. */
  33577. this.needsUpdate = false;
  33578. this._frustum = new Frustum();
  33579. this._frameExtents = new Vector2( 1, 1 );
  33580. this._viewportCount = 1;
  33581. this._viewports = [
  33582. new Vector4( 0, 0, 1, 1 )
  33583. ];
  33584. }
  33585. /**
  33586. * Used internally by the renderer to get the number of viewports that need
  33587. * to be rendered for this shadow.
  33588. *
  33589. * @return {number} The viewport count.
  33590. */
  33591. getViewportCount() {
  33592. return this._viewportCount;
  33593. }
  33594. /**
  33595. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33596. *
  33597. * @return {Frustum} The shadow camera frustum.
  33598. */
  33599. getFrustum() {
  33600. return this._frustum;
  33601. }
  33602. /**
  33603. * Update the matrices for the camera and shadow, used internally by the renderer.
  33604. *
  33605. * @param {Light} light - The light for which the shadow is being rendered.
  33606. */
  33607. updateMatrices( light ) {
  33608. const shadowCamera = this.camera;
  33609. const shadowMatrix = this.matrix;
  33610. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33611. shadowCamera.position.copy( _lightPositionWorld$1 );
  33612. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33613. shadowCamera.lookAt( _lookTarget$1 );
  33614. shadowCamera.updateMatrixWorld();
  33615. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33616. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33617. if ( shadowCamera.reversedDepth ) {
  33618. shadowMatrix.set(
  33619. 0.5, 0.0, 0.0, 0.5,
  33620. 0.0, 0.5, 0.0, 0.5,
  33621. 0.0, 0.0, 1.0, 0.0,
  33622. 0.0, 0.0, 0.0, 1.0
  33623. );
  33624. } else {
  33625. shadowMatrix.set(
  33626. 0.5, 0.0, 0.0, 0.5,
  33627. 0.0, 0.5, 0.0, 0.5,
  33628. 0.0, 0.0, 0.5, 0.5,
  33629. 0.0, 0.0, 0.0, 1.0
  33630. );
  33631. }
  33632. shadowMatrix.multiply( _projScreenMatrix$1 );
  33633. }
  33634. /**
  33635. * Returns a viewport definition for the given viewport index.
  33636. *
  33637. * @param {number} viewportIndex - The viewport index.
  33638. * @return {Vector4} The viewport.
  33639. */
  33640. getViewport( viewportIndex ) {
  33641. return this._viewports[ viewportIndex ];
  33642. }
  33643. /**
  33644. * Returns the frame extends.
  33645. *
  33646. * @return {Vector2} The frame extends.
  33647. */
  33648. getFrameExtents() {
  33649. return this._frameExtents;
  33650. }
  33651. /**
  33652. * Frees the GPU-related resources allocated by this instance. Call this
  33653. * method whenever this instance is no longer used in your app.
  33654. */
  33655. dispose() {
  33656. if ( this.map ) {
  33657. this.map.dispose();
  33658. }
  33659. if ( this.mapPass ) {
  33660. this.mapPass.dispose();
  33661. }
  33662. }
  33663. /**
  33664. * Copies the values of the given light shadow instance to this instance.
  33665. *
  33666. * @param {LightShadow} source - The light shadow to copy.
  33667. * @return {LightShadow} A reference to this light shadow instance.
  33668. */
  33669. copy( source ) {
  33670. this.camera = source.camera.clone();
  33671. this.intensity = source.intensity;
  33672. this.bias = source.bias;
  33673. this.radius = source.radius;
  33674. this.autoUpdate = source.autoUpdate;
  33675. this.needsUpdate = source.needsUpdate;
  33676. this.normalBias = source.normalBias;
  33677. this.blurSamples = source.blurSamples;
  33678. this.mapSize.copy( source.mapSize );
  33679. return this;
  33680. }
  33681. /**
  33682. * Returns a new light shadow instance with copied values from this instance.
  33683. *
  33684. * @return {LightShadow} A clone of this instance.
  33685. */
  33686. clone() {
  33687. return new this.constructor().copy( this );
  33688. }
  33689. /**
  33690. * Serializes the light shadow into JSON.
  33691. *
  33692. * @return {Object} A JSON object representing the serialized light shadow.
  33693. * @see {@link ObjectLoader#parse}
  33694. */
  33695. toJSON() {
  33696. const object = {};
  33697. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33698. if ( this.bias !== 0 ) object.bias = this.bias;
  33699. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33700. if ( this.radius !== 1 ) object.radius = this.radius;
  33701. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33702. object.camera = this.camera.toJSON( false ).object;
  33703. delete object.camera.matrix;
  33704. return object;
  33705. }
  33706. }
  33707. /**
  33708. * Represents the shadow configuration of directional lights.
  33709. *
  33710. * @augments LightShadow
  33711. */
  33712. class SpotLightShadow extends LightShadow {
  33713. /**
  33714. * Constructs a new spot light shadow.
  33715. */
  33716. constructor() {
  33717. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33718. /**
  33719. * This flag can be used for type testing.
  33720. *
  33721. * @type {boolean}
  33722. * @readonly
  33723. * @default true
  33724. */
  33725. this.isSpotLightShadow = true;
  33726. /**
  33727. * Used to focus the shadow camera. The camera's field of view is set as a
  33728. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33729. *
  33730. * @type {number}
  33731. * @default 1
  33732. */
  33733. this.focus = 1;
  33734. /**
  33735. * Texture aspect ratio.
  33736. *
  33737. * @type {number}
  33738. * @default 1
  33739. */
  33740. this.aspect = 1;
  33741. }
  33742. updateMatrices( light ) {
  33743. const camera = this.camera;
  33744. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33745. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33746. const far = light.distance || camera.far;
  33747. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33748. camera.fov = fov;
  33749. camera.aspect = aspect;
  33750. camera.far = far;
  33751. camera.updateProjectionMatrix();
  33752. }
  33753. super.updateMatrices( light );
  33754. }
  33755. copy( source ) {
  33756. super.copy( source );
  33757. this.focus = source.focus;
  33758. return this;
  33759. }
  33760. }
  33761. /**
  33762. * This light gets emitted from a single point in one direction, along a cone
  33763. * that increases in size the further from the light it gets.
  33764. *
  33765. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33766. *
  33767. * ```js
  33768. * // white spotlight shining from the side, modulated by a texture
  33769. * const spotLight = new THREE.SpotLight( 0xffffff );
  33770. * spotLight.position.set( 100, 1000, 100 );
  33771. * spotLight.map = new THREE.TextureLoader().load( url );
  33772. *
  33773. * spotLight.castShadow = true;
  33774. * spotLight.shadow.mapSize.width = 1024;
  33775. * spotLight.shadow.mapSize.height = 1024;
  33776. * spotLight.shadow.camera.near = 500;
  33777. * spotLight.shadow.camera.far = 4000;
  33778. * spotLight.shadow.camera.fov = 30;s
  33779. * ```
  33780. *
  33781. * @augments Light
  33782. */
  33783. class SpotLight extends Light {
  33784. /**
  33785. * Constructs a new spot light.
  33786. *
  33787. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33788. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33789. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33790. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33791. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33792. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33793. */
  33794. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33795. super( color, intensity );
  33796. /**
  33797. * This flag can be used for type testing.
  33798. *
  33799. * @type {boolean}
  33800. * @readonly
  33801. * @default true
  33802. */
  33803. this.isSpotLight = true;
  33804. this.type = 'SpotLight';
  33805. this.position.copy( Object3D.DEFAULT_UP );
  33806. this.updateMatrix();
  33807. /**
  33808. * The spot light points from its position to the
  33809. * target's position.
  33810. *
  33811. * For the target's position to be changed to anything other
  33812. * than the default, it must be added to the scene.
  33813. *
  33814. * It is also possible to set the target to be another 3D object
  33815. * in the scene. The light will now track the target object.
  33816. *
  33817. * @type {Object3D}
  33818. */
  33819. this.target = new Object3D();
  33820. /**
  33821. * Maximum range of the light. `0` means no limit.
  33822. *
  33823. * @type {number}
  33824. * @default 0
  33825. */
  33826. this.distance = distance;
  33827. /**
  33828. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33829. *
  33830. * @type {number}
  33831. * @default Math.PI/3
  33832. */
  33833. this.angle = angle;
  33834. /**
  33835. * Percent of the spotlight cone that is attenuated due to penumbra.
  33836. * Value range is `[0,1]`.
  33837. *
  33838. * @type {number}
  33839. * @default 0
  33840. */
  33841. this.penumbra = penumbra;
  33842. /**
  33843. * The amount the light dims along the distance of the light. In context of
  33844. * physically-correct rendering the default value should not be changed.
  33845. *
  33846. * @type {number}
  33847. * @default 2
  33848. */
  33849. this.decay = decay;
  33850. /**
  33851. * A texture used to modulate the color of the light. The spot light
  33852. * color is mixed with the RGB value of this texture, with a ratio
  33853. * corresponding to its alpha value. The cookie-like masking effect is
  33854. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33855. *
  33856. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33857. *
  33858. * @type {?Texture}
  33859. * @default null
  33860. */
  33861. this.map = null;
  33862. /**
  33863. * This property holds the light's shadow configuration.
  33864. *
  33865. * @type {SpotLightShadow}
  33866. */
  33867. this.shadow = new SpotLightShadow();
  33868. }
  33869. /**
  33870. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33871. * Changing the power will also change the light's intensity.
  33872. *
  33873. * @type {number}
  33874. */
  33875. get power() {
  33876. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33877. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33878. return this.intensity * Math.PI;
  33879. }
  33880. set power( power ) {
  33881. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33882. this.intensity = power / Math.PI;
  33883. }
  33884. dispose() {
  33885. super.dispose();
  33886. this.shadow.dispose();
  33887. }
  33888. copy( source, recursive ) {
  33889. super.copy( source, recursive );
  33890. this.distance = source.distance;
  33891. this.angle = source.angle;
  33892. this.penumbra = source.penumbra;
  33893. this.decay = source.decay;
  33894. this.target = source.target.clone();
  33895. this.map = source.map;
  33896. this.shadow = source.shadow.clone();
  33897. return this;
  33898. }
  33899. toJSON( meta ) {
  33900. const data = super.toJSON( meta );
  33901. data.object.distance = this.distance;
  33902. data.object.angle = this.angle;
  33903. data.object.decay = this.decay;
  33904. data.object.penumbra = this.penumbra;
  33905. data.object.target = this.target.uuid;
  33906. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33907. data.object.shadow = this.shadow.toJSON();
  33908. return data;
  33909. }
  33910. }
  33911. /**
  33912. * Represents the shadow configuration of point lights.
  33913. *
  33914. * @augments LightShadow
  33915. */
  33916. class PointLightShadow extends LightShadow {
  33917. /**
  33918. * Constructs a new point light shadow.
  33919. */
  33920. constructor() {
  33921. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33922. /**
  33923. * This flag can be used for type testing.
  33924. *
  33925. * @type {boolean}
  33926. * @readonly
  33927. * @default true
  33928. */
  33929. this.isPointLightShadow = true;
  33930. }
  33931. }
  33932. /**
  33933. * A light that gets emitted from a single point in all directions. A common
  33934. * use case for this is to replicate the light emitted from a bare
  33935. * lightbulb.
  33936. *
  33937. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33938. *
  33939. * ```js
  33940. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33941. * light.position.set( 50, 50, 50 );
  33942. * scene.add( light );
  33943. * ```
  33944. *
  33945. * @augments Light
  33946. */
  33947. class PointLight extends Light {
  33948. /**
  33949. * Constructs a new point light.
  33950. *
  33951. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33952. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33953. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33954. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33955. */
  33956. constructor( color, intensity, distance = 0, decay = 2 ) {
  33957. super( color, intensity );
  33958. /**
  33959. * This flag can be used for type testing.
  33960. *
  33961. * @type {boolean}
  33962. * @readonly
  33963. * @default true
  33964. */
  33965. this.isPointLight = true;
  33966. this.type = 'PointLight';
  33967. /**
  33968. * When distance is zero, light will attenuate according to inverse-square
  33969. * law to infinite distance. When distance is non-zero, light will attenuate
  33970. * according to inverse-square law until near the distance cutoff, where it
  33971. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33972. * physically correct.
  33973. *
  33974. * @type {number}
  33975. * @default 0
  33976. */
  33977. this.distance = distance;
  33978. /**
  33979. * The amount the light dims along the distance of the light. In context of
  33980. * physically-correct rendering the default value should not be changed.
  33981. *
  33982. * @type {number}
  33983. * @default 2
  33984. */
  33985. this.decay = decay;
  33986. /**
  33987. * This property holds the light's shadow configuration.
  33988. *
  33989. * @type {PointLightShadow}
  33990. */
  33991. this.shadow = new PointLightShadow();
  33992. }
  33993. /**
  33994. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33995. * Changing the power will also change the light's intensity.
  33996. *
  33997. * @type {number}
  33998. */
  33999. get power() {
  34000. // compute the light's luminous power (in lumens) from its intensity (in candela)
  34001. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  34002. return this.intensity * 4 * Math.PI;
  34003. }
  34004. set power( power ) {
  34005. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  34006. this.intensity = power / ( 4 * Math.PI );
  34007. }
  34008. dispose() {
  34009. super.dispose();
  34010. this.shadow.dispose();
  34011. }
  34012. copy( source, recursive ) {
  34013. super.copy( source, recursive );
  34014. this.distance = source.distance;
  34015. this.decay = source.decay;
  34016. this.shadow = source.shadow.clone();
  34017. return this;
  34018. }
  34019. toJSON( meta ) {
  34020. const data = super.toJSON( meta );
  34021. data.object.distance = this.distance;
  34022. data.object.decay = this.decay;
  34023. data.object.shadow = this.shadow.toJSON();
  34024. return data;
  34025. }
  34026. }
  34027. /**
  34028. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  34029. *
  34030. * In this projection mode, an object's size in the rendered image stays
  34031. * constant regardless of its distance from the camera. This can be useful
  34032. * for rendering 2D scenes and UI elements, amongst other things.
  34033. *
  34034. * ```js
  34035. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  34036. * scene.add( camera );
  34037. * ```
  34038. *
  34039. * @augments Camera
  34040. */
  34041. class OrthographicCamera extends Camera {
  34042. /**
  34043. * Constructs a new orthographic camera.
  34044. *
  34045. * @param {number} [left=-1] - The left plane of the camera's frustum.
  34046. * @param {number} [right=1] - The right plane of the camera's frustum.
  34047. * @param {number} [top=1] - The top plane of the camera's frustum.
  34048. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  34049. * @param {number} [near=0.1] - The camera's near plane.
  34050. * @param {number} [far=2000] - The camera's far plane.
  34051. */
  34052. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  34053. super();
  34054. /**
  34055. * This flag can be used for type testing.
  34056. *
  34057. * @type {boolean}
  34058. * @readonly
  34059. * @default true
  34060. */
  34061. this.isOrthographicCamera = true;
  34062. this.type = 'OrthographicCamera';
  34063. /**
  34064. * The zoom factor of the camera.
  34065. *
  34066. * @type {number}
  34067. * @default 1
  34068. */
  34069. this.zoom = 1;
  34070. /**
  34071. * Represents the frustum window specification. This property should not be edited
  34072. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  34073. *
  34074. * @type {?Object}
  34075. * @default null
  34076. */
  34077. this.view = null;
  34078. /**
  34079. * The left plane of the camera's frustum.
  34080. *
  34081. * @type {number}
  34082. * @default -1
  34083. */
  34084. this.left = left;
  34085. /**
  34086. * The right plane of the camera's frustum.
  34087. *
  34088. * @type {number}
  34089. * @default 1
  34090. */
  34091. this.right = right;
  34092. /**
  34093. * The top plane of the camera's frustum.
  34094. *
  34095. * @type {number}
  34096. * @default 1
  34097. */
  34098. this.top = top;
  34099. /**
  34100. * The bottom plane of the camera's frustum.
  34101. *
  34102. * @type {number}
  34103. * @default -1
  34104. */
  34105. this.bottom = bottom;
  34106. /**
  34107. * The camera's near plane. The valid range is greater than `0`
  34108. * and less than the current value of {@link OrthographicCamera#far}.
  34109. *
  34110. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  34111. * valid value for an orthographic camera's near plane.
  34112. *
  34113. * @type {number}
  34114. * @default 0.1
  34115. */
  34116. this.near = near;
  34117. /**
  34118. * The camera's far plane. Must be greater than the
  34119. * current value of {@link OrthographicCamera#near}.
  34120. *
  34121. * @type {number}
  34122. * @default 2000
  34123. */
  34124. this.far = far;
  34125. this.updateProjectionMatrix();
  34126. }
  34127. copy( source, recursive ) {
  34128. super.copy( source, recursive );
  34129. this.left = source.left;
  34130. this.right = source.right;
  34131. this.top = source.top;
  34132. this.bottom = source.bottom;
  34133. this.near = source.near;
  34134. this.far = source.far;
  34135. this.zoom = source.zoom;
  34136. this.view = source.view === null ? null : Object.assign( {}, source.view );
  34137. return this;
  34138. }
  34139. /**
  34140. * Sets an offset in a larger frustum. This is useful for multi-window or
  34141. * multi-monitor/multi-machine setups.
  34142. *
  34143. * @param {number} fullWidth - The full width of multiview setup.
  34144. * @param {number} fullHeight - The full height of multiview setup.
  34145. * @param {number} x - The horizontal offset of the subcamera.
  34146. * @param {number} y - The vertical offset of the subcamera.
  34147. * @param {number} width - The width of subcamera.
  34148. * @param {number} height - The height of subcamera.
  34149. * @see {@link PerspectiveCamera#setViewOffset}
  34150. */
  34151. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  34152. if ( this.view === null ) {
  34153. this.view = {
  34154. enabled: true,
  34155. fullWidth: 1,
  34156. fullHeight: 1,
  34157. offsetX: 0,
  34158. offsetY: 0,
  34159. width: 1,
  34160. height: 1
  34161. };
  34162. }
  34163. this.view.enabled = true;
  34164. this.view.fullWidth = fullWidth;
  34165. this.view.fullHeight = fullHeight;
  34166. this.view.offsetX = x;
  34167. this.view.offsetY = y;
  34168. this.view.width = width;
  34169. this.view.height = height;
  34170. this.updateProjectionMatrix();
  34171. }
  34172. /**
  34173. * Removes the view offset from the projection matrix.
  34174. */
  34175. clearViewOffset() {
  34176. if ( this.view !== null ) {
  34177. this.view.enabled = false;
  34178. }
  34179. this.updateProjectionMatrix();
  34180. }
  34181. /**
  34182. * Updates the camera's projection matrix. Must be called after any change of
  34183. * camera properties.
  34184. */
  34185. updateProjectionMatrix() {
  34186. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  34187. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  34188. const cx = ( this.right + this.left ) / 2;
  34189. const cy = ( this.top + this.bottom ) / 2;
  34190. let left = cx - dx;
  34191. let right = cx + dx;
  34192. let top = cy + dy;
  34193. let bottom = cy - dy;
  34194. if ( this.view !== null && this.view.enabled ) {
  34195. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  34196. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  34197. left += scaleW * this.view.offsetX;
  34198. right = left + scaleW * this.view.width;
  34199. top -= scaleH * this.view.offsetY;
  34200. bottom = top - scaleH * this.view.height;
  34201. }
  34202. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34203. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34204. }
  34205. toJSON( meta ) {
  34206. const data = super.toJSON( meta );
  34207. data.object.zoom = this.zoom;
  34208. data.object.left = this.left;
  34209. data.object.right = this.right;
  34210. data.object.top = this.top;
  34211. data.object.bottom = this.bottom;
  34212. data.object.near = this.near;
  34213. data.object.far = this.far;
  34214. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34215. return data;
  34216. }
  34217. }
  34218. /**
  34219. * Represents the shadow configuration of directional lights.
  34220. *
  34221. * @augments LightShadow
  34222. */
  34223. class DirectionalLightShadow extends LightShadow {
  34224. /**
  34225. * Constructs a new directional light shadow.
  34226. */
  34227. constructor() {
  34228. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34229. /**
  34230. * This flag can be used for type testing.
  34231. *
  34232. * @type {boolean}
  34233. * @readonly
  34234. * @default true
  34235. */
  34236. this.isDirectionalLightShadow = true;
  34237. }
  34238. }
  34239. /**
  34240. * A light that gets emitted in a specific direction. This light will behave
  34241. * as though it is infinitely far away and the rays produced from it are all
  34242. * parallel. The common use case for this is to simulate daylight; the sun is
  34243. * far enough away that its position can be considered to be infinite, and
  34244. * all light rays coming from it are parallel.
  34245. *
  34246. * A common point of confusion for directional lights is that setting the
  34247. * rotation has no effect. This is because three.js's DirectionalLight is the
  34248. * equivalent to what is often called a 'Target Direct Light' in other
  34249. * applications.
  34250. *
  34251. * This means that its direction is calculated as pointing from the light's
  34252. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34253. * (as opposed to a 'Free Direct Light' that just has a rotation
  34254. * component).
  34255. *
  34256. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34257. *
  34258. * ```js
  34259. * // White directional light at half intensity shining from the top.
  34260. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34261. * scene.add( directionalLight );
  34262. * ```
  34263. *
  34264. * @augments Light
  34265. */
  34266. class DirectionalLight extends Light {
  34267. /**
  34268. * Constructs a new directional light.
  34269. *
  34270. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34271. * @param {number} [intensity=1] - The light's strength/intensity.
  34272. */
  34273. constructor( color, intensity ) {
  34274. super( color, intensity );
  34275. /**
  34276. * This flag can be used for type testing.
  34277. *
  34278. * @type {boolean}
  34279. * @readonly
  34280. * @default true
  34281. */
  34282. this.isDirectionalLight = true;
  34283. this.type = 'DirectionalLight';
  34284. this.position.copy( Object3D.DEFAULT_UP );
  34285. this.updateMatrix();
  34286. /**
  34287. * The directional light points from its position to the
  34288. * target's position.
  34289. *
  34290. * For the target's position to be changed to anything other
  34291. * than the default, it must be added to the scene.
  34292. *
  34293. * It is also possible to set the target to be another 3D object
  34294. * in the scene. The light will now track the target object.
  34295. *
  34296. * @type {Object3D}
  34297. */
  34298. this.target = new Object3D();
  34299. /**
  34300. * This property holds the light's shadow configuration.
  34301. *
  34302. * @type {DirectionalLightShadow}
  34303. */
  34304. this.shadow = new DirectionalLightShadow();
  34305. }
  34306. dispose() {
  34307. super.dispose();
  34308. this.shadow.dispose();
  34309. }
  34310. copy( source ) {
  34311. super.copy( source );
  34312. this.target = source.target.clone();
  34313. this.shadow = source.shadow.clone();
  34314. return this;
  34315. }
  34316. toJSON( meta ) {
  34317. const data = super.toJSON( meta );
  34318. data.object.shadow = this.shadow.toJSON();
  34319. data.object.target = this.target.uuid;
  34320. return data;
  34321. }
  34322. }
  34323. /**
  34324. * This light globally illuminates all objects in the scene equally.
  34325. *
  34326. * It cannot be used to cast shadows as it does not have a direction.
  34327. *
  34328. * ```js
  34329. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34330. * scene.add( light );
  34331. * ```
  34332. *
  34333. * @augments Light
  34334. */
  34335. class AmbientLight extends Light {
  34336. /**
  34337. * Constructs a new ambient light.
  34338. *
  34339. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34340. * @param {number} [intensity=1] - The light's strength/intensity.
  34341. */
  34342. constructor( color, intensity ) {
  34343. super( color, intensity );
  34344. /**
  34345. * This flag can be used for type testing.
  34346. *
  34347. * @type {boolean}
  34348. * @readonly
  34349. * @default true
  34350. */
  34351. this.isAmbientLight = true;
  34352. this.type = 'AmbientLight';
  34353. }
  34354. }
  34355. /**
  34356. * This class emits light uniformly across the face a rectangular plane.
  34357. * This light type can be used to simulate light sources such as bright
  34358. * windows or strip lighting.
  34359. *
  34360. * Important Notes:
  34361. *
  34362. * - There is no shadow support.
  34363. * - Only PBR materials are supported.
  34364. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34365. * into your app and init the uniforms/textures.
  34366. *
  34367. * ```js
  34368. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34369. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34370. *
  34371. * const intensity = 1; const width = 10; const height = 10;
  34372. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34373. * rectLight.position.set( 5, 5, 0 );
  34374. * rectLight.lookAt( 0, 0, 0 );
  34375. * scene.add( rectLight )
  34376. * ```
  34377. *
  34378. * @augments Light
  34379. */
  34380. class RectAreaLight extends Light {
  34381. /**
  34382. * Constructs a new area light.
  34383. *
  34384. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34385. * @param {number} [intensity=1] - The light's strength/intensity.
  34386. * @param {number} [width=10] - The width of the light.
  34387. * @param {number} [height=10] - The height of the light.
  34388. */
  34389. constructor( color, intensity, width = 10, height = 10 ) {
  34390. super( color, intensity );
  34391. /**
  34392. * This flag can be used for type testing.
  34393. *
  34394. * @type {boolean}
  34395. * @readonly
  34396. * @default true
  34397. */
  34398. this.isRectAreaLight = true;
  34399. this.type = 'RectAreaLight';
  34400. /**
  34401. * The width of the light.
  34402. *
  34403. * @type {number}
  34404. * @default 10
  34405. */
  34406. this.width = width;
  34407. /**
  34408. * The height of the light.
  34409. *
  34410. * @type {number}
  34411. * @default 10
  34412. */
  34413. this.height = height;
  34414. }
  34415. /**
  34416. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34417. * Changing the power will also change the light's intensity.
  34418. *
  34419. * @type {number}
  34420. */
  34421. get power() {
  34422. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34423. return this.intensity * this.width * this.height * Math.PI;
  34424. }
  34425. set power( power ) {
  34426. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34427. this.intensity = power / ( this.width * this.height * Math.PI );
  34428. }
  34429. copy( source ) {
  34430. super.copy( source );
  34431. this.width = source.width;
  34432. this.height = source.height;
  34433. return this;
  34434. }
  34435. toJSON( meta ) {
  34436. const data = super.toJSON( meta );
  34437. data.object.width = this.width;
  34438. data.object.height = this.height;
  34439. return data;
  34440. }
  34441. }
  34442. /**
  34443. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34444. * to encode lighting information.
  34445. *
  34446. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34447. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34448. */
  34449. class SphericalHarmonics3 {
  34450. /**
  34451. * Constructs a new spherical harmonics.
  34452. */
  34453. constructor() {
  34454. /**
  34455. * This flag can be used for type testing.
  34456. *
  34457. * @type {boolean}
  34458. * @readonly
  34459. * @default true
  34460. */
  34461. this.isSphericalHarmonics3 = true;
  34462. /**
  34463. * An array holding the (9) SH coefficients.
  34464. *
  34465. * @type {Array<Vector3>}
  34466. */
  34467. this.coefficients = [];
  34468. for ( let i = 0; i < 9; i ++ ) {
  34469. this.coefficients.push( new Vector3() );
  34470. }
  34471. }
  34472. /**
  34473. * Sets the given SH coefficients to this instance by copying
  34474. * the values.
  34475. *
  34476. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34477. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34478. */
  34479. set( coefficients ) {
  34480. for ( let i = 0; i < 9; i ++ ) {
  34481. this.coefficients[ i ].copy( coefficients[ i ] );
  34482. }
  34483. return this;
  34484. }
  34485. /**
  34486. * Sets all SH coefficients to `0`.
  34487. *
  34488. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34489. */
  34490. zero() {
  34491. for ( let i = 0; i < 9; i ++ ) {
  34492. this.coefficients[ i ].set( 0, 0, 0 );
  34493. }
  34494. return this;
  34495. }
  34496. /**
  34497. * Returns the radiance in the direction of the given normal.
  34498. *
  34499. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34500. * @param {Vector3} target - The target vector that is used to store the method's result.
  34501. * @return {Vector3} The radiance.
  34502. */
  34503. getAt( normal, target ) {
  34504. // normal is assumed to be unit length
  34505. const x = normal.x, y = normal.y, z = normal.z;
  34506. const coeff = this.coefficients;
  34507. // band 0
  34508. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34509. // band 1
  34510. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34511. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34512. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34513. // band 2
  34514. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34515. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34516. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34517. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34518. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34519. return target;
  34520. }
  34521. /**
  34522. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34523. * direction of the given normal.
  34524. *
  34525. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34526. * @param {Vector3} target - The target vector that is used to store the method's result.
  34527. * @return {Vector3} The irradiance.
  34528. */
  34529. getIrradianceAt( normal, target ) {
  34530. // normal is assumed to be unit length
  34531. const x = normal.x, y = normal.y, z = normal.z;
  34532. const coeff = this.coefficients;
  34533. // band 0
  34534. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34535. // band 1
  34536. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34537. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34538. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34539. // band 2
  34540. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34541. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34542. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34543. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34544. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34545. return target;
  34546. }
  34547. /**
  34548. * Adds the given SH to this instance.
  34549. *
  34550. * @param {SphericalHarmonics3} sh - The SH to add.
  34551. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34552. */
  34553. add( sh ) {
  34554. for ( let i = 0; i < 9; i ++ ) {
  34555. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34556. }
  34557. return this;
  34558. }
  34559. /**
  34560. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34561. * {@link SphericalHarmonics3#scale} at once.
  34562. *
  34563. * @param {SphericalHarmonics3} sh - The SH to add.
  34564. * @param {number} s - The scale factor.
  34565. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34566. */
  34567. addScaledSH( sh, s ) {
  34568. for ( let i = 0; i < 9; i ++ ) {
  34569. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34570. }
  34571. return this;
  34572. }
  34573. /**
  34574. * Scales this SH by the given scale factor.
  34575. *
  34576. * @param {number} s - The scale factor.
  34577. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34578. */
  34579. scale( s ) {
  34580. for ( let i = 0; i < 9; i ++ ) {
  34581. this.coefficients[ i ].multiplyScalar( s );
  34582. }
  34583. return this;
  34584. }
  34585. /**
  34586. * Linear interpolates between the given SH and this instance by the given
  34587. * alpha factor.
  34588. *
  34589. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34590. * @param {number} alpha - The alpha factor.
  34591. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34592. */
  34593. lerp( sh, alpha ) {
  34594. for ( let i = 0; i < 9; i ++ ) {
  34595. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34596. }
  34597. return this;
  34598. }
  34599. /**
  34600. * Returns `true` if this spherical harmonics is equal with the given one.
  34601. *
  34602. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34603. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34604. */
  34605. equals( sh ) {
  34606. for ( let i = 0; i < 9; i ++ ) {
  34607. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34608. return false;
  34609. }
  34610. }
  34611. return true;
  34612. }
  34613. /**
  34614. * Copies the values of the given spherical harmonics to this instance.
  34615. *
  34616. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34617. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34618. */
  34619. copy( sh ) {
  34620. return this.set( sh.coefficients );
  34621. }
  34622. /**
  34623. * Returns a new spherical harmonics with copied values from this instance.
  34624. *
  34625. * @return {SphericalHarmonics3} A clone of this instance.
  34626. */
  34627. clone() {
  34628. return new this.constructor().copy( this );
  34629. }
  34630. /**
  34631. * Sets the SH coefficients of this instance from the given array.
  34632. *
  34633. * @param {Array<number>} array - An array holding the SH coefficients.
  34634. * @param {number} [offset=0] - The array offset where to start copying.
  34635. * @return {SphericalHarmonics3} A clone of this instance.
  34636. */
  34637. fromArray( array, offset = 0 ) {
  34638. const coefficients = this.coefficients;
  34639. for ( let i = 0; i < 9; i ++ ) {
  34640. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34641. }
  34642. return this;
  34643. }
  34644. /**
  34645. * Returns an array with the SH coefficients, or copies them into the provided
  34646. * array. The coefficients are represented as numbers.
  34647. *
  34648. * @param {Array<number>} [array=[]] - The target array.
  34649. * @param {number} [offset=0] - The array offset where to start copying.
  34650. * @return {Array<number>} An array with flat SH coefficients.
  34651. */
  34652. toArray( array = [], offset = 0 ) {
  34653. const coefficients = this.coefficients;
  34654. for ( let i = 0; i < 9; i ++ ) {
  34655. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34656. }
  34657. return array;
  34658. }
  34659. /**
  34660. * Computes the SH basis for the given normal vector.
  34661. *
  34662. * @param {Vector3} normal - The normal.
  34663. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34664. */
  34665. static getBasisAt( normal, shBasis ) {
  34666. // normal is assumed to be unit length
  34667. const x = normal.x, y = normal.y, z = normal.z;
  34668. // band 0
  34669. shBasis[ 0 ] = 0.282095;
  34670. // band 1
  34671. shBasis[ 1 ] = 0.488603 * y;
  34672. shBasis[ 2 ] = 0.488603 * z;
  34673. shBasis[ 3 ] = 0.488603 * x;
  34674. // band 2
  34675. shBasis[ 4 ] = 1.092548 * x * y;
  34676. shBasis[ 5 ] = 1.092548 * y * z;
  34677. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34678. shBasis[ 7 ] = 1.092548 * x * z;
  34679. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34680. }
  34681. }
  34682. /**
  34683. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34684. * classical light sources (e.g. directional, point or spot lights), light
  34685. * probes do not emit light. Instead they store information about light
  34686. * passing through 3D space. During rendering, the light that hits a 3D
  34687. * object is approximated by using the data from the light probe.
  34688. *
  34689. * Light probes are usually created from (radiance) environment maps. The
  34690. * class {@link LightProbeGenerator} can be used to create light probes from
  34691. * cube textures or render targets. However, light estimation data could also
  34692. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34693. * augmented reality content that reacts to real world lighting.
  34694. *
  34695. * The current probe implementation in three.js supports so-called diffuse
  34696. * light probes. This type of light probe is functionally equivalent to an
  34697. * irradiance environment map.
  34698. *
  34699. * @augments Light
  34700. */
  34701. class LightProbe extends Light {
  34702. /**
  34703. * Constructs a new light probe.
  34704. *
  34705. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34706. * @param {number} [intensity=1] - The light's strength/intensity.
  34707. */
  34708. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34709. super( undefined, intensity );
  34710. /**
  34711. * This flag can be used for type testing.
  34712. *
  34713. * @type {boolean}
  34714. * @readonly
  34715. * @default true
  34716. */
  34717. this.isLightProbe = true;
  34718. /**
  34719. * A light probe uses spherical harmonics to encode lighting information.
  34720. *
  34721. * @type {SphericalHarmonics3}
  34722. */
  34723. this.sh = sh;
  34724. }
  34725. copy( source ) {
  34726. super.copy( source );
  34727. this.sh.copy( source.sh );
  34728. return this;
  34729. }
  34730. toJSON( meta ) {
  34731. const data = super.toJSON( meta );
  34732. data.object.sh = this.sh.toArray();
  34733. return data;
  34734. }
  34735. }
  34736. /**
  34737. * Class for loading materials. The files are internally
  34738. * loaded via {@link FileLoader}.
  34739. *
  34740. * ```js
  34741. * const loader = new THREE.MaterialLoader();
  34742. * const material = await loader.loadAsync( 'material.json' );
  34743. * ```
  34744. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34745. *
  34746. * @augments Loader
  34747. */
  34748. class MaterialLoader extends Loader {
  34749. /**
  34750. * Constructs a new material loader.
  34751. *
  34752. * @param {LoadingManager} [manager] - The loading manager.
  34753. */
  34754. constructor( manager ) {
  34755. super( manager );
  34756. /**
  34757. * A dictionary holding textures used by the material.
  34758. *
  34759. * @type {Object<string,Texture>}
  34760. */
  34761. this.textures = {};
  34762. }
  34763. /**
  34764. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34765. *
  34766. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34767. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34768. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34769. * @param {onErrorCallback} onError - Executed when errors occur.
  34770. */
  34771. load( url, onLoad, onProgress, onError ) {
  34772. const scope = this;
  34773. const loader = new FileLoader( scope.manager );
  34774. loader.setPath( scope.path );
  34775. loader.setRequestHeader( scope.requestHeader );
  34776. loader.setWithCredentials( scope.withCredentials );
  34777. loader.load( url, function ( text ) {
  34778. try {
  34779. onLoad( scope.parse( JSON.parse( text ) ) );
  34780. } catch ( e ) {
  34781. if ( onError ) {
  34782. onError( e );
  34783. } else {
  34784. error( e );
  34785. }
  34786. scope.manager.itemError( url );
  34787. }
  34788. }, onProgress, onError );
  34789. }
  34790. /**
  34791. * Parses the given JSON object and returns a material.
  34792. *
  34793. * @param {Object} json - The serialized material.
  34794. * @return {Material} The parsed material.
  34795. */
  34796. parse( json ) {
  34797. const textures = this.textures;
  34798. function getTexture( name ) {
  34799. if ( textures[ name ] === undefined ) {
  34800. warn( 'MaterialLoader: Undefined texture', name );
  34801. }
  34802. return textures[ name ];
  34803. }
  34804. const material = this.createMaterialFromType( json.type );
  34805. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34806. if ( json.name !== undefined ) material.name = json.name;
  34807. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34808. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34809. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34810. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34811. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34812. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34813. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34814. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34815. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34816. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34817. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34818. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34819. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34820. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34821. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34822. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34823. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34824. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34825. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34826. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34827. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34828. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34829. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34830. if ( json.fog !== undefined ) material.fog = json.fog;
  34831. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34832. if ( json.blending !== undefined ) material.blending = json.blending;
  34833. if ( json.combine !== undefined ) material.combine = json.combine;
  34834. if ( json.side !== undefined ) material.side = json.side;
  34835. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34836. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34837. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34838. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34839. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34840. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34841. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34842. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34843. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34844. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34845. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34846. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34847. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34848. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34849. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34850. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34851. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34852. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34853. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34854. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34855. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34856. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34857. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34858. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34859. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34860. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34861. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34862. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34863. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34864. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34865. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34866. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34867. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34868. if ( json.scale !== undefined ) material.scale = json.scale;
  34869. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34870. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34871. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34872. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34873. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34874. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34875. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34876. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34877. if ( json.visible !== undefined ) material.visible = json.visible;
  34878. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34879. if ( json.userData !== undefined ) material.userData = json.userData;
  34880. if ( json.vertexColors !== undefined ) {
  34881. if ( typeof json.vertexColors === 'number' ) {
  34882. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34883. } else {
  34884. material.vertexColors = json.vertexColors;
  34885. }
  34886. }
  34887. // Shader Material
  34888. if ( json.uniforms !== undefined ) {
  34889. for ( const name in json.uniforms ) {
  34890. const uniform = json.uniforms[ name ];
  34891. material.uniforms[ name ] = {};
  34892. switch ( uniform.type ) {
  34893. case 't':
  34894. material.uniforms[ name ].value = getTexture( uniform.value );
  34895. break;
  34896. case 'c':
  34897. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34898. break;
  34899. case 'v2':
  34900. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34901. break;
  34902. case 'v3':
  34903. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34904. break;
  34905. case 'v4':
  34906. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34907. break;
  34908. case 'm3':
  34909. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34910. break;
  34911. case 'm4':
  34912. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34913. break;
  34914. default:
  34915. material.uniforms[ name ].value = uniform.value;
  34916. }
  34917. }
  34918. }
  34919. if ( json.defines !== undefined ) material.defines = json.defines;
  34920. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34921. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34922. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34923. if ( json.extensions !== undefined ) {
  34924. for ( const key in json.extensions ) {
  34925. material.extensions[ key ] = json.extensions[ key ];
  34926. }
  34927. }
  34928. if ( json.lights !== undefined ) material.lights = json.lights;
  34929. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34930. // for PointsMaterial
  34931. if ( json.size !== undefined ) material.size = json.size;
  34932. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34933. // maps
  34934. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34935. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34936. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34937. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34938. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34939. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34940. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34941. if ( json.normalScale !== undefined ) {
  34942. let normalScale = json.normalScale;
  34943. if ( Array.isArray( normalScale ) === false ) {
  34944. // Blender exporter used to export a scalar. See #7459
  34945. normalScale = [ normalScale, normalScale ];
  34946. }
  34947. material.normalScale = new Vector2().fromArray( normalScale );
  34948. }
  34949. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34950. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34951. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34952. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34953. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34954. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34955. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34956. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34957. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34958. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34959. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34960. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34961. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34962. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34963. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34964. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34965. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34966. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34967. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34968. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34969. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34970. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34971. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34972. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34973. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34974. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34975. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34976. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34977. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34978. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34979. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34980. return material;
  34981. }
  34982. /**
  34983. * Textures are not embedded in the material JSON so they have
  34984. * to be injected before the loading process starts.
  34985. *
  34986. * @param {Object} value - A dictionary holding textures for material properties.
  34987. * @return {MaterialLoader} A reference to this material loader.
  34988. */
  34989. setTextures( value ) {
  34990. this.textures = value;
  34991. return this;
  34992. }
  34993. /**
  34994. * Creates a material for the given type.
  34995. *
  34996. * @param {string} type - The material type.
  34997. * @return {Material} The new material.
  34998. */
  34999. createMaterialFromType( type ) {
  35000. return MaterialLoader.createMaterialFromType( type );
  35001. }
  35002. /**
  35003. * Creates a material for the given type.
  35004. *
  35005. * @static
  35006. * @param {string} type - The material type.
  35007. * @return {Material} The new material.
  35008. */
  35009. static createMaterialFromType( type ) {
  35010. const materialLib = {
  35011. ShadowMaterial,
  35012. SpriteMaterial,
  35013. RawShaderMaterial,
  35014. ShaderMaterial,
  35015. PointsMaterial,
  35016. MeshPhysicalMaterial,
  35017. MeshStandardMaterial,
  35018. MeshPhongMaterial,
  35019. MeshToonMaterial,
  35020. MeshNormalMaterial,
  35021. MeshLambertMaterial,
  35022. MeshDepthMaterial,
  35023. MeshDistanceMaterial,
  35024. MeshBasicMaterial,
  35025. MeshMatcapMaterial,
  35026. LineDashedMaterial,
  35027. LineBasicMaterial,
  35028. Material
  35029. };
  35030. return new materialLib[ type ]();
  35031. }
  35032. }
  35033. /**
  35034. * A class with loader utility functions.
  35035. */
  35036. class LoaderUtils {
  35037. /**
  35038. * Extracts the base URL from the given URL.
  35039. *
  35040. * @param {string} url -The URL to extract the base URL from.
  35041. * @return {string} The extracted base URL.
  35042. */
  35043. static extractUrlBase( url ) {
  35044. const index = url.lastIndexOf( '/' );
  35045. if ( index === -1 ) return './';
  35046. return url.slice( 0, index + 1 );
  35047. }
  35048. /**
  35049. * Resolves relative URLs against the given path. Absolute paths, data urls,
  35050. * and blob URLs will be returned as is. Invalid URLs will return an empty
  35051. * string.
  35052. *
  35053. * @param {string} url -The URL to resolve.
  35054. * @param {string} path - The base path for relative URLs to be resolved against.
  35055. * @return {string} The resolved URL.
  35056. */
  35057. static resolveURL( url, path ) {
  35058. // Invalid URL
  35059. if ( typeof url !== 'string' || url === '' ) return '';
  35060. // Host Relative URL
  35061. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  35062. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  35063. }
  35064. // Absolute URL http://,https://,//
  35065. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  35066. // Data URI
  35067. if ( /^data:.*,.*$/i.test( url ) ) return url;
  35068. // Blob URL
  35069. if ( /^blob:.*$/i.test( url ) ) return url;
  35070. // Relative URL
  35071. return path + url;
  35072. }
  35073. }
  35074. /**
  35075. * An instanced version of a geometry.
  35076. */
  35077. class InstancedBufferGeometry extends BufferGeometry {
  35078. /**
  35079. * Constructs a new instanced buffer geometry.
  35080. */
  35081. constructor() {
  35082. super();
  35083. /**
  35084. * This flag can be used for type testing.
  35085. *
  35086. * @type {boolean}
  35087. * @readonly
  35088. * @default true
  35089. */
  35090. this.isInstancedBufferGeometry = true;
  35091. this.type = 'InstancedBufferGeometry';
  35092. /**
  35093. * The instance count.
  35094. *
  35095. * @type {number}
  35096. * @default Infinity
  35097. */
  35098. this.instanceCount = Infinity;
  35099. }
  35100. copy( source ) {
  35101. super.copy( source );
  35102. this.instanceCount = source.instanceCount;
  35103. return this;
  35104. }
  35105. toJSON() {
  35106. const data = super.toJSON();
  35107. data.instanceCount = this.instanceCount;
  35108. data.isInstancedBufferGeometry = true;
  35109. return data;
  35110. }
  35111. }
  35112. /**
  35113. * Class for loading geometries. The files are internally
  35114. * loaded via {@link FileLoader}.
  35115. *
  35116. * ```js
  35117. * const loader = new THREE.BufferGeometryLoader();
  35118. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  35119. *
  35120. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  35121. * const object = new THREE.Mesh( geometry, material );
  35122. * scene.add( object );
  35123. * ```
  35124. *
  35125. * @augments Loader
  35126. */
  35127. class BufferGeometryLoader extends Loader {
  35128. /**
  35129. * Constructs a new geometry loader.
  35130. *
  35131. * @param {LoadingManager} [manager] - The loading manager.
  35132. */
  35133. constructor( manager ) {
  35134. super( manager );
  35135. }
  35136. /**
  35137. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  35138. *
  35139. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35140. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  35141. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35142. * @param {onErrorCallback} onError - Executed when errors occur.
  35143. */
  35144. load( url, onLoad, onProgress, onError ) {
  35145. const scope = this;
  35146. const loader = new FileLoader( scope.manager );
  35147. loader.setPath( scope.path );
  35148. loader.setRequestHeader( scope.requestHeader );
  35149. loader.setWithCredentials( scope.withCredentials );
  35150. loader.load( url, function ( text ) {
  35151. try {
  35152. onLoad( scope.parse( JSON.parse( text ) ) );
  35153. } catch ( e ) {
  35154. if ( onError ) {
  35155. onError( e );
  35156. } else {
  35157. error( e );
  35158. }
  35159. scope.manager.itemError( url );
  35160. }
  35161. }, onProgress, onError );
  35162. }
  35163. /**
  35164. * Parses the given JSON object and returns a geometry.
  35165. *
  35166. * @param {Object} json - The serialized geometry.
  35167. * @return {BufferGeometry} The parsed geometry.
  35168. */
  35169. parse( json ) {
  35170. const interleavedBufferMap = {};
  35171. const arrayBufferMap = {};
  35172. function getInterleavedBuffer( json, uuid ) {
  35173. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  35174. const interleavedBuffers = json.interleavedBuffers;
  35175. const interleavedBuffer = interleavedBuffers[ uuid ];
  35176. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  35177. const array = getTypedArray( interleavedBuffer.type, buffer );
  35178. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  35179. ib.uuid = interleavedBuffer.uuid;
  35180. interleavedBufferMap[ uuid ] = ib;
  35181. return ib;
  35182. }
  35183. function getArrayBuffer( json, uuid ) {
  35184. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  35185. const arrayBuffers = json.arrayBuffers;
  35186. const arrayBuffer = arrayBuffers[ uuid ];
  35187. const ab = new Uint32Array( arrayBuffer ).buffer;
  35188. arrayBufferMap[ uuid ] = ab;
  35189. return ab;
  35190. }
  35191. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  35192. const index = json.data.index;
  35193. if ( index !== undefined ) {
  35194. const typedArray = getTypedArray( index.type, index.array );
  35195. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35196. }
  35197. const attributes = json.data.attributes;
  35198. for ( const key in attributes ) {
  35199. const attribute = attributes[ key ];
  35200. let bufferAttribute;
  35201. if ( attribute.isInterleavedBufferAttribute ) {
  35202. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35203. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35204. } else {
  35205. const typedArray = getTypedArray( attribute.type, attribute.array );
  35206. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35207. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35208. }
  35209. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35210. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35211. geometry.setAttribute( key, bufferAttribute );
  35212. }
  35213. const morphAttributes = json.data.morphAttributes;
  35214. if ( morphAttributes ) {
  35215. for ( const key in morphAttributes ) {
  35216. const attributeArray = morphAttributes[ key ];
  35217. const array = [];
  35218. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35219. const attribute = attributeArray[ i ];
  35220. let bufferAttribute;
  35221. if ( attribute.isInterleavedBufferAttribute ) {
  35222. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35223. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35224. } else {
  35225. const typedArray = getTypedArray( attribute.type, attribute.array );
  35226. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35227. }
  35228. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35229. array.push( bufferAttribute );
  35230. }
  35231. geometry.morphAttributes[ key ] = array;
  35232. }
  35233. }
  35234. const morphTargetsRelative = json.data.morphTargetsRelative;
  35235. if ( morphTargetsRelative ) {
  35236. geometry.morphTargetsRelative = true;
  35237. }
  35238. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35239. if ( groups !== undefined ) {
  35240. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35241. const group = groups[ i ];
  35242. geometry.addGroup( group.start, group.count, group.materialIndex );
  35243. }
  35244. }
  35245. const boundingSphere = json.data.boundingSphere;
  35246. if ( boundingSphere !== undefined ) {
  35247. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35248. }
  35249. if ( json.name ) geometry.name = json.name;
  35250. if ( json.userData ) geometry.userData = json.userData;
  35251. return geometry;
  35252. }
  35253. }
  35254. /**
  35255. * 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).
  35256. * The files are internally loaded via {@link FileLoader}.
  35257. *
  35258. * ```js
  35259. * const loader = new THREE.ObjectLoader();
  35260. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35261. * scene.add( obj );
  35262. *
  35263. * // Alternatively, to parse a previously loaded JSON structure
  35264. * const object = await loader.parseAsync( a_json_object );
  35265. * scene.add( object );
  35266. * ```
  35267. *
  35268. * @augments Loader
  35269. */
  35270. class ObjectLoader extends Loader {
  35271. /**
  35272. * Constructs a new object loader.
  35273. *
  35274. * @param {LoadingManager} [manager] - The loading manager.
  35275. */
  35276. constructor( manager ) {
  35277. super( manager );
  35278. }
  35279. /**
  35280. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35281. *
  35282. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35283. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35284. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35285. * @param {onErrorCallback} onError - Executed when errors occur.
  35286. */
  35287. load( url, onLoad, onProgress, onError ) {
  35288. const scope = this;
  35289. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35290. this.resourcePath = this.resourcePath || path;
  35291. const loader = new FileLoader( this.manager );
  35292. loader.setPath( this.path );
  35293. loader.setRequestHeader( this.requestHeader );
  35294. loader.setWithCredentials( this.withCredentials );
  35295. loader.load( url, function ( text ) {
  35296. let json = null;
  35297. try {
  35298. json = JSON.parse( text );
  35299. } catch ( error ) {
  35300. if ( onError !== undefined ) onError( error );
  35301. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35302. return;
  35303. }
  35304. const metadata = json.metadata;
  35305. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35306. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35307. error( 'ObjectLoader: Can\'t load ' + url );
  35308. return;
  35309. }
  35310. scope.parse( json, onLoad );
  35311. }, onProgress, onError );
  35312. }
  35313. /**
  35314. * Async version of {@link ObjectLoader#load}.
  35315. *
  35316. * @async
  35317. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35318. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35319. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35320. */
  35321. async loadAsync( url, onProgress ) {
  35322. const scope = this;
  35323. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35324. this.resourcePath = this.resourcePath || path;
  35325. const loader = new FileLoader( this.manager );
  35326. loader.setPath( this.path );
  35327. loader.setRequestHeader( this.requestHeader );
  35328. loader.setWithCredentials( this.withCredentials );
  35329. const text = await loader.loadAsync( url, onProgress );
  35330. const json = JSON.parse( text );
  35331. const metadata = json.metadata;
  35332. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35333. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35334. }
  35335. return await scope.parseAsync( json );
  35336. }
  35337. /**
  35338. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35339. * but can also be used directly to parse a previously loaded JSON structure.
  35340. *
  35341. * @param {Object} json - The serialized 3D object.
  35342. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35343. * @return {Object3D} The parsed 3D object.
  35344. */
  35345. parse( json, onLoad ) {
  35346. const animations = this.parseAnimations( json.animations );
  35347. const shapes = this.parseShapes( json.shapes );
  35348. const geometries = this.parseGeometries( json.geometries, shapes );
  35349. const images = this.parseImages( json.images, function () {
  35350. if ( onLoad !== undefined ) onLoad( object );
  35351. } );
  35352. const textures = this.parseTextures( json.textures, images );
  35353. const materials = this.parseMaterials( json.materials, textures );
  35354. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35355. const skeletons = this.parseSkeletons( json.skeletons, object );
  35356. this.bindSkeletons( object, skeletons );
  35357. this.bindLightTargets( object );
  35358. //
  35359. if ( onLoad !== undefined ) {
  35360. let hasImages = false;
  35361. for ( const uuid in images ) {
  35362. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35363. hasImages = true;
  35364. break;
  35365. }
  35366. }
  35367. if ( hasImages === false ) onLoad( object );
  35368. }
  35369. return object;
  35370. }
  35371. /**
  35372. * Async version of {@link ObjectLoader#parse}.
  35373. *
  35374. * @param {Object} json - The serialized 3D object.
  35375. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35376. */
  35377. async parseAsync( json ) {
  35378. const animations = this.parseAnimations( json.animations );
  35379. const shapes = this.parseShapes( json.shapes );
  35380. const geometries = this.parseGeometries( json.geometries, shapes );
  35381. const images = await this.parseImagesAsync( json.images );
  35382. const textures = this.parseTextures( json.textures, images );
  35383. const materials = this.parseMaterials( json.materials, textures );
  35384. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35385. const skeletons = this.parseSkeletons( json.skeletons, object );
  35386. this.bindSkeletons( object, skeletons );
  35387. this.bindLightTargets( object );
  35388. return object;
  35389. }
  35390. // internals
  35391. parseShapes( json ) {
  35392. const shapes = {};
  35393. if ( json !== undefined ) {
  35394. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35395. const shape = new Shape().fromJSON( json[ i ] );
  35396. shapes[ shape.uuid ] = shape;
  35397. }
  35398. }
  35399. return shapes;
  35400. }
  35401. parseSkeletons( json, object ) {
  35402. const skeletons = {};
  35403. const bones = {};
  35404. // generate bone lookup table
  35405. object.traverse( function ( child ) {
  35406. if ( child.isBone ) bones[ child.uuid ] = child;
  35407. } );
  35408. // create skeletons
  35409. if ( json !== undefined ) {
  35410. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35411. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35412. skeletons[ skeleton.uuid ] = skeleton;
  35413. }
  35414. }
  35415. return skeletons;
  35416. }
  35417. parseGeometries( json, shapes ) {
  35418. const geometries = {};
  35419. if ( json !== undefined ) {
  35420. const bufferGeometryLoader = new BufferGeometryLoader();
  35421. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35422. let geometry;
  35423. const data = json[ i ];
  35424. switch ( data.type ) {
  35425. case 'BufferGeometry':
  35426. case 'InstancedBufferGeometry':
  35427. geometry = bufferGeometryLoader.parse( data );
  35428. break;
  35429. default:
  35430. if ( data.type in Geometries ) {
  35431. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35432. } else {
  35433. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35434. }
  35435. }
  35436. geometry.uuid = data.uuid;
  35437. if ( data.name !== undefined ) geometry.name = data.name;
  35438. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35439. geometries[ data.uuid ] = geometry;
  35440. }
  35441. }
  35442. return geometries;
  35443. }
  35444. parseMaterials( json, textures ) {
  35445. const cache = {}; // MultiMaterial
  35446. const materials = {};
  35447. if ( json !== undefined ) {
  35448. const loader = new MaterialLoader();
  35449. loader.setTextures( textures );
  35450. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35451. const data = json[ i ];
  35452. if ( cache[ data.uuid ] === undefined ) {
  35453. cache[ data.uuid ] = loader.parse( data );
  35454. }
  35455. materials[ data.uuid ] = cache[ data.uuid ];
  35456. }
  35457. }
  35458. return materials;
  35459. }
  35460. parseAnimations( json ) {
  35461. const animations = {};
  35462. if ( json !== undefined ) {
  35463. for ( let i = 0; i < json.length; i ++ ) {
  35464. const data = json[ i ];
  35465. const clip = AnimationClip.parse( data );
  35466. animations[ clip.uuid ] = clip;
  35467. }
  35468. }
  35469. return animations;
  35470. }
  35471. parseImages( json, onLoad ) {
  35472. const scope = this;
  35473. const images = {};
  35474. let loader;
  35475. function loadImage( url ) {
  35476. scope.manager.itemStart( url );
  35477. return loader.load( url, function () {
  35478. scope.manager.itemEnd( url );
  35479. }, undefined, function () {
  35480. scope.manager.itemError( url );
  35481. scope.manager.itemEnd( url );
  35482. } );
  35483. }
  35484. function deserializeImage( image ) {
  35485. if ( typeof image === 'string' ) {
  35486. const url = image;
  35487. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35488. return loadImage( path );
  35489. } else {
  35490. if ( image.data ) {
  35491. return {
  35492. data: getTypedArray( image.type, image.data ),
  35493. width: image.width,
  35494. height: image.height
  35495. };
  35496. } else {
  35497. return null;
  35498. }
  35499. }
  35500. }
  35501. if ( json !== undefined && json.length > 0 ) {
  35502. const manager = new LoadingManager( onLoad );
  35503. loader = new ImageLoader( manager );
  35504. loader.setCrossOrigin( this.crossOrigin );
  35505. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35506. const image = json[ i ];
  35507. const url = image.url;
  35508. if ( Array.isArray( url ) ) {
  35509. // load array of images e.g CubeTexture
  35510. const imageArray = [];
  35511. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35512. const currentUrl = url[ j ];
  35513. const deserializedImage = deserializeImage( currentUrl );
  35514. if ( deserializedImage !== null ) {
  35515. if ( deserializedImage instanceof HTMLImageElement ) {
  35516. imageArray.push( deserializedImage );
  35517. } else {
  35518. // special case: handle array of data textures for cube textures
  35519. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35520. }
  35521. }
  35522. }
  35523. images[ image.uuid ] = new Source( imageArray );
  35524. } else {
  35525. // load single image
  35526. const deserializedImage = deserializeImage( image.url );
  35527. images[ image.uuid ] = new Source( deserializedImage );
  35528. }
  35529. }
  35530. }
  35531. return images;
  35532. }
  35533. async parseImagesAsync( json ) {
  35534. const scope = this;
  35535. const images = {};
  35536. let loader;
  35537. async function deserializeImage( image ) {
  35538. if ( typeof image === 'string' ) {
  35539. const url = image;
  35540. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35541. return await loader.loadAsync( path );
  35542. } else {
  35543. if ( image.data ) {
  35544. return {
  35545. data: getTypedArray( image.type, image.data ),
  35546. width: image.width,
  35547. height: image.height
  35548. };
  35549. } else {
  35550. return null;
  35551. }
  35552. }
  35553. }
  35554. if ( json !== undefined && json.length > 0 ) {
  35555. loader = new ImageLoader( this.manager );
  35556. loader.setCrossOrigin( this.crossOrigin );
  35557. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35558. const image = json[ i ];
  35559. const url = image.url;
  35560. if ( Array.isArray( url ) ) {
  35561. // load array of images e.g CubeTexture
  35562. const imageArray = [];
  35563. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35564. const currentUrl = url[ j ];
  35565. const deserializedImage = await deserializeImage( currentUrl );
  35566. if ( deserializedImage !== null ) {
  35567. if ( deserializedImage instanceof HTMLImageElement ) {
  35568. imageArray.push( deserializedImage );
  35569. } else {
  35570. // special case: handle array of data textures for cube textures
  35571. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35572. }
  35573. }
  35574. }
  35575. images[ image.uuid ] = new Source( imageArray );
  35576. } else {
  35577. // load single image
  35578. const deserializedImage = await deserializeImage( image.url );
  35579. images[ image.uuid ] = new Source( deserializedImage );
  35580. }
  35581. }
  35582. }
  35583. return images;
  35584. }
  35585. parseTextures( json, images ) {
  35586. function parseConstant( value, type ) {
  35587. if ( typeof value === 'number' ) return value;
  35588. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35589. return type[ value ];
  35590. }
  35591. const textures = {};
  35592. if ( json !== undefined ) {
  35593. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35594. const data = json[ i ];
  35595. if ( data.image === undefined ) {
  35596. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35597. }
  35598. if ( images[ data.image ] === undefined ) {
  35599. warn( 'ObjectLoader: Undefined image', data.image );
  35600. }
  35601. const source = images[ data.image ];
  35602. const image = source.data;
  35603. let texture;
  35604. if ( Array.isArray( image ) ) {
  35605. texture = new CubeTexture();
  35606. if ( image.length === 6 ) texture.needsUpdate = true;
  35607. } else {
  35608. if ( image && image.data ) {
  35609. texture = new DataTexture();
  35610. } else {
  35611. texture = new Texture();
  35612. }
  35613. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35614. }
  35615. texture.source = source;
  35616. texture.uuid = data.uuid;
  35617. if ( data.name !== undefined ) texture.name = data.name;
  35618. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35619. if ( data.channel !== undefined ) texture.channel = data.channel;
  35620. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35621. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35622. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35623. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35624. if ( data.wrap !== undefined ) {
  35625. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35626. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35627. }
  35628. if ( data.format !== undefined ) texture.format = data.format;
  35629. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35630. if ( data.type !== undefined ) texture.type = data.type;
  35631. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35632. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35633. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35634. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35635. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35636. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35637. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35638. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35639. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35640. if ( data.userData !== undefined ) texture.userData = data.userData;
  35641. textures[ data.uuid ] = texture;
  35642. }
  35643. }
  35644. return textures;
  35645. }
  35646. parseObject( data, geometries, materials, textures, animations ) {
  35647. let object;
  35648. function getGeometry( name ) {
  35649. if ( geometries[ name ] === undefined ) {
  35650. warn( 'ObjectLoader: Undefined geometry', name );
  35651. }
  35652. return geometries[ name ];
  35653. }
  35654. function getMaterial( name ) {
  35655. if ( name === undefined ) return undefined;
  35656. if ( Array.isArray( name ) ) {
  35657. const array = [];
  35658. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35659. const uuid = name[ i ];
  35660. if ( materials[ uuid ] === undefined ) {
  35661. warn( 'ObjectLoader: Undefined material', uuid );
  35662. }
  35663. array.push( materials[ uuid ] );
  35664. }
  35665. return array;
  35666. }
  35667. if ( materials[ name ] === undefined ) {
  35668. warn( 'ObjectLoader: Undefined material', name );
  35669. }
  35670. return materials[ name ];
  35671. }
  35672. function getTexture( uuid ) {
  35673. if ( textures[ uuid ] === undefined ) {
  35674. warn( 'ObjectLoader: Undefined texture', uuid );
  35675. }
  35676. return textures[ uuid ];
  35677. }
  35678. let geometry, material;
  35679. switch ( data.type ) {
  35680. case 'Scene':
  35681. object = new Scene();
  35682. if ( data.background !== undefined ) {
  35683. if ( Number.isInteger( data.background ) ) {
  35684. object.background = new Color( data.background );
  35685. } else {
  35686. object.background = getTexture( data.background );
  35687. }
  35688. }
  35689. if ( data.environment !== undefined ) {
  35690. object.environment = getTexture( data.environment );
  35691. }
  35692. if ( data.fog !== undefined ) {
  35693. if ( data.fog.type === 'Fog' ) {
  35694. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35695. } else if ( data.fog.type === 'FogExp2' ) {
  35696. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35697. }
  35698. if ( data.fog.name !== '' ) {
  35699. object.fog.name = data.fog.name;
  35700. }
  35701. }
  35702. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35703. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35704. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35705. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35706. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35707. break;
  35708. case 'PerspectiveCamera':
  35709. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35710. if ( data.focus !== undefined ) object.focus = data.focus;
  35711. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35712. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35713. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35714. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35715. break;
  35716. case 'OrthographicCamera':
  35717. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35718. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35719. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35720. break;
  35721. case 'AmbientLight':
  35722. object = new AmbientLight( data.color, data.intensity );
  35723. break;
  35724. case 'DirectionalLight':
  35725. object = new DirectionalLight( data.color, data.intensity );
  35726. object.target = data.target || '';
  35727. break;
  35728. case 'PointLight':
  35729. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35730. break;
  35731. case 'RectAreaLight':
  35732. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35733. break;
  35734. case 'SpotLight':
  35735. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35736. object.target = data.target || '';
  35737. break;
  35738. case 'HemisphereLight':
  35739. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35740. break;
  35741. case 'LightProbe':
  35742. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35743. object = new LightProbe( sh, data.intensity );
  35744. break;
  35745. case 'SkinnedMesh':
  35746. geometry = getGeometry( data.geometry );
  35747. material = getMaterial( data.material );
  35748. object = new SkinnedMesh( geometry, material );
  35749. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35750. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35751. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35752. break;
  35753. case 'Mesh':
  35754. geometry = getGeometry( data.geometry );
  35755. material = getMaterial( data.material );
  35756. object = new Mesh( geometry, material );
  35757. break;
  35758. case 'InstancedMesh':
  35759. geometry = getGeometry( data.geometry );
  35760. material = getMaterial( data.material );
  35761. const count = data.count;
  35762. const instanceMatrix = data.instanceMatrix;
  35763. const instanceColor = data.instanceColor;
  35764. object = new InstancedMesh( geometry, material, count );
  35765. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35766. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35767. break;
  35768. case 'BatchedMesh':
  35769. geometry = getGeometry( data.geometry );
  35770. material = getMaterial( data.material );
  35771. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35772. object.geometry = geometry;
  35773. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35774. object.sortObjects = data.sortObjects;
  35775. object._drawRanges = data.drawRanges;
  35776. object._reservedRanges = data.reservedRanges;
  35777. object._geometryInfo = data.geometryInfo.map( info => {
  35778. let box = null;
  35779. let sphere = null;
  35780. if ( info.boundingBox !== undefined ) {
  35781. box = new Box3().fromJSON( info.boundingBox );
  35782. }
  35783. if ( info.boundingSphere !== undefined ) {
  35784. sphere = new Sphere().fromJSON( info.boundingSphere );
  35785. }
  35786. return {
  35787. ...info,
  35788. boundingBox: box,
  35789. boundingSphere: sphere
  35790. };
  35791. } );
  35792. object._instanceInfo = data.instanceInfo;
  35793. object._availableInstanceIds = data._availableInstanceIds;
  35794. object._availableGeometryIds = data._availableGeometryIds;
  35795. object._nextIndexStart = data.nextIndexStart;
  35796. object._nextVertexStart = data.nextVertexStart;
  35797. object._geometryCount = data.geometryCount;
  35798. object._maxInstanceCount = data.maxInstanceCount;
  35799. object._maxVertexCount = data.maxVertexCount;
  35800. object._maxIndexCount = data.maxIndexCount;
  35801. object._geometryInitialized = data.geometryInitialized;
  35802. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35803. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35804. if ( data.colorsTexture !== undefined ) {
  35805. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35806. }
  35807. if ( data.boundingSphere !== undefined ) {
  35808. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35809. }
  35810. if ( data.boundingBox !== undefined ) {
  35811. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35812. }
  35813. break;
  35814. case 'LOD':
  35815. object = new LOD();
  35816. break;
  35817. case 'Line':
  35818. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35819. break;
  35820. case 'LineLoop':
  35821. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35822. break;
  35823. case 'LineSegments':
  35824. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35825. break;
  35826. case 'PointCloud':
  35827. case 'Points':
  35828. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35829. break;
  35830. case 'Sprite':
  35831. object = new Sprite( getMaterial( data.material ) );
  35832. break;
  35833. case 'Group':
  35834. object = new Group();
  35835. break;
  35836. case 'Bone':
  35837. object = new Bone();
  35838. break;
  35839. default:
  35840. object = new Object3D();
  35841. }
  35842. object.uuid = data.uuid;
  35843. if ( data.name !== undefined ) object.name = data.name;
  35844. if ( data.matrix !== undefined ) {
  35845. object.matrix.fromArray( data.matrix );
  35846. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35847. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35848. } else {
  35849. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35850. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35851. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35852. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35853. }
  35854. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35855. if ( data.pivot !== undefined ) object.pivot = new Vector3().fromArray( data.pivot );
  35856. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35857. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35858. if ( data.shadow ) {
  35859. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35860. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35861. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35862. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35863. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35864. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35865. }
  35866. if ( data.visible !== undefined ) object.visible = data.visible;
  35867. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35868. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35869. if ( data.static !== undefined ) object.static = data.static;
  35870. if ( data.userData !== undefined ) object.userData = data.userData;
  35871. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35872. if ( data.children !== undefined ) {
  35873. const children = data.children;
  35874. for ( let i = 0; i < children.length; i ++ ) {
  35875. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35876. }
  35877. }
  35878. if ( data.animations !== undefined ) {
  35879. const objectAnimations = data.animations;
  35880. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35881. const uuid = objectAnimations[ i ];
  35882. object.animations.push( animations[ uuid ] );
  35883. }
  35884. }
  35885. if ( data.type === 'LOD' ) {
  35886. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35887. const levels = data.levels;
  35888. for ( let l = 0; l < levels.length; l ++ ) {
  35889. const level = levels[ l ];
  35890. const child = object.getObjectByProperty( 'uuid', level.object );
  35891. if ( child !== undefined ) {
  35892. object.addLevel( child, level.distance, level.hysteresis );
  35893. }
  35894. }
  35895. }
  35896. return object;
  35897. }
  35898. bindSkeletons( object, skeletons ) {
  35899. if ( Object.keys( skeletons ).length === 0 ) return;
  35900. object.traverse( function ( child ) {
  35901. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35902. const skeleton = skeletons[ child.skeleton ];
  35903. if ( skeleton === undefined ) {
  35904. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35905. } else {
  35906. child.bind( skeleton, child.bindMatrix );
  35907. }
  35908. }
  35909. } );
  35910. }
  35911. bindLightTargets( object ) {
  35912. object.traverse( function ( child ) {
  35913. if ( child.isDirectionalLight || child.isSpotLight ) {
  35914. const uuid = child.target;
  35915. const target = object.getObjectByProperty( 'uuid', uuid );
  35916. if ( target !== undefined ) {
  35917. child.target = target;
  35918. } else {
  35919. child.target = new Object3D();
  35920. }
  35921. }
  35922. } );
  35923. }
  35924. }
  35925. const TEXTURE_MAPPING = {
  35926. UVMapping: UVMapping,
  35927. CubeReflectionMapping: CubeReflectionMapping,
  35928. CubeRefractionMapping: CubeRefractionMapping,
  35929. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35930. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35931. CubeUVReflectionMapping: CubeUVReflectionMapping
  35932. };
  35933. const TEXTURE_WRAPPING = {
  35934. RepeatWrapping: RepeatWrapping,
  35935. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35936. MirroredRepeatWrapping: MirroredRepeatWrapping
  35937. };
  35938. const TEXTURE_FILTER = {
  35939. NearestFilter: NearestFilter,
  35940. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35941. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35942. LinearFilter: LinearFilter,
  35943. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35944. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35945. };
  35946. const _errorMap = new WeakMap();
  35947. /**
  35948. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35949. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35950. * textures for rendering.
  35951. *
  35952. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35953. * These options need to be configured via {@link ImageBitmapLoader#setOptions} prior to loading,
  35954. * unlike regular images which can be configured on the Texture to set these options on GPU upload instead.
  35955. *
  35956. * To match the default behaviour of {@link Texture}, the following options are needed:
  35957. *
  35958. * ```js
  35959. * { imageOrientation: 'flipY', premultiplyAlpha: 'none' }
  35960. * ```
  35961. *
  35962. * Also note that unlike {@link FileLoader}, this loader will only avoid multiple concurrent requests to the same URL if {@link Cache} is enabled.
  35963. *
  35964. * ```js
  35965. * const loader = new THREE.ImageBitmapLoader();
  35966. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35967. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35968. *
  35969. * const texture = new THREE.Texture( imageBitmap );
  35970. * texture.needsUpdate = true;
  35971. * ```
  35972. *
  35973. * @augments Loader
  35974. */
  35975. class ImageBitmapLoader extends Loader {
  35976. /**
  35977. * Constructs a new image bitmap loader.
  35978. *
  35979. * @param {LoadingManager} [manager] - The loading manager.
  35980. */
  35981. constructor( manager ) {
  35982. super( manager );
  35983. /**
  35984. * This flag can be used for type testing.
  35985. *
  35986. * @type {boolean}
  35987. * @readonly
  35988. * @default true
  35989. */
  35990. this.isImageBitmapLoader = true;
  35991. if ( typeof createImageBitmap === 'undefined' ) {
  35992. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35993. }
  35994. if ( typeof fetch === 'undefined' ) {
  35995. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35996. }
  35997. /**
  35998. * Represents the loader options.
  35999. *
  36000. * @type {Object}
  36001. * @default {premultiplyAlpha:'none'}
  36002. */
  36003. this.options = { premultiplyAlpha: 'none' };
  36004. /**
  36005. * Used for aborting requests.
  36006. *
  36007. * @private
  36008. * @type {AbortController}
  36009. */
  36010. this._abortController = new AbortController();
  36011. }
  36012. /**
  36013. * Sets the given loader options. The structure of the object must match the `options` parameter of
  36014. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  36015. *
  36016. * @param {Object} options - The loader options to set.
  36017. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  36018. */
  36019. setOptions( options ) {
  36020. this.options = options;
  36021. return this;
  36022. }
  36023. /**
  36024. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  36025. *
  36026. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36027. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  36028. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  36029. * @param {onErrorCallback} onError - Executed when errors occur.
  36030. * @return {ImageBitmap|undefined} The image bitmap.
  36031. */
  36032. load( url, onLoad, onProgress, onError ) {
  36033. if ( url === undefined ) url = '';
  36034. if ( this.path !== undefined ) url = this.path + url;
  36035. url = this.manager.resolveURL( url );
  36036. const scope = this;
  36037. const cached = Cache.get( `image-bitmap:${url}` );
  36038. if ( cached !== undefined ) {
  36039. scope.manager.itemStart( url );
  36040. // If cached is a promise, wait for it to resolve
  36041. if ( cached.then ) {
  36042. cached.then( imageBitmap => {
  36043. // check if there is an error for the cached promise
  36044. if ( _errorMap.has( cached ) === true ) {
  36045. if ( onError ) onError( _errorMap.get( cached ) );
  36046. scope.manager.itemError( url );
  36047. scope.manager.itemEnd( url );
  36048. } else {
  36049. if ( onLoad ) onLoad( imageBitmap );
  36050. scope.manager.itemEnd( url );
  36051. return imageBitmap;
  36052. }
  36053. } );
  36054. return;
  36055. }
  36056. // If cached is not a promise (i.e., it's already an imageBitmap)
  36057. setTimeout( function () {
  36058. if ( onLoad ) onLoad( cached );
  36059. scope.manager.itemEnd( url );
  36060. }, 0 );
  36061. return cached;
  36062. }
  36063. const fetchOptions = {};
  36064. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  36065. fetchOptions.headers = this.requestHeader;
  36066. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  36067. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  36068. return res.blob();
  36069. } ).then( function ( blob ) {
  36070. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  36071. } ).then( function ( imageBitmap ) {
  36072. Cache.add( `image-bitmap:${url}`, imageBitmap );
  36073. if ( onLoad ) onLoad( imageBitmap );
  36074. scope.manager.itemEnd( url );
  36075. return imageBitmap;
  36076. } ).catch( function ( e ) {
  36077. if ( onError ) onError( e );
  36078. _errorMap.set( promise, e );
  36079. Cache.remove( `image-bitmap:${url}` );
  36080. scope.manager.itemError( url );
  36081. scope.manager.itemEnd( url );
  36082. } );
  36083. Cache.add( `image-bitmap:${url}`, promise );
  36084. scope.manager.itemStart( url );
  36085. }
  36086. /**
  36087. * Aborts ongoing fetch requests.
  36088. *
  36089. * @return {ImageBitmapLoader} A reference to this instance.
  36090. */
  36091. abort() {
  36092. this._abortController.abort();
  36093. this._abortController = new AbortController();
  36094. return this;
  36095. }
  36096. }
  36097. let _context;
  36098. /**
  36099. * Manages the global audio context in the engine.
  36100. *
  36101. * @hideconstructor
  36102. */
  36103. class AudioContext {
  36104. /**
  36105. * Returns the global native audio context.
  36106. *
  36107. * @return {AudioContext} The native audio context.
  36108. */
  36109. static getContext() {
  36110. if ( _context === undefined ) {
  36111. _context = new ( window.AudioContext || window.webkitAudioContext )();
  36112. }
  36113. return _context;
  36114. }
  36115. /**
  36116. * Allows to set the global native audio context from outside.
  36117. *
  36118. * @param {AudioContext} value - The native context to set.
  36119. */
  36120. static setContext( value ) {
  36121. _context = value;
  36122. }
  36123. }
  36124. /**
  36125. * Class for loading audio buffers. Audios are internally
  36126. * loaded via {@link FileLoader}.
  36127. *
  36128. * ```js
  36129. * const audioListener = new THREE.AudioListener();
  36130. * const ambientSound = new THREE.Audio( audioListener );
  36131. *
  36132. * const loader = new THREE.AudioLoader();
  36133. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  36134. *
  36135. * ambientSound.setBuffer( audioBuffer );
  36136. * ambientSound.play();
  36137. * ```
  36138. *
  36139. * @augments Loader
  36140. */
  36141. class AudioLoader extends Loader {
  36142. /**
  36143. * Constructs a new audio loader.
  36144. *
  36145. * @param {LoadingManager} [manager] - The loading manager.
  36146. */
  36147. constructor( manager ) {
  36148. super( manager );
  36149. }
  36150. /**
  36151. * Starts loading from the given URL and passes the loaded audio buffer
  36152. * to the `onLoad()` callback.
  36153. *
  36154. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  36155. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  36156. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  36157. * @param {onErrorCallback} onError - Executed when errors occur.
  36158. */
  36159. load( url, onLoad, onProgress, onError ) {
  36160. const scope = this;
  36161. const loader = new FileLoader( this.manager );
  36162. loader.setResponseType( 'arraybuffer' );
  36163. loader.setPath( this.path );
  36164. loader.setRequestHeader( this.requestHeader );
  36165. loader.setWithCredentials( this.withCredentials );
  36166. loader.load( url, function ( buffer ) {
  36167. try {
  36168. // Create a copy of the buffer. The `decodeAudioData` method
  36169. // detaches the buffer when complete, preventing reuse.
  36170. const bufferCopy = buffer.slice( 0 );
  36171. const context = AudioContext.getContext();
  36172. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  36173. onLoad( audioBuffer );
  36174. } ).catch( handleError );
  36175. } catch ( e ) {
  36176. handleError( e );
  36177. }
  36178. }, onProgress, onError );
  36179. function handleError( e ) {
  36180. if ( onError ) {
  36181. onError( e );
  36182. } else {
  36183. error( e );
  36184. }
  36185. scope.manager.itemError( url );
  36186. }
  36187. }
  36188. }
  36189. const _eyeRight = /*@__PURE__*/ new Matrix4();
  36190. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  36191. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  36192. /**
  36193. * A special type of camera that uses two perspective cameras with
  36194. * stereoscopic projection. Can be used for rendering stereo effects
  36195. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  36196. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  36197. */
  36198. class StereoCamera {
  36199. /**
  36200. * Constructs a new stereo camera.
  36201. */
  36202. constructor() {
  36203. /**
  36204. * The type property is used for detecting the object type
  36205. * in context of serialization/deserialization.
  36206. *
  36207. * @type {string}
  36208. * @readonly
  36209. */
  36210. this.type = 'StereoCamera';
  36211. /**
  36212. * The aspect.
  36213. *
  36214. * @type {number}
  36215. * @default 1
  36216. */
  36217. this.aspect = 1;
  36218. /**
  36219. * The eye separation which represents the distance
  36220. * between the left and right camera.
  36221. *
  36222. * @type {number}
  36223. * @default 0.064
  36224. */
  36225. this.eyeSep = 0.064;
  36226. /**
  36227. * The camera representing the left eye. This is added to layer `1` so objects to be
  36228. * rendered by the left camera must also be added to this layer.
  36229. *
  36230. * @type {PerspectiveCamera}
  36231. */
  36232. this.cameraL = new PerspectiveCamera();
  36233. this.cameraL.layers.enable( 1 );
  36234. this.cameraL.matrixAutoUpdate = false;
  36235. /**
  36236. * The camera representing the right eye. This is added to layer `2` so objects to be
  36237. * rendered by the right camera must also be added to this layer.
  36238. *
  36239. * @type {PerspectiveCamera}
  36240. */
  36241. this.cameraR = new PerspectiveCamera();
  36242. this.cameraR.layers.enable( 2 );
  36243. this.cameraR.matrixAutoUpdate = false;
  36244. this._cache = {
  36245. focus: null,
  36246. fov: null,
  36247. aspect: null,
  36248. near: null,
  36249. far: null,
  36250. zoom: null,
  36251. eyeSep: null
  36252. };
  36253. }
  36254. /**
  36255. * Updates the stereo camera based on the given perspective camera.
  36256. *
  36257. * @param {PerspectiveCamera} camera - The perspective camera.
  36258. */
  36259. update( camera ) {
  36260. const cache = this._cache;
  36261. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36262. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36263. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36264. if ( needsUpdate ) {
  36265. cache.focus = camera.focus;
  36266. cache.fov = camera.fov;
  36267. cache.aspect = camera.aspect * this.aspect;
  36268. cache.near = camera.near;
  36269. cache.far = camera.far;
  36270. cache.zoom = camera.zoom;
  36271. cache.eyeSep = this.eyeSep;
  36272. // Off-axis stereoscopic effect based on
  36273. // http://paulbourke.net/stereographics/stereorender/
  36274. _projectionMatrix.copy( camera.projectionMatrix );
  36275. const eyeSepHalf = cache.eyeSep / 2;
  36276. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36277. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36278. let xmin, xmax;
  36279. // translate xOffset
  36280. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36281. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36282. // for left eye
  36283. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36284. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36285. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36286. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36287. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36288. // for right eye
  36289. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36290. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36291. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36292. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36293. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36294. }
  36295. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36296. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36297. }
  36298. }
  36299. /**
  36300. * This type of camera can be used in order to efficiently render a scene with a
  36301. * predefined set of cameras. This is an important performance aspect for
  36302. * rendering VR scenes.
  36303. *
  36304. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36305. * to define for each sub camera the `viewport` property which determines the
  36306. * part of the viewport that is rendered with this camera.
  36307. *
  36308. * @augments PerspectiveCamera
  36309. */
  36310. class ArrayCamera extends PerspectiveCamera {
  36311. /**
  36312. * Constructs a new array camera.
  36313. *
  36314. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36315. */
  36316. constructor( array = [] ) {
  36317. super();
  36318. /**
  36319. * This flag can be used for type testing.
  36320. *
  36321. * @type {boolean}
  36322. * @readonly
  36323. * @default true
  36324. */
  36325. this.isArrayCamera = true;
  36326. /**
  36327. * Whether this camera is used with multiview rendering or not.
  36328. *
  36329. * @type {boolean}
  36330. * @readonly
  36331. * @default false
  36332. */
  36333. this.isMultiViewCamera = false;
  36334. /**
  36335. * An array of perspective sub cameras.
  36336. *
  36337. * @type {Array<PerspectiveCamera>}
  36338. */
  36339. this.cameras = array;
  36340. }
  36341. }
  36342. /**
  36343. * Class for keeping track of time.
  36344. */
  36345. class Clock {
  36346. /**
  36347. * Constructs a new clock.
  36348. *
  36349. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36350. * `getDelta()` is called for the first time.
  36351. */
  36352. constructor( autoStart = true ) {
  36353. /**
  36354. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36355. * for the first time.
  36356. *
  36357. * @type {boolean}
  36358. * @default true
  36359. */
  36360. this.autoStart = autoStart;
  36361. /**
  36362. * Holds the time at which the clock's `start()` method was last called.
  36363. *
  36364. * @type {number}
  36365. * @default 0
  36366. */
  36367. this.startTime = 0;
  36368. /**
  36369. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36370. * `getDelta()` methods were last called.
  36371. *
  36372. * @type {number}
  36373. * @default 0
  36374. */
  36375. this.oldTime = 0;
  36376. /**
  36377. * Keeps track of the total time that the clock has been running.
  36378. *
  36379. * @type {number}
  36380. * @default 0
  36381. */
  36382. this.elapsedTime = 0;
  36383. /**
  36384. * Whether the clock is running or not.
  36385. *
  36386. * @type {boolean}
  36387. * @default true
  36388. */
  36389. this.running = false;
  36390. }
  36391. /**
  36392. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36393. * called by the class.
  36394. */
  36395. start() {
  36396. this.startTime = performance.now();
  36397. this.oldTime = this.startTime;
  36398. this.elapsedTime = 0;
  36399. this.running = true;
  36400. }
  36401. /**
  36402. * Stops the clock.
  36403. */
  36404. stop() {
  36405. this.getElapsedTime();
  36406. this.running = false;
  36407. this.autoStart = false;
  36408. }
  36409. /**
  36410. * Returns the elapsed time in seconds.
  36411. *
  36412. * @return {number} The elapsed time.
  36413. */
  36414. getElapsedTime() {
  36415. this.getDelta();
  36416. return this.elapsedTime;
  36417. }
  36418. /**
  36419. * Returns the delta time in seconds.
  36420. *
  36421. * @return {number} The delta time.
  36422. */
  36423. getDelta() {
  36424. let diff = 0;
  36425. if ( this.autoStart && ! this.running ) {
  36426. this.start();
  36427. return 0;
  36428. }
  36429. if ( this.running ) {
  36430. const newTime = performance.now();
  36431. diff = ( newTime - this.oldTime ) / 1000;
  36432. this.oldTime = newTime;
  36433. this.elapsedTime += diff;
  36434. }
  36435. return diff;
  36436. }
  36437. }
  36438. const _position$1 = /*@__PURE__*/ new Vector3();
  36439. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36440. const _scale$1 = /*@__PURE__*/ new Vector3();
  36441. const _forward = /*@__PURE__*/ new Vector3();
  36442. const _up = /*@__PURE__*/ new Vector3();
  36443. /**
  36444. * The class represents a virtual listener of the all positional and non-positional audio effects
  36445. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36446. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36447. *
  36448. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36449. * camera represents the 3D transformation of the listener.
  36450. *
  36451. * @augments Object3D
  36452. */
  36453. class AudioListener extends Object3D {
  36454. /**
  36455. * Constructs a new audio listener.
  36456. */
  36457. constructor() {
  36458. super();
  36459. this.type = 'AudioListener';
  36460. /**
  36461. * The native audio context.
  36462. *
  36463. * @type {AudioContext}
  36464. * @readonly
  36465. */
  36466. this.context = AudioContext.getContext();
  36467. /**
  36468. * The gain node used for volume control.
  36469. *
  36470. * @type {GainNode}
  36471. * @readonly
  36472. */
  36473. this.gain = this.context.createGain();
  36474. this.gain.connect( this.context.destination );
  36475. /**
  36476. * An optional filter.
  36477. *
  36478. * Defined via {@link AudioListener#setFilter}.
  36479. *
  36480. * @type {?AudioNode}
  36481. * @default null
  36482. * @readonly
  36483. */
  36484. this.filter = null;
  36485. /**
  36486. * Time delta values required for `linearRampToValueAtTime()` usage.
  36487. *
  36488. * @type {number}
  36489. * @default 0
  36490. * @readonly
  36491. */
  36492. this.timeDelta = 0;
  36493. // private
  36494. this._clock = new Clock();
  36495. }
  36496. /**
  36497. * Returns the listener's input node.
  36498. *
  36499. * This method is used by other audio nodes to connect to this listener.
  36500. *
  36501. * @return {GainNode} The input node.
  36502. */
  36503. getInput() {
  36504. return this.gain;
  36505. }
  36506. /**
  36507. * Removes the current filter from this listener.
  36508. *
  36509. * @return {AudioListener} A reference to this listener.
  36510. */
  36511. removeFilter() {
  36512. if ( this.filter !== null ) {
  36513. this.gain.disconnect( this.filter );
  36514. this.filter.disconnect( this.context.destination );
  36515. this.gain.connect( this.context.destination );
  36516. this.filter = null;
  36517. }
  36518. return this;
  36519. }
  36520. /**
  36521. * Returns the current set filter.
  36522. *
  36523. * @return {?AudioNode} The filter.
  36524. */
  36525. getFilter() {
  36526. return this.filter;
  36527. }
  36528. /**
  36529. * Sets the given filter to this listener.
  36530. *
  36531. * @param {AudioNode} value - The filter to set.
  36532. * @return {AudioListener} A reference to this listener.
  36533. */
  36534. setFilter( value ) {
  36535. if ( this.filter !== null ) {
  36536. this.gain.disconnect( this.filter );
  36537. this.filter.disconnect( this.context.destination );
  36538. } else {
  36539. this.gain.disconnect( this.context.destination );
  36540. }
  36541. this.filter = value;
  36542. this.gain.connect( this.filter );
  36543. this.filter.connect( this.context.destination );
  36544. return this;
  36545. }
  36546. /**
  36547. * Returns the applications master volume.
  36548. *
  36549. * @return {number} The master volume.
  36550. */
  36551. getMasterVolume() {
  36552. return this.gain.gain.value;
  36553. }
  36554. /**
  36555. * Sets the applications master volume. This volume setting affects
  36556. * all audio nodes in the scene.
  36557. *
  36558. * @param {number} value - The master volume to set.
  36559. * @return {AudioListener} A reference to this listener.
  36560. */
  36561. setMasterVolume( value ) {
  36562. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36563. return this;
  36564. }
  36565. updateMatrixWorld( force ) {
  36566. super.updateMatrixWorld( force );
  36567. const listener = this.context.listener;
  36568. this.timeDelta = this._clock.getDelta();
  36569. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36570. // the initial forward and up directions must be orthogonal
  36571. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36572. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36573. if ( listener.positionX ) {
  36574. // code path for Chrome (see #14393)
  36575. const endTime = this.context.currentTime + this.timeDelta;
  36576. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36577. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36578. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36579. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36580. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36581. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36582. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36583. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36584. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36585. } else {
  36586. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36587. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36588. }
  36589. }
  36590. }
  36591. /**
  36592. * Represents a non-positional ( global ) audio object.
  36593. *
  36594. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36595. *
  36596. * ```js
  36597. * // create an AudioListener and add it to the camera
  36598. * const listener = new THREE.AudioListener();
  36599. * camera.add( listener );
  36600. *
  36601. * // create a global audio source
  36602. * const sound = new THREE.Audio( listener );
  36603. *
  36604. * // load a sound and set it as the Audio object's buffer
  36605. * const audioLoader = new THREE.AudioLoader();
  36606. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36607. * sound.setBuffer( buffer );
  36608. * sound.setLoop( true );
  36609. * sound.setVolume( 0.5 );
  36610. * sound.play();
  36611. * });
  36612. * ```
  36613. *
  36614. * @augments Object3D
  36615. */
  36616. class Audio extends Object3D {
  36617. /**
  36618. * Constructs a new audio.
  36619. *
  36620. * @param {AudioListener} listener - The global audio listener.
  36621. */
  36622. constructor( listener ) {
  36623. super();
  36624. this.type = 'Audio';
  36625. /**
  36626. * The global audio listener.
  36627. *
  36628. * @type {AudioListener}
  36629. * @readonly
  36630. */
  36631. this.listener = listener;
  36632. /**
  36633. * The audio context.
  36634. *
  36635. * @type {AudioContext}
  36636. * @readonly
  36637. */
  36638. this.context = listener.context;
  36639. /**
  36640. * The gain node used for volume control.
  36641. *
  36642. * @type {GainNode}
  36643. * @readonly
  36644. */
  36645. this.gain = this.context.createGain();
  36646. this.gain.connect( listener.getInput() );
  36647. /**
  36648. * Whether to start playback automatically or not.
  36649. *
  36650. * @type {boolean}
  36651. * @default false
  36652. */
  36653. this.autoplay = false;
  36654. /**
  36655. * A reference to an audio buffer.
  36656. *
  36657. * Defined via {@link Audio#setBuffer}.
  36658. *
  36659. * @type {?AudioBuffer}
  36660. * @default null
  36661. * @readonly
  36662. */
  36663. this.buffer = null;
  36664. /**
  36665. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36666. * +/- 1200 is an octave.
  36667. *
  36668. * Defined via {@link Audio#setDetune}.
  36669. *
  36670. * @type {number}
  36671. * @default 0
  36672. * @readonly
  36673. */
  36674. this.detune = 0;
  36675. /**
  36676. * Whether the audio should loop or not.
  36677. *
  36678. * Defined via {@link Audio#setLoop}.
  36679. *
  36680. * @type {boolean}
  36681. * @default false
  36682. * @readonly
  36683. */
  36684. this.loop = false;
  36685. /**
  36686. * Defines where in the audio buffer the replay should
  36687. * start, in seconds.
  36688. *
  36689. * @type {number}
  36690. * @default 0
  36691. */
  36692. this.loopStart = 0;
  36693. /**
  36694. * Defines where in the audio buffer the replay should
  36695. * stop, in seconds.
  36696. *
  36697. * @type {number}
  36698. * @default 0
  36699. */
  36700. this.loopEnd = 0;
  36701. /**
  36702. * An offset to the time within the audio buffer the playback
  36703. * should begin, in seconds.
  36704. *
  36705. * @type {number}
  36706. * @default 0
  36707. */
  36708. this.offset = 0;
  36709. /**
  36710. * Overrides the default duration of the audio.
  36711. *
  36712. * @type {undefined|number}
  36713. * @default undefined
  36714. */
  36715. this.duration = undefined;
  36716. /**
  36717. * The playback speed.
  36718. *
  36719. * Defined via {@link Audio#setPlaybackRate}.
  36720. *
  36721. * @type {number}
  36722. * @readonly
  36723. * @default 1
  36724. */
  36725. this.playbackRate = 1;
  36726. /**
  36727. * Indicates whether the audio is playing or not.
  36728. *
  36729. * This flag will be automatically set when using {@link Audio#play},
  36730. * {@link Audio#pause}, {@link Audio#stop}.
  36731. *
  36732. * @type {boolean}
  36733. * @readonly
  36734. * @default false
  36735. */
  36736. this.isPlaying = false;
  36737. /**
  36738. * Indicates whether the audio playback can be controlled
  36739. * with method like {@link Audio#play} or {@link Audio#pause}.
  36740. *
  36741. * This flag will be automatically set when audio sources are
  36742. * defined.
  36743. *
  36744. * @type {boolean}
  36745. * @readonly
  36746. * @default true
  36747. */
  36748. this.hasPlaybackControl = true;
  36749. /**
  36750. * Holds a reference to the current audio source.
  36751. *
  36752. * The property is automatically by one of the `set*()` methods.
  36753. *
  36754. * @type {?AudioNode}
  36755. * @readonly
  36756. * @default null
  36757. */
  36758. this.source = null;
  36759. /**
  36760. * Defines the source type.
  36761. *
  36762. * The property is automatically set by one of the `set*()` methods.
  36763. *
  36764. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36765. * @readonly
  36766. * @default 'empty'
  36767. */
  36768. this.sourceType = 'empty';
  36769. this._startedAt = 0;
  36770. this._progress = 0;
  36771. this._connected = false;
  36772. /**
  36773. * Can be used to apply a variety of low-order filters to create
  36774. * more complex sound effects e.g. via `BiquadFilterNode`.
  36775. *
  36776. * The property is automatically set by {@link Audio#setFilters}.
  36777. *
  36778. * @type {Array<AudioNode>}
  36779. * @readonly
  36780. */
  36781. this.filters = [];
  36782. }
  36783. /**
  36784. * Returns the output audio node.
  36785. *
  36786. * @return {GainNode} The output node.
  36787. */
  36788. getOutput() {
  36789. return this.gain;
  36790. }
  36791. /**
  36792. * Sets the given audio node as the source of this instance.
  36793. *
  36794. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36795. *
  36796. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36797. * @return {Audio} A reference to this instance.
  36798. */
  36799. setNodeSource( audioNode ) {
  36800. this.hasPlaybackControl = false;
  36801. this.sourceType = 'audioNode';
  36802. this.source = audioNode;
  36803. this.connect();
  36804. return this;
  36805. }
  36806. /**
  36807. * Sets the given media element as the source of this instance.
  36808. *
  36809. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36810. *
  36811. * @param {HTMLMediaElement} mediaElement - The media element.
  36812. * @return {Audio} A reference to this instance.
  36813. */
  36814. setMediaElementSource( mediaElement ) {
  36815. this.hasPlaybackControl = false;
  36816. this.sourceType = 'mediaNode';
  36817. this.source = this.context.createMediaElementSource( mediaElement );
  36818. this.connect();
  36819. return this;
  36820. }
  36821. /**
  36822. * Sets the given media stream as the source of this instance.
  36823. *
  36824. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36825. *
  36826. * @param {MediaStream} mediaStream - The media stream.
  36827. * @return {Audio} A reference to this instance.
  36828. */
  36829. setMediaStreamSource( mediaStream ) {
  36830. this.hasPlaybackControl = false;
  36831. this.sourceType = 'mediaStreamNode';
  36832. this.source = this.context.createMediaStreamSource( mediaStream );
  36833. this.connect();
  36834. return this;
  36835. }
  36836. /**
  36837. * Sets the given audio buffer as the source of this instance.
  36838. *
  36839. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36840. *
  36841. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36842. * @return {Audio} A reference to this instance.
  36843. */
  36844. setBuffer( audioBuffer ) {
  36845. this.buffer = audioBuffer;
  36846. this.sourceType = 'buffer';
  36847. if ( this.autoplay ) this.play();
  36848. return this;
  36849. }
  36850. /**
  36851. * Starts the playback of the audio.
  36852. *
  36853. * Can only be used with compatible audio sources that allow playback control.
  36854. *
  36855. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36856. * @return {Audio|undefined} A reference to this instance.
  36857. */
  36858. play( delay = 0 ) {
  36859. if ( this.isPlaying === true ) {
  36860. warn( 'Audio: Audio is already playing.' );
  36861. return;
  36862. }
  36863. if ( this.hasPlaybackControl === false ) {
  36864. warn( 'Audio: this Audio has no playback control.' );
  36865. return;
  36866. }
  36867. this._startedAt = this.context.currentTime + delay;
  36868. const source = this.context.createBufferSource();
  36869. source.buffer = this.buffer;
  36870. source.loop = this.loop;
  36871. source.loopStart = this.loopStart;
  36872. source.loopEnd = this.loopEnd;
  36873. source.onended = this.onEnded.bind( this );
  36874. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36875. this.isPlaying = true;
  36876. this.source = source;
  36877. this.setDetune( this.detune );
  36878. this.setPlaybackRate( this.playbackRate );
  36879. return this.connect();
  36880. }
  36881. /**
  36882. * Pauses the playback of the audio.
  36883. *
  36884. * Can only be used with compatible audio sources that allow playback control.
  36885. *
  36886. * @return {Audio|undefined} A reference to this instance.
  36887. */
  36888. pause() {
  36889. if ( this.hasPlaybackControl === false ) {
  36890. warn( 'Audio: this Audio has no playback control.' );
  36891. return;
  36892. }
  36893. if ( this.isPlaying === true ) {
  36894. // update current progress
  36895. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36896. if ( this.loop === true ) {
  36897. // ensure _progress does not exceed duration with looped audios
  36898. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36899. }
  36900. this.source.stop();
  36901. this.source.onended = null;
  36902. this.isPlaying = false;
  36903. }
  36904. return this;
  36905. }
  36906. /**
  36907. * Stops the playback of the audio.
  36908. *
  36909. * Can only be used with compatible audio sources that allow playback control.
  36910. *
  36911. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36912. * @return {Audio|undefined} A reference to this instance.
  36913. */
  36914. stop( delay = 0 ) {
  36915. if ( this.hasPlaybackControl === false ) {
  36916. warn( 'Audio: this Audio has no playback control.' );
  36917. return;
  36918. }
  36919. this._progress = 0;
  36920. if ( this.source !== null ) {
  36921. this.source.stop( this.context.currentTime + delay );
  36922. this.source.onended = null;
  36923. }
  36924. this.isPlaying = false;
  36925. return this;
  36926. }
  36927. /**
  36928. * Connects to the audio source. This is used internally on
  36929. * initialisation and when setting / removing filters.
  36930. *
  36931. * @return {Audio} A reference to this instance.
  36932. */
  36933. connect() {
  36934. if ( this.filters.length > 0 ) {
  36935. this.source.connect( this.filters[ 0 ] );
  36936. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36937. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36938. }
  36939. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36940. } else {
  36941. this.source.connect( this.getOutput() );
  36942. }
  36943. this._connected = true;
  36944. return this;
  36945. }
  36946. /**
  36947. * Disconnects to the audio source. This is used internally on
  36948. * initialisation and when setting / removing filters.
  36949. *
  36950. * @return {Audio|undefined} A reference to this instance.
  36951. */
  36952. disconnect() {
  36953. if ( this._connected === false ) {
  36954. return;
  36955. }
  36956. if ( this.filters.length > 0 ) {
  36957. this.source.disconnect( this.filters[ 0 ] );
  36958. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36959. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36960. }
  36961. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36962. } else {
  36963. this.source.disconnect( this.getOutput() );
  36964. }
  36965. this._connected = false;
  36966. return this;
  36967. }
  36968. /**
  36969. * Returns the current set filters.
  36970. *
  36971. * @return {Array<AudioNode>} The list of filters.
  36972. */
  36973. getFilters() {
  36974. return this.filters;
  36975. }
  36976. /**
  36977. * Sets an array of filters and connects them with the audio source.
  36978. *
  36979. * @param {Array<AudioNode>} [value] - A list of filters.
  36980. * @return {Audio} A reference to this instance.
  36981. */
  36982. setFilters( value ) {
  36983. if ( ! value ) value = [];
  36984. if ( this._connected === true ) {
  36985. this.disconnect();
  36986. this.filters = value.slice();
  36987. this.connect();
  36988. } else {
  36989. this.filters = value.slice();
  36990. }
  36991. return this;
  36992. }
  36993. /**
  36994. * Defines the detuning of oscillation in cents.
  36995. *
  36996. * @param {number} value - The detuning of oscillation in cents.
  36997. * @return {Audio} A reference to this instance.
  36998. */
  36999. setDetune( value ) {
  37000. this.detune = value;
  37001. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  37002. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  37003. }
  37004. return this;
  37005. }
  37006. /**
  37007. * Returns the detuning of oscillation in cents.
  37008. *
  37009. * @return {number} The detuning of oscillation in cents.
  37010. */
  37011. getDetune() {
  37012. return this.detune;
  37013. }
  37014. /**
  37015. * Returns the first filter in the list of filters.
  37016. *
  37017. * @return {AudioNode|undefined} The first filter in the list of filters.
  37018. */
  37019. getFilter() {
  37020. return this.getFilters()[ 0 ];
  37021. }
  37022. /**
  37023. * Applies a single filter node to the audio.
  37024. *
  37025. * @param {AudioNode} [filter] - The filter to set.
  37026. * @return {Audio} A reference to this instance.
  37027. */
  37028. setFilter( filter ) {
  37029. return this.setFilters( filter ? [ filter ] : [] );
  37030. }
  37031. /**
  37032. * Sets the playback rate.
  37033. *
  37034. * Can only be used with compatible audio sources that allow playback control.
  37035. *
  37036. * @param {number} [value] - The playback rate to set.
  37037. * @return {Audio|undefined} A reference to this instance.
  37038. */
  37039. setPlaybackRate( value ) {
  37040. if ( this.hasPlaybackControl === false ) {
  37041. warn( 'Audio: this Audio has no playback control.' );
  37042. return;
  37043. }
  37044. this.playbackRate = value;
  37045. if ( this.isPlaying === true ) {
  37046. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  37047. }
  37048. return this;
  37049. }
  37050. /**
  37051. * Returns the current playback rate.
  37052. * @return {number} The playback rate.
  37053. */
  37054. getPlaybackRate() {
  37055. return this.playbackRate;
  37056. }
  37057. /**
  37058. * Automatically called when playback finished.
  37059. */
  37060. onEnded() {
  37061. this.isPlaying = false;
  37062. this._progress = 0;
  37063. }
  37064. /**
  37065. * Returns the loop flag.
  37066. *
  37067. * Can only be used with compatible audio sources that allow playback control.
  37068. *
  37069. * @return {boolean} Whether the audio should loop or not.
  37070. */
  37071. getLoop() {
  37072. if ( this.hasPlaybackControl === false ) {
  37073. warn( 'Audio: this Audio has no playback control.' );
  37074. return false;
  37075. }
  37076. return this.loop;
  37077. }
  37078. /**
  37079. * Sets the loop flag.
  37080. *
  37081. * Can only be used with compatible audio sources that allow playback control.
  37082. *
  37083. * @param {boolean} value - Whether the audio should loop or not.
  37084. * @return {Audio|undefined} A reference to this instance.
  37085. */
  37086. setLoop( value ) {
  37087. if ( this.hasPlaybackControl === false ) {
  37088. warn( 'Audio: this Audio has no playback control.' );
  37089. return;
  37090. }
  37091. this.loop = value;
  37092. if ( this.isPlaying === true ) {
  37093. this.source.loop = this.loop;
  37094. }
  37095. return this;
  37096. }
  37097. /**
  37098. * Sets the loop start value which defines where in the audio buffer the replay should
  37099. * start, in seconds.
  37100. *
  37101. * @param {number} value - The loop start value.
  37102. * @return {Audio} A reference to this instance.
  37103. */
  37104. setLoopStart( value ) {
  37105. this.loopStart = value;
  37106. return this;
  37107. }
  37108. /**
  37109. * Sets the loop end value which defines where in the audio buffer the replay should
  37110. * stop, in seconds.
  37111. *
  37112. * @param {number} value - The loop end value.
  37113. * @return {Audio} A reference to this instance.
  37114. */
  37115. setLoopEnd( value ) {
  37116. this.loopEnd = value;
  37117. return this;
  37118. }
  37119. /**
  37120. * Returns the volume.
  37121. *
  37122. * @return {number} The volume.
  37123. */
  37124. getVolume() {
  37125. return this.gain.gain.value;
  37126. }
  37127. /**
  37128. * Sets the volume.
  37129. *
  37130. * @param {number} value - The volume to set.
  37131. * @return {Audio} A reference to this instance.
  37132. */
  37133. setVolume( value ) {
  37134. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  37135. return this;
  37136. }
  37137. copy( source, recursive ) {
  37138. super.copy( source, recursive );
  37139. if ( source.sourceType !== 'buffer' ) {
  37140. warn( 'Audio: Audio source type cannot be copied.' );
  37141. return this;
  37142. }
  37143. this.autoplay = source.autoplay;
  37144. this.buffer = source.buffer;
  37145. this.detune = source.detune;
  37146. this.loop = source.loop;
  37147. this.loopStart = source.loopStart;
  37148. this.loopEnd = source.loopEnd;
  37149. this.offset = source.offset;
  37150. this.duration = source.duration;
  37151. this.playbackRate = source.playbackRate;
  37152. this.hasPlaybackControl = source.hasPlaybackControl;
  37153. this.sourceType = source.sourceType;
  37154. this.filters = source.filters.slice();
  37155. return this;
  37156. }
  37157. clone( recursive ) {
  37158. return new this.constructor( this.listener ).copy( this, recursive );
  37159. }
  37160. }
  37161. const _position = /*@__PURE__*/ new Vector3();
  37162. const _quaternion = /*@__PURE__*/ new Quaternion();
  37163. const _scale = /*@__PURE__*/ new Vector3();
  37164. const _orientation = /*@__PURE__*/ new Vector3();
  37165. /**
  37166. * Represents a positional audio object.
  37167. *
  37168. * ```js
  37169. * // create an AudioListener and add it to the camera
  37170. * const listener = new THREE.AudioListener();
  37171. * camera.add( listener );
  37172. *
  37173. * // create the PositionalAudio object (passing in the listener)
  37174. * const sound = new THREE.PositionalAudio( listener );
  37175. *
  37176. * // load a sound and set it as the PositionalAudio object's buffer
  37177. * const audioLoader = new THREE.AudioLoader();
  37178. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  37179. * sound.setBuffer( buffer );
  37180. * sound.setRefDistance( 20 );
  37181. * sound.play();
  37182. * });
  37183. *
  37184. * // create an object for the sound to play from
  37185. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  37186. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  37187. * const mesh = new THREE.Mesh( sphere, material );
  37188. * scene.add( mesh );
  37189. *
  37190. * // finally add the sound to the mesh
  37191. * mesh.add( sound );
  37192. *
  37193. * @augments Audio
  37194. */
  37195. class PositionalAudio extends Audio {
  37196. /**
  37197. * Constructs a positional audio.
  37198. *
  37199. * @param {AudioListener} listener - The global audio listener.
  37200. */
  37201. constructor( listener ) {
  37202. super( listener );
  37203. /**
  37204. * The panner node represents the location, direction, and behavior of an audio
  37205. * source in 3D space.
  37206. *
  37207. * @type {PannerNode}
  37208. * @readonly
  37209. */
  37210. this.panner = this.context.createPanner();
  37211. this.panner.panningModel = 'HRTF';
  37212. this.panner.connect( this.gain );
  37213. }
  37214. connect() {
  37215. super.connect();
  37216. this.panner.connect( this.gain );
  37217. return this;
  37218. }
  37219. disconnect() {
  37220. super.disconnect();
  37221. this.panner.disconnect( this.gain );
  37222. return this;
  37223. }
  37224. getOutput() {
  37225. return this.panner;
  37226. }
  37227. /**
  37228. * Returns the current reference distance.
  37229. *
  37230. * @return {number} The reference distance.
  37231. */
  37232. getRefDistance() {
  37233. return this.panner.refDistance;
  37234. }
  37235. /**
  37236. * Defines the reference distance for reducing volume as the audio source moves
  37237. * further from the listener – i.e. the distance at which the volume reduction
  37238. * starts taking effect.
  37239. *
  37240. * @param {number} value - The reference distance to set.
  37241. * @return {PositionalAudio} A reference to this instance.
  37242. */
  37243. setRefDistance( value ) {
  37244. this.panner.refDistance = value;
  37245. return this;
  37246. }
  37247. /**
  37248. * Returns the current rolloff factor.
  37249. *
  37250. * @return {number} The rolloff factor.
  37251. */
  37252. getRolloffFactor() {
  37253. return this.panner.rolloffFactor;
  37254. }
  37255. /**
  37256. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37257. *
  37258. * @param {number} value - The rolloff factor.
  37259. * @return {PositionalAudio} A reference to this instance.
  37260. */
  37261. setRolloffFactor( value ) {
  37262. this.panner.rolloffFactor = value;
  37263. return this;
  37264. }
  37265. /**
  37266. * Returns the current distance model.
  37267. *
  37268. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37269. */
  37270. getDistanceModel() {
  37271. return this.panner.distanceModel;
  37272. }
  37273. /**
  37274. * Defines which algorithm to use to reduce the volume of the audio source
  37275. * as it moves away from the listener.
  37276. *
  37277. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37278. * for more details.
  37279. *
  37280. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37281. * @return {PositionalAudio} A reference to this instance.
  37282. */
  37283. setDistanceModel( value ) {
  37284. this.panner.distanceModel = value;
  37285. return this;
  37286. }
  37287. /**
  37288. * Returns the current max distance.
  37289. *
  37290. * @return {number} The max distance.
  37291. */
  37292. getMaxDistance() {
  37293. return this.panner.maxDistance;
  37294. }
  37295. /**
  37296. * Defines the maximum distance between the audio source and the listener,
  37297. * after which the volume is not reduced any further.
  37298. *
  37299. * This value is used only by the `linear` distance model.
  37300. *
  37301. * @param {number} value - The max distance.
  37302. * @return {PositionalAudio} A reference to this instance.
  37303. */
  37304. setMaxDistance( value ) {
  37305. this.panner.maxDistance = value;
  37306. return this;
  37307. }
  37308. /**
  37309. * Sets the directional cone in which the audio can be listened.
  37310. *
  37311. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37312. * @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.
  37313. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37314. * @return {PositionalAudio} A reference to this instance.
  37315. */
  37316. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37317. this.panner.coneInnerAngle = coneInnerAngle;
  37318. this.panner.coneOuterAngle = coneOuterAngle;
  37319. this.panner.coneOuterGain = coneOuterGain;
  37320. return this;
  37321. }
  37322. updateMatrixWorld( force ) {
  37323. super.updateMatrixWorld( force );
  37324. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37325. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37326. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37327. const panner = this.panner;
  37328. if ( panner.positionX ) {
  37329. // code path for Chrome and Firefox (see #14393)
  37330. const endTime = this.context.currentTime + this.listener.timeDelta;
  37331. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37332. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37333. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37334. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37335. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37336. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37337. } else {
  37338. panner.setPosition( _position.x, _position.y, _position.z );
  37339. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37340. }
  37341. }
  37342. }
  37343. /**
  37344. * This class can be used to analyse audio data.
  37345. *
  37346. * ```js
  37347. * // create an AudioListener and add it to the camera
  37348. * const listener = new THREE.AudioListener();
  37349. * camera.add( listener );
  37350. *
  37351. * // create an Audio source
  37352. * const sound = new THREE.Audio( listener );
  37353. *
  37354. * // load a sound and set it as the Audio object's buffer
  37355. * const audioLoader = new THREE.AudioLoader();
  37356. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37357. * sound.setBuffer( buffer );
  37358. * sound.setLoop(true);
  37359. * sound.setVolume(0.5);
  37360. * sound.play();
  37361. * });
  37362. *
  37363. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37364. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37365. *
  37366. * // get the average frequency of the sound
  37367. * const data = analyser.getAverageFrequency();
  37368. * ```
  37369. */
  37370. class AudioAnalyser {
  37371. /**
  37372. * Constructs a new audio analyzer.
  37373. *
  37374. * @param {Audio} audio - The audio to analyze.
  37375. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37376. */
  37377. constructor( audio, fftSize = 2048 ) {
  37378. /**
  37379. * The global audio listener.
  37380. *
  37381. * @type {AnalyserNode}
  37382. */
  37383. this.analyser = audio.context.createAnalyser();
  37384. this.analyser.fftSize = fftSize;
  37385. /**
  37386. * Holds the analyzed data.
  37387. *
  37388. * @type {Uint8Array}
  37389. */
  37390. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37391. audio.getOutput().connect( this.analyser );
  37392. }
  37393. /**
  37394. * Returns an array with frequency data of the audio.
  37395. *
  37396. * Each item in the array represents the decibel value for a specific frequency.
  37397. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37398. * For example, for 48000 sample rate, the last item of the array will represent
  37399. * the decibel value for 24000 Hz.
  37400. *
  37401. * @return {Uint8Array} The frequency data.
  37402. */
  37403. getFrequencyData() {
  37404. this.analyser.getByteFrequencyData( this.data );
  37405. return this.data;
  37406. }
  37407. /**
  37408. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37409. *
  37410. * @return {number} The average frequency.
  37411. */
  37412. getAverageFrequency() {
  37413. let value = 0;
  37414. const data = this.getFrequencyData();
  37415. for ( let i = 0; i < data.length; i ++ ) {
  37416. value += data[ i ];
  37417. }
  37418. return value / data.length;
  37419. }
  37420. }
  37421. /**
  37422. * Buffered scene graph property that allows weighted accumulation; used internally.
  37423. */
  37424. class PropertyMixer {
  37425. /**
  37426. * Constructs a new property mixer.
  37427. *
  37428. * @param {PropertyBinding} binding - The property binding.
  37429. * @param {string} typeName - The keyframe track type name.
  37430. * @param {number} valueSize - The keyframe track value size.
  37431. */
  37432. constructor( binding, typeName, valueSize ) {
  37433. /**
  37434. * The property binding.
  37435. *
  37436. * @type {PropertyBinding}
  37437. */
  37438. this.binding = binding;
  37439. /**
  37440. * The keyframe track value size.
  37441. *
  37442. * @type {number}
  37443. */
  37444. this.valueSize = valueSize;
  37445. let mixFunction,
  37446. mixFunctionAdditive,
  37447. setIdentity;
  37448. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37449. //
  37450. // interpolators can use .buffer as their .result
  37451. // the data then goes to 'incoming'
  37452. //
  37453. // 'accu0' and 'accu1' are used frame-interleaved for
  37454. // the cumulative result and are compared to detect
  37455. // changes
  37456. //
  37457. // 'orig' stores the original state of the property
  37458. //
  37459. // 'add' is used for additive cumulative results
  37460. //
  37461. // 'work' is optional and is only present for quaternion types. It is used
  37462. // to store intermediate quaternion multiplication results
  37463. switch ( typeName ) {
  37464. case 'quaternion':
  37465. mixFunction = this._slerp;
  37466. mixFunctionAdditive = this._slerpAdditive;
  37467. setIdentity = this._setAdditiveIdentityQuaternion;
  37468. this.buffer = new Float64Array( valueSize * 6 );
  37469. this._workIndex = 5;
  37470. break;
  37471. case 'string':
  37472. case 'bool':
  37473. mixFunction = this._select;
  37474. // Use the regular mix function and for additive on these types,
  37475. // additive is not relevant for non-numeric types
  37476. mixFunctionAdditive = this._select;
  37477. setIdentity = this._setAdditiveIdentityOther;
  37478. this.buffer = new Array( valueSize * 5 );
  37479. break;
  37480. default:
  37481. mixFunction = this._lerp;
  37482. mixFunctionAdditive = this._lerpAdditive;
  37483. setIdentity = this._setAdditiveIdentityNumeric;
  37484. this.buffer = new Float64Array( valueSize * 5 );
  37485. }
  37486. this._mixBufferRegion = mixFunction;
  37487. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37488. this._setIdentity = setIdentity;
  37489. this._origIndex = 3;
  37490. this._addIndex = 4;
  37491. /**
  37492. * TODO
  37493. *
  37494. * @type {number}
  37495. * @default 0
  37496. */
  37497. this.cumulativeWeight = 0;
  37498. /**
  37499. * TODO
  37500. *
  37501. * @type {number}
  37502. * @default 0
  37503. */
  37504. this.cumulativeWeightAdditive = 0;
  37505. /**
  37506. * TODO
  37507. *
  37508. * @type {number}
  37509. * @default 0
  37510. */
  37511. this.useCount = 0;
  37512. /**
  37513. * TODO
  37514. *
  37515. * @type {number}
  37516. * @default 0
  37517. */
  37518. this.referenceCount = 0;
  37519. }
  37520. /**
  37521. * Accumulates data in the `incoming` region into `accu<i>`.
  37522. *
  37523. * @param {number} accuIndex - The accumulation index.
  37524. * @param {number} weight - The weight.
  37525. */
  37526. accumulate( accuIndex, weight ) {
  37527. // note: happily accumulating nothing when weight = 0, the caller knows
  37528. // the weight and shouldn't have made the call in the first place
  37529. const buffer = this.buffer,
  37530. stride = this.valueSize,
  37531. offset = accuIndex * stride + stride;
  37532. let currentWeight = this.cumulativeWeight;
  37533. if ( currentWeight === 0 ) {
  37534. // accuN := incoming * weight
  37535. for ( let i = 0; i !== stride; ++ i ) {
  37536. buffer[ offset + i ] = buffer[ i ];
  37537. }
  37538. currentWeight = weight;
  37539. } else {
  37540. // accuN := accuN + incoming * weight
  37541. currentWeight += weight;
  37542. const mix = weight / currentWeight;
  37543. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37544. }
  37545. this.cumulativeWeight = currentWeight;
  37546. }
  37547. /**
  37548. * Accumulates data in the `incoming` region into `add`.
  37549. *
  37550. * @param {number} weight - The weight.
  37551. */
  37552. accumulateAdditive( weight ) {
  37553. const buffer = this.buffer,
  37554. stride = this.valueSize,
  37555. offset = stride * this._addIndex;
  37556. if ( this.cumulativeWeightAdditive === 0 ) {
  37557. // add = identity
  37558. this._setIdentity();
  37559. }
  37560. // add := add + incoming * weight
  37561. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37562. this.cumulativeWeightAdditive += weight;
  37563. }
  37564. /**
  37565. * Applies the state of `accu<i>` to the binding when accus differ.
  37566. *
  37567. * @param {number} accuIndex - The accumulation index.
  37568. */
  37569. apply( accuIndex ) {
  37570. const stride = this.valueSize,
  37571. buffer = this.buffer,
  37572. offset = accuIndex * stride + stride,
  37573. weight = this.cumulativeWeight,
  37574. weightAdditive = this.cumulativeWeightAdditive,
  37575. binding = this.binding;
  37576. this.cumulativeWeight = 0;
  37577. this.cumulativeWeightAdditive = 0;
  37578. if ( weight < 1 ) {
  37579. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37580. const originalValueOffset = stride * this._origIndex;
  37581. this._mixBufferRegion(
  37582. buffer, offset, originalValueOffset, 1 - weight, stride );
  37583. }
  37584. if ( weightAdditive > 0 ) {
  37585. // accuN := accuN + additive accuN
  37586. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37587. }
  37588. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37589. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37590. // value has changed -> update scene graph
  37591. binding.setValue( buffer, offset );
  37592. break;
  37593. }
  37594. }
  37595. }
  37596. /**
  37597. * Remembers the state of the bound property and copy it to both accus.
  37598. */
  37599. saveOriginalState() {
  37600. const binding = this.binding;
  37601. const buffer = this.buffer,
  37602. stride = this.valueSize,
  37603. originalValueOffset = stride * this._origIndex;
  37604. binding.getValue( buffer, originalValueOffset );
  37605. // accu[0..1] := orig -- initially detect changes against the original
  37606. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37607. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37608. }
  37609. // Add to identity for additive
  37610. this._setIdentity();
  37611. this.cumulativeWeight = 0;
  37612. this.cumulativeWeightAdditive = 0;
  37613. }
  37614. /**
  37615. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37616. */
  37617. restoreOriginalState() {
  37618. const originalValueOffset = this.valueSize * 3;
  37619. this.binding.setValue( this.buffer, originalValueOffset );
  37620. }
  37621. // internals
  37622. _setAdditiveIdentityNumeric() {
  37623. const startIndex = this._addIndex * this.valueSize;
  37624. const endIndex = startIndex + this.valueSize;
  37625. for ( let i = startIndex; i < endIndex; i ++ ) {
  37626. this.buffer[ i ] = 0;
  37627. }
  37628. }
  37629. _setAdditiveIdentityQuaternion() {
  37630. this._setAdditiveIdentityNumeric();
  37631. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37632. }
  37633. _setAdditiveIdentityOther() {
  37634. const startIndex = this._origIndex * this.valueSize;
  37635. const targetIndex = this._addIndex * this.valueSize;
  37636. for ( let i = 0; i < this.valueSize; i ++ ) {
  37637. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37638. }
  37639. }
  37640. // mix functions
  37641. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37642. if ( t >= 0.5 ) {
  37643. for ( let i = 0; i !== stride; ++ i ) {
  37644. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37645. }
  37646. }
  37647. }
  37648. _slerp( buffer, dstOffset, srcOffset, t ) {
  37649. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37650. }
  37651. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37652. const workOffset = this._workIndex * stride;
  37653. // Store result in intermediate buffer offset
  37654. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37655. // Slerp to the intermediate result
  37656. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37657. }
  37658. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37659. const s = 1 - t;
  37660. for ( let i = 0; i !== stride; ++ i ) {
  37661. const j = dstOffset + i;
  37662. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37663. }
  37664. }
  37665. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37666. for ( let i = 0; i !== stride; ++ i ) {
  37667. const j = dstOffset + i;
  37668. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37669. }
  37670. }
  37671. }
  37672. // Characters [].:/ are reserved for track binding syntax.
  37673. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37674. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37675. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37676. // only latin characters, and the unicode \p{L} is not yet supported. So
  37677. // instead, we exclude reserved characters and match everything else.
  37678. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37679. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37680. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37681. // be matched to parse the rest of the track name.
  37682. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37683. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37684. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37685. // Object on target node, and accessor. May not contain reserved
  37686. // characters. Accessor may contain any character except closing bracket.
  37687. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37688. // Property and accessor. May not contain reserved characters. Accessor may
  37689. // contain any non-bracket characters.
  37690. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37691. const _trackRe = new RegExp( ''
  37692. + '^'
  37693. + _directoryRe
  37694. + _nodeRe
  37695. + _objectRe
  37696. + _propertyRe
  37697. + '$'
  37698. );
  37699. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37700. class Composite {
  37701. constructor( targetGroup, path, optionalParsedPath ) {
  37702. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37703. this._targetGroup = targetGroup;
  37704. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37705. }
  37706. getValue( array, offset ) {
  37707. this.bind(); // bind all binding
  37708. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37709. binding = this._bindings[ firstValidIndex ];
  37710. // and only call .getValue on the first
  37711. if ( binding !== undefined ) binding.getValue( array, offset );
  37712. }
  37713. setValue( array, offset ) {
  37714. const bindings = this._bindings;
  37715. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37716. bindings[ i ].setValue( array, offset );
  37717. }
  37718. }
  37719. bind() {
  37720. const bindings = this._bindings;
  37721. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37722. bindings[ i ].bind();
  37723. }
  37724. }
  37725. unbind() {
  37726. const bindings = this._bindings;
  37727. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37728. bindings[ i ].unbind();
  37729. }
  37730. }
  37731. }
  37732. // Note: This class uses a State pattern on a per-method basis:
  37733. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37734. // prototype version of these methods with one that represents
  37735. // the bound state. When the property is not found, the methods
  37736. // become no-ops.
  37737. /**
  37738. * This holds a reference to a real property in the scene graph; used internally.
  37739. */
  37740. class PropertyBinding {
  37741. /**
  37742. * Constructs a new property binding.
  37743. *
  37744. * @param {Object} rootNode - The root node.
  37745. * @param {string} path - The path.
  37746. * @param {?Object} [parsedPath] - The parsed path.
  37747. */
  37748. constructor( rootNode, path, parsedPath ) {
  37749. /**
  37750. * The object path to the animated property.
  37751. *
  37752. * @type {string}
  37753. */
  37754. this.path = path;
  37755. /**
  37756. * An object holding information about the path.
  37757. *
  37758. * @type {Object}
  37759. */
  37760. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37761. /**
  37762. * The object owns the animated property.
  37763. *
  37764. * @type {?Object}
  37765. */
  37766. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37767. /**
  37768. * The root node.
  37769. *
  37770. * @type {Object3D|Skeleton}
  37771. */
  37772. this.rootNode = rootNode;
  37773. // initial state of these methods that calls 'bind'
  37774. this.getValue = this._getValue_unbound;
  37775. this.setValue = this._setValue_unbound;
  37776. }
  37777. /**
  37778. * Factory method for creating a property binding from the given parameters.
  37779. *
  37780. * @static
  37781. * @param {Object} root - The root node.
  37782. * @param {string} path - The path.
  37783. * @param {?Object} [parsedPath] - The parsed path.
  37784. * @return {PropertyBinding|Composite} The created property binding or composite.
  37785. */
  37786. static create( root, path, parsedPath ) {
  37787. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37788. return new PropertyBinding( root, path, parsedPath );
  37789. } else {
  37790. return new PropertyBinding.Composite( root, path, parsedPath );
  37791. }
  37792. }
  37793. /**
  37794. * Replaces spaces with underscores and removes unsupported characters from
  37795. * node names, to ensure compatibility with parseTrackName().
  37796. *
  37797. * @param {string} name - Node name to be sanitized.
  37798. * @return {string} The sanitized node name.
  37799. */
  37800. static sanitizeNodeName( name ) {
  37801. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37802. }
  37803. /**
  37804. * Parses the given track name (an object path to an animated property) and
  37805. * returns an object with information about the path. Matches strings in the following forms:
  37806. *
  37807. * - nodeName.property
  37808. * - nodeName.property[accessor]
  37809. * - nodeName.material.property[accessor]
  37810. * - uuid.property[accessor]
  37811. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37812. * - parentName/nodeName.property
  37813. * - parentName/parentName/nodeName.property[index]
  37814. * - .bone[Armature.DEF_cog].position
  37815. * - scene:helium_balloon_model:helium_balloon_model.position
  37816. *
  37817. * @static
  37818. * @param {string} trackName - The track name to parse.
  37819. * @return {Object} The parsed track name as an object.
  37820. */
  37821. static parseTrackName( trackName ) {
  37822. const matches = _trackRe.exec( trackName );
  37823. if ( matches === null ) {
  37824. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37825. }
  37826. const results = {
  37827. // directoryName: matches[ 1 ], // (tschw) currently unused
  37828. nodeName: matches[ 2 ],
  37829. objectName: matches[ 3 ],
  37830. objectIndex: matches[ 4 ],
  37831. propertyName: matches[ 5 ], // required
  37832. propertyIndex: matches[ 6 ]
  37833. };
  37834. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37835. if ( lastDot !== undefined && lastDot !== -1 ) {
  37836. const objectName = results.nodeName.substring( lastDot + 1 );
  37837. // Object names must be checked against an allowlist. Otherwise, there
  37838. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37839. // 'bar' could be the objectName, or part of a nodeName (which can
  37840. // include '.' characters).
  37841. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37842. results.nodeName = results.nodeName.substring( 0, lastDot );
  37843. results.objectName = objectName;
  37844. }
  37845. }
  37846. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37847. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37848. }
  37849. return results;
  37850. }
  37851. /**
  37852. * Searches for a node in the hierarchy of the given root object by the given
  37853. * node name.
  37854. *
  37855. * @static
  37856. * @param {Object} root - The root object.
  37857. * @param {string|number} nodeName - The name of the node.
  37858. * @return {?Object} The found node. Returns `null` if no object was found.
  37859. */
  37860. static findNode( root, nodeName ) {
  37861. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37862. return root;
  37863. }
  37864. // search into skeleton bones.
  37865. if ( root.skeleton ) {
  37866. const bone = root.skeleton.getBoneByName( nodeName );
  37867. if ( bone !== undefined ) {
  37868. return bone;
  37869. }
  37870. }
  37871. // search into node subtree.
  37872. if ( root.children ) {
  37873. const searchNodeSubtree = function ( children ) {
  37874. for ( let i = 0; i < children.length; i ++ ) {
  37875. const childNode = children[ i ];
  37876. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37877. return childNode;
  37878. }
  37879. const result = searchNodeSubtree( childNode.children );
  37880. if ( result ) return result;
  37881. }
  37882. return null;
  37883. };
  37884. const subTreeNode = searchNodeSubtree( root.children );
  37885. if ( subTreeNode ) {
  37886. return subTreeNode;
  37887. }
  37888. }
  37889. return null;
  37890. }
  37891. // these are used to "bind" a nonexistent property
  37892. _getValue_unavailable() {}
  37893. _setValue_unavailable() {}
  37894. // Getters
  37895. _getValue_direct( buffer, offset ) {
  37896. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37897. }
  37898. _getValue_array( buffer, offset ) {
  37899. const source = this.resolvedProperty;
  37900. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37901. buffer[ offset ++ ] = source[ i ];
  37902. }
  37903. }
  37904. _getValue_arrayElement( buffer, offset ) {
  37905. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37906. }
  37907. _getValue_toArray( buffer, offset ) {
  37908. this.resolvedProperty.toArray( buffer, offset );
  37909. }
  37910. // Direct
  37911. _setValue_direct( buffer, offset ) {
  37912. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37913. }
  37914. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37915. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37916. this.targetObject.needsUpdate = true;
  37917. }
  37918. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37919. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37920. this.targetObject.matrixWorldNeedsUpdate = true;
  37921. }
  37922. // EntireArray
  37923. _setValue_array( buffer, offset ) {
  37924. const dest = this.resolvedProperty;
  37925. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37926. dest[ i ] = buffer[ offset ++ ];
  37927. }
  37928. }
  37929. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37930. const dest = this.resolvedProperty;
  37931. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37932. dest[ i ] = buffer[ offset ++ ];
  37933. }
  37934. this.targetObject.needsUpdate = true;
  37935. }
  37936. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37937. const dest = this.resolvedProperty;
  37938. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37939. dest[ i ] = buffer[ offset ++ ];
  37940. }
  37941. this.targetObject.matrixWorldNeedsUpdate = true;
  37942. }
  37943. // ArrayElement
  37944. _setValue_arrayElement( buffer, offset ) {
  37945. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37946. }
  37947. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37948. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37949. this.targetObject.needsUpdate = true;
  37950. }
  37951. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37952. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37953. this.targetObject.matrixWorldNeedsUpdate = true;
  37954. }
  37955. // HasToFromArray
  37956. _setValue_fromArray( buffer, offset ) {
  37957. this.resolvedProperty.fromArray( buffer, offset );
  37958. }
  37959. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37960. this.resolvedProperty.fromArray( buffer, offset );
  37961. this.targetObject.needsUpdate = true;
  37962. }
  37963. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37964. this.resolvedProperty.fromArray( buffer, offset );
  37965. this.targetObject.matrixWorldNeedsUpdate = true;
  37966. }
  37967. _getValue_unbound( targetArray, offset ) {
  37968. this.bind();
  37969. this.getValue( targetArray, offset );
  37970. }
  37971. _setValue_unbound( sourceArray, offset ) {
  37972. this.bind();
  37973. this.setValue( sourceArray, offset );
  37974. }
  37975. /**
  37976. * Creates a getter / setter pair for the property tracked by this binding.
  37977. */
  37978. bind() {
  37979. let targetObject = this.node;
  37980. const parsedPath = this.parsedPath;
  37981. const objectName = parsedPath.objectName;
  37982. const propertyName = parsedPath.propertyName;
  37983. let propertyIndex = parsedPath.propertyIndex;
  37984. if ( ! targetObject ) {
  37985. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37986. this.node = targetObject;
  37987. }
  37988. // set fail state so we can just 'return' on error
  37989. this.getValue = this._getValue_unavailable;
  37990. this.setValue = this._setValue_unavailable;
  37991. // ensure there is a value node
  37992. if ( ! targetObject ) {
  37993. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37994. return;
  37995. }
  37996. if ( objectName ) {
  37997. let objectIndex = parsedPath.objectIndex;
  37998. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37999. switch ( objectName ) {
  38000. case 'materials':
  38001. if ( ! targetObject.material ) {
  38002. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38003. return;
  38004. }
  38005. if ( ! targetObject.material.materials ) {
  38006. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  38007. return;
  38008. }
  38009. targetObject = targetObject.material.materials;
  38010. break;
  38011. case 'bones':
  38012. if ( ! targetObject.skeleton ) {
  38013. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  38014. return;
  38015. }
  38016. // potential future optimization: skip this if propertyIndex is already an integer
  38017. // and convert the integer string to a true integer.
  38018. targetObject = targetObject.skeleton.bones;
  38019. // support resolving morphTarget names into indices.
  38020. for ( let i = 0; i < targetObject.length; i ++ ) {
  38021. if ( targetObject[ i ].name === objectIndex ) {
  38022. objectIndex = i;
  38023. break;
  38024. }
  38025. }
  38026. break;
  38027. case 'map':
  38028. if ( 'map' in targetObject ) {
  38029. targetObject = targetObject.map;
  38030. break;
  38031. }
  38032. if ( ! targetObject.material ) {
  38033. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  38034. return;
  38035. }
  38036. if ( ! targetObject.material.map ) {
  38037. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  38038. return;
  38039. }
  38040. targetObject = targetObject.material.map;
  38041. break;
  38042. default:
  38043. if ( targetObject[ objectName ] === undefined ) {
  38044. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  38045. return;
  38046. }
  38047. targetObject = targetObject[ objectName ];
  38048. }
  38049. if ( objectIndex !== undefined ) {
  38050. if ( targetObject[ objectIndex ] === undefined ) {
  38051. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  38052. return;
  38053. }
  38054. targetObject = targetObject[ objectIndex ];
  38055. }
  38056. }
  38057. // resolve property
  38058. const nodeProperty = targetObject[ propertyName ];
  38059. if ( nodeProperty === undefined ) {
  38060. const nodeName = parsedPath.nodeName;
  38061. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  38062. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  38063. return;
  38064. }
  38065. // determine versioning scheme
  38066. let versioning = this.Versioning.None;
  38067. this.targetObject = targetObject;
  38068. if ( targetObject.isMaterial === true ) {
  38069. versioning = this.Versioning.NeedsUpdate;
  38070. } else if ( targetObject.isObject3D === true ) {
  38071. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  38072. }
  38073. // determine how the property gets bound
  38074. let bindingType = this.BindingType.Direct;
  38075. if ( propertyIndex !== undefined ) {
  38076. // access a sub element of the property array (only primitives are supported right now)
  38077. if ( propertyName === 'morphTargetInfluences' ) {
  38078. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  38079. // support resolving morphTarget names into indices.
  38080. if ( ! targetObject.geometry ) {
  38081. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  38082. return;
  38083. }
  38084. if ( ! targetObject.geometry.morphAttributes ) {
  38085. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  38086. return;
  38087. }
  38088. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  38089. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  38090. }
  38091. }
  38092. bindingType = this.BindingType.ArrayElement;
  38093. this.resolvedProperty = nodeProperty;
  38094. this.propertyIndex = propertyIndex;
  38095. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  38096. // must use copy for Object3D.Euler/Quaternion
  38097. bindingType = this.BindingType.HasFromToArray;
  38098. this.resolvedProperty = nodeProperty;
  38099. } else if ( Array.isArray( nodeProperty ) ) {
  38100. bindingType = this.BindingType.EntireArray;
  38101. this.resolvedProperty = nodeProperty;
  38102. } else {
  38103. this.propertyName = propertyName;
  38104. }
  38105. // select getter / setter
  38106. this.getValue = this.GetterByBindingType[ bindingType ];
  38107. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  38108. }
  38109. /**
  38110. * Unbinds the property.
  38111. */
  38112. unbind() {
  38113. this.node = null;
  38114. // back to the prototype version of getValue / setValue
  38115. // note: avoiding to mutate the shape of 'this' via 'delete'
  38116. this.getValue = this._getValue_unbound;
  38117. this.setValue = this._setValue_unbound;
  38118. }
  38119. }
  38120. PropertyBinding.Composite = Composite;
  38121. PropertyBinding.prototype.BindingType = {
  38122. Direct: 0,
  38123. EntireArray: 1,
  38124. ArrayElement: 2,
  38125. HasFromToArray: 3
  38126. };
  38127. PropertyBinding.prototype.Versioning = {
  38128. None: 0,
  38129. NeedsUpdate: 1,
  38130. MatrixWorldNeedsUpdate: 2
  38131. };
  38132. PropertyBinding.prototype.GetterByBindingType = [
  38133. PropertyBinding.prototype._getValue_direct,
  38134. PropertyBinding.prototype._getValue_array,
  38135. PropertyBinding.prototype._getValue_arrayElement,
  38136. PropertyBinding.prototype._getValue_toArray,
  38137. ];
  38138. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  38139. [
  38140. // Direct
  38141. PropertyBinding.prototype._setValue_direct,
  38142. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  38143. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  38144. ], [
  38145. // EntireArray
  38146. PropertyBinding.prototype._setValue_array,
  38147. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  38148. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  38149. ], [
  38150. // ArrayElement
  38151. PropertyBinding.prototype._setValue_arrayElement,
  38152. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  38153. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  38154. ], [
  38155. // HasToFromArray
  38156. PropertyBinding.prototype._setValue_fromArray,
  38157. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  38158. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  38159. ]
  38160. ];
  38161. /**
  38162. * A group of objects that receives a shared animation state.
  38163. *
  38164. * Usage:
  38165. *
  38166. * - Add objects you would otherwise pass as 'root' to the
  38167. * constructor or the .clipAction method of AnimationMixer.
  38168. * - Instead pass this object as 'root'.
  38169. * - You can also add and remove objects later when the mixer is running.
  38170. *
  38171. * Note:
  38172. *
  38173. * - Objects of this class appear as one object to the mixer,
  38174. * so cache control of the individual objects must be done on the group.
  38175. *
  38176. * Limitation:
  38177. *
  38178. * - The animated properties must be compatible among the all objects in the group.
  38179. * - A single property can either be controlled through a target group or directly, but not both.
  38180. */
  38181. class AnimationObjectGroup {
  38182. /**
  38183. * Constructs a new animation group.
  38184. *
  38185. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  38186. */
  38187. constructor() {
  38188. /**
  38189. * This flag can be used for type testing.
  38190. *
  38191. * @type {boolean}
  38192. * @readonly
  38193. * @default true
  38194. */
  38195. this.isAnimationObjectGroup = true;
  38196. /**
  38197. * The UUID of the 3D object.
  38198. *
  38199. * @type {string}
  38200. * @readonly
  38201. */
  38202. this.uuid = generateUUID();
  38203. // cached objects followed by the active ones
  38204. this._objects = Array.prototype.slice.call( arguments );
  38205. this.nCachedObjects_ = 0; // threshold
  38206. // note: read by PropertyBinding.Composite
  38207. const indices = {};
  38208. this._indicesByUUID = indices; // for bookkeeping
  38209. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38210. indices[ arguments[ i ].uuid ] = i;
  38211. }
  38212. this._paths = []; // inside: string
  38213. this._parsedPaths = []; // inside: { we don't care, here }
  38214. this._bindings = []; // inside: Array< PropertyBinding >
  38215. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38216. const scope = this;
  38217. this.stats = {
  38218. objects: {
  38219. get total() {
  38220. return scope._objects.length;
  38221. },
  38222. get inUse() {
  38223. return this.total - scope.nCachedObjects_;
  38224. }
  38225. },
  38226. get bindingsPerObject() {
  38227. return scope._bindings.length;
  38228. }
  38229. };
  38230. }
  38231. /**
  38232. * Adds an arbitrary number of objects to this animation group.
  38233. *
  38234. * @param {...Object3D} arguments - The 3D objects to add.
  38235. */
  38236. add() {
  38237. const objects = this._objects,
  38238. indicesByUUID = this._indicesByUUID,
  38239. paths = this._paths,
  38240. parsedPaths = this._parsedPaths,
  38241. bindings = this._bindings,
  38242. nBindings = bindings.length;
  38243. let knownObject = undefined,
  38244. nObjects = objects.length,
  38245. nCachedObjects = this.nCachedObjects_;
  38246. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38247. const object = arguments[ i ],
  38248. uuid = object.uuid;
  38249. let index = indicesByUUID[ uuid ];
  38250. if ( index === undefined ) {
  38251. // unknown object -> add it to the ACTIVE region
  38252. index = nObjects ++;
  38253. indicesByUUID[ uuid ] = index;
  38254. objects.push( object );
  38255. // accounting is done, now do the same for all bindings
  38256. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38257. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38258. }
  38259. } else if ( index < nCachedObjects ) {
  38260. knownObject = objects[ index ];
  38261. // move existing object to the ACTIVE region
  38262. const firstActiveIndex = -- nCachedObjects,
  38263. lastCachedObject = objects[ firstActiveIndex ];
  38264. indicesByUUID[ lastCachedObject.uuid ] = index;
  38265. objects[ index ] = lastCachedObject;
  38266. indicesByUUID[ uuid ] = firstActiveIndex;
  38267. objects[ firstActiveIndex ] = object;
  38268. // accounting is done, now do the same for all bindings
  38269. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38270. const bindingsForPath = bindings[ j ],
  38271. lastCached = bindingsForPath[ firstActiveIndex ];
  38272. let binding = bindingsForPath[ index ];
  38273. bindingsForPath[ index ] = lastCached;
  38274. if ( binding === undefined ) {
  38275. // since we do not bother to create new bindings
  38276. // for objects that are cached, the binding may
  38277. // or may not exist
  38278. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38279. }
  38280. bindingsForPath[ firstActiveIndex ] = binding;
  38281. }
  38282. } else if ( objects[ index ] !== knownObject ) {
  38283. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38284. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38285. } // else the object is already where we want it to be
  38286. } // for arguments
  38287. this.nCachedObjects_ = nCachedObjects;
  38288. }
  38289. /**
  38290. * Removes an arbitrary number of objects to this animation group
  38291. *
  38292. * @param {...Object3D} arguments - The 3D objects to remove.
  38293. */
  38294. remove() {
  38295. const objects = this._objects,
  38296. indicesByUUID = this._indicesByUUID,
  38297. bindings = this._bindings,
  38298. nBindings = bindings.length;
  38299. let nCachedObjects = this.nCachedObjects_;
  38300. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38301. const object = arguments[ i ],
  38302. uuid = object.uuid,
  38303. index = indicesByUUID[ uuid ];
  38304. if ( index !== undefined && index >= nCachedObjects ) {
  38305. // move existing object into the CACHED region
  38306. const lastCachedIndex = nCachedObjects ++,
  38307. firstActiveObject = objects[ lastCachedIndex ];
  38308. indicesByUUID[ firstActiveObject.uuid ] = index;
  38309. objects[ index ] = firstActiveObject;
  38310. indicesByUUID[ uuid ] = lastCachedIndex;
  38311. objects[ lastCachedIndex ] = object;
  38312. // accounting is done, now do the same for all bindings
  38313. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38314. const bindingsForPath = bindings[ j ],
  38315. firstActive = bindingsForPath[ lastCachedIndex ],
  38316. binding = bindingsForPath[ index ];
  38317. bindingsForPath[ index ] = firstActive;
  38318. bindingsForPath[ lastCachedIndex ] = binding;
  38319. }
  38320. }
  38321. } // for arguments
  38322. this.nCachedObjects_ = nCachedObjects;
  38323. }
  38324. /**
  38325. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38326. *
  38327. * @param {...Object3D} arguments - The 3D objects to uncache.
  38328. */
  38329. uncache() {
  38330. const objects = this._objects,
  38331. indicesByUUID = this._indicesByUUID,
  38332. bindings = this._bindings,
  38333. nBindings = bindings.length;
  38334. let nCachedObjects = this.nCachedObjects_,
  38335. nObjects = objects.length;
  38336. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38337. const object = arguments[ i ],
  38338. uuid = object.uuid,
  38339. index = indicesByUUID[ uuid ];
  38340. if ( index !== undefined ) {
  38341. delete indicesByUUID[ uuid ];
  38342. if ( index < nCachedObjects ) {
  38343. // object is cached, shrink the CACHED region
  38344. const firstActiveIndex = -- nCachedObjects,
  38345. lastCachedObject = objects[ firstActiveIndex ],
  38346. lastIndex = -- nObjects,
  38347. lastObject = objects[ lastIndex ];
  38348. // last cached object takes this object's place
  38349. indicesByUUID[ lastCachedObject.uuid ] = index;
  38350. objects[ index ] = lastCachedObject;
  38351. // last object goes to the activated slot and pop
  38352. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38353. objects[ firstActiveIndex ] = lastObject;
  38354. objects.pop();
  38355. // accounting is done, now do the same for all bindings
  38356. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38357. const bindingsForPath = bindings[ j ],
  38358. lastCached = bindingsForPath[ firstActiveIndex ],
  38359. last = bindingsForPath[ lastIndex ];
  38360. bindingsForPath[ index ] = lastCached;
  38361. bindingsForPath[ firstActiveIndex ] = last;
  38362. bindingsForPath.pop();
  38363. }
  38364. } else {
  38365. // object is active, just swap with the last and pop
  38366. const lastIndex = -- nObjects,
  38367. lastObject = objects[ lastIndex ];
  38368. if ( lastIndex > 0 ) {
  38369. indicesByUUID[ lastObject.uuid ] = index;
  38370. }
  38371. objects[ index ] = lastObject;
  38372. objects.pop();
  38373. // accounting is done, now do the same for all bindings
  38374. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38375. const bindingsForPath = bindings[ j ];
  38376. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38377. bindingsForPath.pop();
  38378. }
  38379. } // cached or active
  38380. } // if object is known
  38381. } // for arguments
  38382. this.nCachedObjects_ = nCachedObjects;
  38383. }
  38384. // Internal interface used by befriended PropertyBinding.Composite:
  38385. subscribe_( path, parsedPath ) {
  38386. // returns an array of bindings for the given path that is changed
  38387. // according to the contained objects in the group
  38388. const indicesByPath = this._bindingsIndicesByPath;
  38389. let index = indicesByPath[ path ];
  38390. const bindings = this._bindings;
  38391. if ( index !== undefined ) return bindings[ index ];
  38392. const paths = this._paths,
  38393. parsedPaths = this._parsedPaths,
  38394. objects = this._objects,
  38395. nObjects = objects.length,
  38396. nCachedObjects = this.nCachedObjects_,
  38397. bindingsForPath = new Array( nObjects );
  38398. index = bindings.length;
  38399. indicesByPath[ path ] = index;
  38400. paths.push( path );
  38401. parsedPaths.push( parsedPath );
  38402. bindings.push( bindingsForPath );
  38403. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38404. const object = objects[ i ];
  38405. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38406. }
  38407. return bindingsForPath;
  38408. }
  38409. unsubscribe_( path ) {
  38410. // tells the group to forget about a property path and no longer
  38411. // update the array previously obtained with 'subscribe_'
  38412. const indicesByPath = this._bindingsIndicesByPath,
  38413. index = indicesByPath[ path ];
  38414. if ( index !== undefined ) {
  38415. const paths = this._paths,
  38416. parsedPaths = this._parsedPaths,
  38417. bindings = this._bindings,
  38418. lastBindingsIndex = bindings.length - 1,
  38419. lastBindings = bindings[ lastBindingsIndex ],
  38420. lastBindingsPath = path[ lastBindingsIndex ];
  38421. indicesByPath[ lastBindingsPath ] = index;
  38422. bindings[ index ] = lastBindings;
  38423. bindings.pop();
  38424. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38425. parsedPaths.pop();
  38426. paths[ index ] = paths[ lastBindingsIndex ];
  38427. paths.pop();
  38428. }
  38429. }
  38430. }
  38431. /**
  38432. * An instance of `AnimationAction` schedules the playback of an animation which is
  38433. * stored in {@link AnimationClip}.
  38434. */
  38435. class AnimationAction {
  38436. /**
  38437. * Constructs a new animation action.
  38438. *
  38439. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38440. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38441. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38442. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38443. */
  38444. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38445. this._mixer = mixer;
  38446. this._clip = clip;
  38447. this._localRoot = localRoot;
  38448. /**
  38449. * Defines how the animation is blended/combined when two or more animations
  38450. * are simultaneously played.
  38451. *
  38452. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38453. */
  38454. this.blendMode = blendMode;
  38455. const tracks = clip.tracks,
  38456. nTracks = tracks.length,
  38457. interpolants = new Array( nTracks );
  38458. const interpolantSettings = {
  38459. endingStart: ZeroCurvatureEnding,
  38460. endingEnd: ZeroCurvatureEnding
  38461. };
  38462. for ( let i = 0; i !== nTracks; ++ i ) {
  38463. const interpolant = tracks[ i ].createInterpolant( null );
  38464. interpolants[ i ] = interpolant;
  38465. interpolant.settings = interpolantSettings;
  38466. }
  38467. this._interpolantSettings = interpolantSettings;
  38468. this._interpolants = interpolants; // bound by the mixer
  38469. // inside: PropertyMixer (managed by the mixer)
  38470. this._propertyBindings = new Array( nTracks );
  38471. this._cacheIndex = null; // for the memory manager
  38472. this._byClipCacheIndex = null; // for the memory manager
  38473. this._timeScaleInterpolant = null;
  38474. this._weightInterpolant = null;
  38475. /**
  38476. * The loop mode, set via {@link AnimationAction#setLoop}.
  38477. *
  38478. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38479. * @default LoopRepeat
  38480. */
  38481. this.loop = LoopRepeat;
  38482. this._loopCount = -1;
  38483. // global mixer time when the action is to be started
  38484. // it's set back to 'null' upon start of the action
  38485. this._startTime = null;
  38486. /**
  38487. * The local time of this action (in seconds, starting with `0`).
  38488. *
  38489. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38490. * loop state).
  38491. *
  38492. * @type {number}
  38493. * @default Infinity
  38494. */
  38495. this.time = 0;
  38496. /**
  38497. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38498. * animation to pause. Negative values cause the animation to play backwards.
  38499. *
  38500. * @type {number}
  38501. * @default 1
  38502. */
  38503. this.timeScale = 1;
  38504. this._effectiveTimeScale = 1;
  38505. /**
  38506. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38507. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38508. * several actions.
  38509. *
  38510. * @type {number}
  38511. * @default 1
  38512. */
  38513. this.weight = 1;
  38514. this._effectiveWeight = 1;
  38515. /**
  38516. * The number of repetitions of the performed clip over the course of this action.
  38517. * Can be set via {@link AnimationAction#setLoop}.
  38518. *
  38519. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38520. * `THREE:LoopOnce`.
  38521. *
  38522. * @type {number}
  38523. * @default Infinity
  38524. */
  38525. this.repetitions = Infinity;
  38526. /**
  38527. * If set to `true`, the playback of the action is paused.
  38528. *
  38529. * @type {boolean}
  38530. * @default false
  38531. */
  38532. this.paused = false;
  38533. /**
  38534. * If set to `false`, the action is disabled so it has no impact.
  38535. *
  38536. * When the action is re-enabled, the animation continues from its current
  38537. * time (setting `enabled` to `false` doesn't reset the action).
  38538. *
  38539. * @type {boolean}
  38540. * @default true
  38541. */
  38542. this.enabled = true;
  38543. /**
  38544. * If set to true the animation will automatically be paused on its last frame.
  38545. *
  38546. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38547. * to `false` when the last loop of the action has finished, so that this action has
  38548. * no further impact.
  38549. *
  38550. * Note: This member has no impact if the action is interrupted (it
  38551. * has only an effect if its last loop has really finished).
  38552. *
  38553. * @type {boolean}
  38554. * @default false
  38555. */
  38556. this.clampWhenFinished = false;
  38557. /**
  38558. * Enables smooth interpolation without separate clips for start, loop and end.
  38559. *
  38560. * @type {boolean}
  38561. * @default true
  38562. */
  38563. this.zeroSlopeAtStart = true;
  38564. /**
  38565. * Enables smooth interpolation without separate clips for start, loop and end.
  38566. *
  38567. * @type {boolean}
  38568. * @default true
  38569. */
  38570. this.zeroSlopeAtEnd = true;
  38571. }
  38572. /**
  38573. * Starts the playback of the animation.
  38574. *
  38575. * @return {AnimationAction} A reference to this animation action.
  38576. */
  38577. play() {
  38578. this._mixer._activateAction( this );
  38579. return this;
  38580. }
  38581. /**
  38582. * Stops the playback of the animation.
  38583. *
  38584. * @return {AnimationAction} A reference to this animation action.
  38585. */
  38586. stop() {
  38587. this._mixer._deactivateAction( this );
  38588. return this.reset();
  38589. }
  38590. /**
  38591. * Resets the playback of the animation.
  38592. *
  38593. * @return {AnimationAction} A reference to this animation action.
  38594. */
  38595. reset() {
  38596. this.paused = false;
  38597. this.enabled = true;
  38598. this.time = 0; // restart clip
  38599. this._loopCount = -1;// forget previous loops
  38600. this._startTime = null;// forget scheduling
  38601. return this.stopFading().stopWarping();
  38602. }
  38603. /**
  38604. * Returns `true` if the animation is running.
  38605. *
  38606. * @return {boolean} Whether the animation is running or not.
  38607. */
  38608. isRunning() {
  38609. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38610. this._startTime === null && this._mixer._isActiveAction( this );
  38611. }
  38612. /**
  38613. * Returns `true` when {@link AnimationAction#play} has been called.
  38614. *
  38615. * @return {boolean} Whether the animation is scheduled or not.
  38616. */
  38617. isScheduled() {
  38618. return this._mixer._isActiveAction( this );
  38619. }
  38620. /**
  38621. * Defines the time when the animation should start.
  38622. *
  38623. * @param {number} time - The start time in seconds.
  38624. * @return {AnimationAction} A reference to this animation action.
  38625. */
  38626. startAt( time ) {
  38627. this._startTime = time;
  38628. return this;
  38629. }
  38630. /**
  38631. * Configures the loop settings for this action.
  38632. *
  38633. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38634. * @param {number} repetitions - The number of repetitions.
  38635. * @return {AnimationAction} A reference to this animation action.
  38636. */
  38637. setLoop( mode, repetitions ) {
  38638. this.loop = mode;
  38639. this.repetitions = repetitions;
  38640. return this;
  38641. }
  38642. /**
  38643. * Sets the effective weight of this action.
  38644. *
  38645. * An action has no effect and thus an effective weight of zero when the
  38646. * action is disabled.
  38647. *
  38648. * @param {number} weight - The weight to set.
  38649. * @return {AnimationAction} A reference to this animation action.
  38650. */
  38651. setEffectiveWeight( weight ) {
  38652. this.weight = weight;
  38653. // note: same logic as when updated at runtime
  38654. this._effectiveWeight = this.enabled ? weight : 0;
  38655. return this.stopFading();
  38656. }
  38657. /**
  38658. * Returns the effective weight of this action.
  38659. *
  38660. * @return {number} The effective weight.
  38661. */
  38662. getEffectiveWeight() {
  38663. return this._effectiveWeight;
  38664. }
  38665. /**
  38666. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38667. * within the passed time interval.
  38668. *
  38669. * @param {number} duration - The duration of the fade.
  38670. * @return {AnimationAction} A reference to this animation action.
  38671. */
  38672. fadeIn( duration ) {
  38673. return this._scheduleFading( duration, 0, 1 );
  38674. }
  38675. /**
  38676. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38677. * within the passed time interval.
  38678. *
  38679. * @param {number} duration - The duration of the fade.
  38680. * @return {AnimationAction} A reference to this animation action.
  38681. */
  38682. fadeOut( duration ) {
  38683. return this._scheduleFading( duration, 1, 0 );
  38684. }
  38685. /**
  38686. * Causes this action to fade in and the given action to fade out,
  38687. * within the passed time interval.
  38688. *
  38689. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38690. * @param {number} duration - The duration of the fade.
  38691. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38692. * @return {AnimationAction} A reference to this animation action.
  38693. */
  38694. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38695. fadeOutAction.fadeOut( duration );
  38696. this.fadeIn( duration );
  38697. if ( warp === true ) {
  38698. const fadeInDuration = this._clip.duration,
  38699. fadeOutDuration = fadeOutAction._clip.duration,
  38700. startEndRatio = fadeOutDuration / fadeInDuration,
  38701. endStartRatio = fadeInDuration / fadeOutDuration;
  38702. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38703. this.warp( endStartRatio, 1.0, duration );
  38704. }
  38705. return this;
  38706. }
  38707. /**
  38708. * Causes this action to fade out and the given action to fade in,
  38709. * within the passed time interval.
  38710. *
  38711. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38712. * @param {number} duration - The duration of the fade.
  38713. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38714. * @return {AnimationAction} A reference to this animation action.
  38715. */
  38716. crossFadeTo( fadeInAction, duration, warp = false ) {
  38717. return fadeInAction.crossFadeFrom( this, duration, warp );
  38718. }
  38719. /**
  38720. * Stops any fading which is applied to this action.
  38721. *
  38722. * @return {AnimationAction} A reference to this animation action.
  38723. */
  38724. stopFading() {
  38725. const weightInterpolant = this._weightInterpolant;
  38726. if ( weightInterpolant !== null ) {
  38727. this._weightInterpolant = null;
  38728. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38729. }
  38730. return this;
  38731. }
  38732. /**
  38733. * Sets the effective time scale of this action.
  38734. *
  38735. * An action has no effect and thus an effective time scale of zero when the
  38736. * action is paused.
  38737. *
  38738. * @param {number} timeScale - The time scale to set.
  38739. * @return {AnimationAction} A reference to this animation action.
  38740. */
  38741. setEffectiveTimeScale( timeScale ) {
  38742. this.timeScale = timeScale;
  38743. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38744. return this.stopWarping();
  38745. }
  38746. /**
  38747. * Returns the effective time scale of this action.
  38748. *
  38749. * @return {number} The effective time scale.
  38750. */
  38751. getEffectiveTimeScale() {
  38752. return this._effectiveTimeScale;
  38753. }
  38754. /**
  38755. * Sets the duration for a single loop of this action.
  38756. *
  38757. * @param {number} duration - The duration to set.
  38758. * @return {AnimationAction} A reference to this animation action.
  38759. */
  38760. setDuration( duration ) {
  38761. this.timeScale = this._clip.duration / duration;
  38762. return this.stopWarping();
  38763. }
  38764. /**
  38765. * Synchronizes this action with the passed other action.
  38766. *
  38767. * @param {AnimationAction} action - The action to sync with.
  38768. * @return {AnimationAction} A reference to this animation action.
  38769. */
  38770. syncWith( action ) {
  38771. this.time = action.time;
  38772. this.timeScale = action.timeScale;
  38773. return this.stopWarping();
  38774. }
  38775. /**
  38776. * Decelerates this animation's speed to `0` within the passed time interval.
  38777. *
  38778. * @param {number} duration - The duration.
  38779. * @return {AnimationAction} A reference to this animation action.
  38780. */
  38781. halt( duration ) {
  38782. return this.warp( this._effectiveTimeScale, 0, duration );
  38783. }
  38784. /**
  38785. * Changes the playback speed, within the passed time interval, by modifying
  38786. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38787. * `endTimeScale`.
  38788. *
  38789. * @param {number} startTimeScale - The start time scale.
  38790. * @param {number} endTimeScale - The end time scale.
  38791. * @param {number} duration - The duration.
  38792. * @return {AnimationAction} A reference to this animation action.
  38793. */
  38794. warp( startTimeScale, endTimeScale, duration ) {
  38795. const mixer = this._mixer,
  38796. now = mixer.time,
  38797. timeScale = this.timeScale;
  38798. let interpolant = this._timeScaleInterpolant;
  38799. if ( interpolant === null ) {
  38800. interpolant = mixer._lendControlInterpolant();
  38801. this._timeScaleInterpolant = interpolant;
  38802. }
  38803. const times = interpolant.parameterPositions,
  38804. values = interpolant.sampleValues;
  38805. times[ 0 ] = now;
  38806. times[ 1 ] = now + duration;
  38807. values[ 0 ] = startTimeScale / timeScale;
  38808. values[ 1 ] = endTimeScale / timeScale;
  38809. return this;
  38810. }
  38811. /**
  38812. * Stops any scheduled warping which is applied to this action.
  38813. *
  38814. * @return {AnimationAction} A reference to this animation action.
  38815. */
  38816. stopWarping() {
  38817. const timeScaleInterpolant = this._timeScaleInterpolant;
  38818. if ( timeScaleInterpolant !== null ) {
  38819. this._timeScaleInterpolant = null;
  38820. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38821. }
  38822. return this;
  38823. }
  38824. /**
  38825. * Returns the animation mixer of this animation action.
  38826. *
  38827. * @return {AnimationMixer} The animation mixer.
  38828. */
  38829. getMixer() {
  38830. return this._mixer;
  38831. }
  38832. /**
  38833. * Returns the animation clip of this animation action.
  38834. *
  38835. * @return {AnimationClip} The animation clip.
  38836. */
  38837. getClip() {
  38838. return this._clip;
  38839. }
  38840. /**
  38841. * Returns the root object of this animation action.
  38842. *
  38843. * @return {Object3D} The root object.
  38844. */
  38845. getRoot() {
  38846. return this._localRoot || this._mixer._root;
  38847. }
  38848. // Internal
  38849. _update( time, deltaTime, timeDirection, accuIndex ) {
  38850. // called by the mixer
  38851. if ( ! this.enabled ) {
  38852. // call ._updateWeight() to update ._effectiveWeight
  38853. this._updateWeight( time );
  38854. return;
  38855. }
  38856. const startTime = this._startTime;
  38857. if ( startTime !== null ) {
  38858. // check for scheduled start of action
  38859. const timeRunning = ( time - startTime ) * timeDirection;
  38860. if ( timeRunning < 0 || timeDirection === 0 ) {
  38861. deltaTime = 0;
  38862. } else {
  38863. this._startTime = null; // unschedule
  38864. deltaTime = timeDirection * timeRunning;
  38865. }
  38866. }
  38867. // apply time scale and advance time
  38868. deltaTime *= this._updateTimeScale( time );
  38869. const clipTime = this._updateTime( deltaTime );
  38870. // note: _updateTime may disable the action resulting in
  38871. // an effective weight of 0
  38872. const weight = this._updateWeight( time );
  38873. if ( weight > 0 ) {
  38874. const interpolants = this._interpolants;
  38875. const propertyMixers = this._propertyBindings;
  38876. switch ( this.blendMode ) {
  38877. case AdditiveAnimationBlendMode:
  38878. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38879. interpolants[ j ].evaluate( clipTime );
  38880. propertyMixers[ j ].accumulateAdditive( weight );
  38881. }
  38882. break;
  38883. case NormalAnimationBlendMode:
  38884. default:
  38885. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38886. interpolants[ j ].evaluate( clipTime );
  38887. propertyMixers[ j ].accumulate( accuIndex, weight );
  38888. }
  38889. }
  38890. }
  38891. }
  38892. _updateWeight( time ) {
  38893. let weight = 0;
  38894. if ( this.enabled ) {
  38895. weight = this.weight;
  38896. const interpolant = this._weightInterpolant;
  38897. if ( interpolant !== null ) {
  38898. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38899. weight *= interpolantValue;
  38900. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38901. this.stopFading();
  38902. if ( interpolantValue === 0 ) {
  38903. // faded out, disable
  38904. this.enabled = false;
  38905. }
  38906. }
  38907. }
  38908. }
  38909. this._effectiveWeight = weight;
  38910. return weight;
  38911. }
  38912. _updateTimeScale( time ) {
  38913. let timeScale = 0;
  38914. if ( ! this.paused ) {
  38915. timeScale = this.timeScale;
  38916. const interpolant = this._timeScaleInterpolant;
  38917. if ( interpolant !== null ) {
  38918. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38919. timeScale *= interpolantValue;
  38920. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38921. this.stopWarping();
  38922. if ( timeScale === 0 ) {
  38923. // motion has halted, pause
  38924. this.paused = true;
  38925. } else {
  38926. // warp done - apply final time scale
  38927. this.timeScale = timeScale;
  38928. }
  38929. }
  38930. }
  38931. }
  38932. this._effectiveTimeScale = timeScale;
  38933. return timeScale;
  38934. }
  38935. _updateTime( deltaTime ) {
  38936. const duration = this._clip.duration;
  38937. const loop = this.loop;
  38938. let time = this.time + deltaTime;
  38939. let loopCount = this._loopCount;
  38940. const pingPong = ( loop === LoopPingPong );
  38941. if ( deltaTime === 0 ) {
  38942. if ( loopCount === -1 ) return time;
  38943. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38944. }
  38945. if ( loop === LoopOnce ) {
  38946. if ( loopCount === -1 ) {
  38947. // just started
  38948. this._loopCount = 0;
  38949. this._setEndings( true, true, false );
  38950. }
  38951. handle_stop: {
  38952. if ( time >= duration ) {
  38953. time = duration;
  38954. } else if ( time < 0 ) {
  38955. time = 0;
  38956. } else {
  38957. this.time = time;
  38958. break handle_stop;
  38959. }
  38960. if ( this.clampWhenFinished ) this.paused = true;
  38961. else this.enabled = false;
  38962. this.time = time;
  38963. this._mixer.dispatchEvent( {
  38964. type: 'finished', action: this,
  38965. direction: deltaTime < 0 ? -1 : 1
  38966. } );
  38967. }
  38968. } else { // repetitive Repeat or PingPong
  38969. if ( loopCount === -1 ) {
  38970. // just started
  38971. if ( deltaTime >= 0 ) {
  38972. loopCount = 0;
  38973. this._setEndings( true, this.repetitions === 0, pingPong );
  38974. } else {
  38975. // when looping in reverse direction, the initial
  38976. // transition through zero counts as a repetition,
  38977. // so leave loopCount at -1
  38978. this._setEndings( this.repetitions === 0, true, pingPong );
  38979. }
  38980. }
  38981. if ( time >= duration || time < 0 ) {
  38982. // wrap around
  38983. const loopDelta = Math.floor( time / duration ); // signed
  38984. time -= duration * loopDelta;
  38985. loopCount += Math.abs( loopDelta );
  38986. const pending = this.repetitions - loopCount;
  38987. if ( pending <= 0 ) {
  38988. // have to stop (switch state, clamp time, fire event)
  38989. if ( this.clampWhenFinished ) this.paused = true;
  38990. else this.enabled = false;
  38991. time = deltaTime > 0 ? duration : 0;
  38992. this.time = time;
  38993. this._mixer.dispatchEvent( {
  38994. type: 'finished', action: this,
  38995. direction: deltaTime > 0 ? 1 : -1
  38996. } );
  38997. } else {
  38998. // keep running
  38999. if ( pending === 1 ) {
  39000. // entering the last round
  39001. const atStart = deltaTime < 0;
  39002. this._setEndings( atStart, ! atStart, pingPong );
  39003. } else {
  39004. this._setEndings( false, false, pingPong );
  39005. }
  39006. this._loopCount = loopCount;
  39007. this.time = time;
  39008. this._mixer.dispatchEvent( {
  39009. type: 'loop', action: this, loopDelta: loopDelta
  39010. } );
  39011. }
  39012. } else {
  39013. this.time = time;
  39014. }
  39015. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  39016. // invert time for the "pong round"
  39017. return duration - time;
  39018. }
  39019. }
  39020. return time;
  39021. }
  39022. _setEndings( atStart, atEnd, pingPong ) {
  39023. const settings = this._interpolantSettings;
  39024. if ( pingPong ) {
  39025. settings.endingStart = ZeroSlopeEnding;
  39026. settings.endingEnd = ZeroSlopeEnding;
  39027. } else {
  39028. // assuming for LoopOnce atStart == atEnd == true
  39029. if ( atStart ) {
  39030. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39031. } else {
  39032. settings.endingStart = WrapAroundEnding;
  39033. }
  39034. if ( atEnd ) {
  39035. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  39036. } else {
  39037. settings.endingEnd = WrapAroundEnding;
  39038. }
  39039. }
  39040. }
  39041. _scheduleFading( duration, weightNow, weightThen ) {
  39042. const mixer = this._mixer, now = mixer.time;
  39043. let interpolant = this._weightInterpolant;
  39044. if ( interpolant === null ) {
  39045. interpolant = mixer._lendControlInterpolant();
  39046. this._weightInterpolant = interpolant;
  39047. }
  39048. const times = interpolant.parameterPositions,
  39049. values = interpolant.sampleValues;
  39050. times[ 0 ] = now;
  39051. values[ 0 ] = weightNow;
  39052. times[ 1 ] = now + duration;
  39053. values[ 1 ] = weightThen;
  39054. return this;
  39055. }
  39056. }
  39057. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  39058. /**
  39059. * `AnimationMixer` is a player for animations on a particular object in
  39060. * the scene. When multiple objects in the scene are animated independently,
  39061. * one `AnimationMixer` may be used for each object.
  39062. */
  39063. class AnimationMixer extends EventDispatcher {
  39064. /**
  39065. * Constructs a new animation mixer.
  39066. *
  39067. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  39068. */
  39069. constructor( root ) {
  39070. super();
  39071. this._root = root;
  39072. this._initMemoryManager();
  39073. this._accuIndex = 0;
  39074. /**
  39075. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  39076. *
  39077. * @type {number}
  39078. * @default 0
  39079. */
  39080. this.time = 0;
  39081. /**
  39082. * A scaling factor for the global time.
  39083. *
  39084. * Note: Setting this member to `0` and later back to `1` is a
  39085. * possibility to pause/unpause all actions that are controlled by this
  39086. * mixer.
  39087. *
  39088. * @type {number}
  39089. * @default 1
  39090. */
  39091. this.timeScale = 1.0;
  39092. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  39093. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  39094. }
  39095. }
  39096. _bindAction( action, prototypeAction ) {
  39097. const root = action._localRoot || this._root,
  39098. tracks = action._clip.tracks,
  39099. nTracks = tracks.length,
  39100. bindings = action._propertyBindings,
  39101. interpolants = action._interpolants,
  39102. rootUuid = root.uuid,
  39103. bindingsByRoot = this._bindingsByRootAndName;
  39104. let bindingsByName = bindingsByRoot[ rootUuid ];
  39105. if ( bindingsByName === undefined ) {
  39106. bindingsByName = {};
  39107. bindingsByRoot[ rootUuid ] = bindingsByName;
  39108. }
  39109. for ( let i = 0; i !== nTracks; ++ i ) {
  39110. const track = tracks[ i ],
  39111. trackName = track.name;
  39112. let binding = bindingsByName[ trackName ];
  39113. if ( binding !== undefined ) {
  39114. ++ binding.referenceCount;
  39115. bindings[ i ] = binding;
  39116. } else {
  39117. binding = bindings[ i ];
  39118. if ( binding !== undefined ) {
  39119. // existing binding, make sure the cache knows
  39120. if ( binding._cacheIndex === null ) {
  39121. ++ binding.referenceCount;
  39122. this._addInactiveBinding( binding, rootUuid, trackName );
  39123. }
  39124. continue;
  39125. }
  39126. const path = prototypeAction && prototypeAction.
  39127. _propertyBindings[ i ].binding.parsedPath;
  39128. binding = new PropertyMixer(
  39129. PropertyBinding.create( root, trackName, path ),
  39130. track.ValueTypeName, track.getValueSize() );
  39131. ++ binding.referenceCount;
  39132. this._addInactiveBinding( binding, rootUuid, trackName );
  39133. bindings[ i ] = binding;
  39134. }
  39135. interpolants[ i ].resultBuffer = binding.buffer;
  39136. }
  39137. }
  39138. _activateAction( action ) {
  39139. if ( ! this._isActiveAction( action ) ) {
  39140. if ( action._cacheIndex === null ) {
  39141. // this action has been forgotten by the cache, but the user
  39142. // appears to be still using it -> rebind
  39143. const rootUuid = ( action._localRoot || this._root ).uuid,
  39144. clipUuid = action._clip.uuid,
  39145. actionsForClip = this._actionsByClip[ clipUuid ];
  39146. this._bindAction( action,
  39147. actionsForClip && actionsForClip.knownActions[ 0 ] );
  39148. this._addInactiveAction( action, clipUuid, rootUuid );
  39149. }
  39150. const bindings = action._propertyBindings;
  39151. // increment reference counts / sort out state
  39152. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39153. const binding = bindings[ i ];
  39154. if ( binding.useCount ++ === 0 ) {
  39155. this._lendBinding( binding );
  39156. binding.saveOriginalState();
  39157. }
  39158. }
  39159. this._lendAction( action );
  39160. }
  39161. }
  39162. _deactivateAction( action ) {
  39163. if ( this._isActiveAction( action ) ) {
  39164. const bindings = action._propertyBindings;
  39165. // decrement reference counts / sort out state
  39166. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39167. const binding = bindings[ i ];
  39168. if ( -- binding.useCount === 0 ) {
  39169. binding.restoreOriginalState();
  39170. this._takeBackBinding( binding );
  39171. }
  39172. }
  39173. this._takeBackAction( action );
  39174. }
  39175. }
  39176. // Memory manager
  39177. _initMemoryManager() {
  39178. this._actions = []; // 'nActiveActions' followed by inactive ones
  39179. this._nActiveActions = 0;
  39180. this._actionsByClip = {};
  39181. // inside:
  39182. // {
  39183. // knownActions: Array< AnimationAction > - used as prototypes
  39184. // actionByRoot: AnimationAction - lookup
  39185. // }
  39186. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  39187. this._nActiveBindings = 0;
  39188. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  39189. this._controlInterpolants = []; // same game as above
  39190. this._nActiveControlInterpolants = 0;
  39191. const scope = this;
  39192. this.stats = {
  39193. actions: {
  39194. get total() {
  39195. return scope._actions.length;
  39196. },
  39197. get inUse() {
  39198. return scope._nActiveActions;
  39199. }
  39200. },
  39201. bindings: {
  39202. get total() {
  39203. return scope._bindings.length;
  39204. },
  39205. get inUse() {
  39206. return scope._nActiveBindings;
  39207. }
  39208. },
  39209. controlInterpolants: {
  39210. get total() {
  39211. return scope._controlInterpolants.length;
  39212. },
  39213. get inUse() {
  39214. return scope._nActiveControlInterpolants;
  39215. }
  39216. }
  39217. };
  39218. }
  39219. // Memory management for AnimationAction objects
  39220. _isActiveAction( action ) {
  39221. const index = action._cacheIndex;
  39222. return index !== null && index < this._nActiveActions;
  39223. }
  39224. _addInactiveAction( action, clipUuid, rootUuid ) {
  39225. const actions = this._actions,
  39226. actionsByClip = this._actionsByClip;
  39227. let actionsForClip = actionsByClip[ clipUuid ];
  39228. if ( actionsForClip === undefined ) {
  39229. actionsForClip = {
  39230. knownActions: [ action ],
  39231. actionByRoot: {}
  39232. };
  39233. action._byClipCacheIndex = 0;
  39234. actionsByClip[ clipUuid ] = actionsForClip;
  39235. } else {
  39236. const knownActions = actionsForClip.knownActions;
  39237. action._byClipCacheIndex = knownActions.length;
  39238. knownActions.push( action );
  39239. }
  39240. action._cacheIndex = actions.length;
  39241. actions.push( action );
  39242. actionsForClip.actionByRoot[ rootUuid ] = action;
  39243. }
  39244. _removeInactiveAction( action ) {
  39245. const actions = this._actions,
  39246. lastInactiveAction = actions[ actions.length - 1 ],
  39247. cacheIndex = action._cacheIndex;
  39248. lastInactiveAction._cacheIndex = cacheIndex;
  39249. actions[ cacheIndex ] = lastInactiveAction;
  39250. actions.pop();
  39251. action._cacheIndex = null;
  39252. const clipUuid = action._clip.uuid,
  39253. actionsByClip = this._actionsByClip,
  39254. actionsForClip = actionsByClip[ clipUuid ],
  39255. knownActionsForClip = actionsForClip.knownActions,
  39256. lastKnownAction =
  39257. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39258. byClipCacheIndex = action._byClipCacheIndex;
  39259. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39260. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39261. knownActionsForClip.pop();
  39262. action._byClipCacheIndex = null;
  39263. const actionByRoot = actionsForClip.actionByRoot,
  39264. rootUuid = ( action._localRoot || this._root ).uuid;
  39265. delete actionByRoot[ rootUuid ];
  39266. if ( knownActionsForClip.length === 0 ) {
  39267. delete actionsByClip[ clipUuid ];
  39268. }
  39269. this._removeInactiveBindingsForAction( action );
  39270. }
  39271. _removeInactiveBindingsForAction( action ) {
  39272. const bindings = action._propertyBindings;
  39273. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39274. const binding = bindings[ i ];
  39275. if ( -- binding.referenceCount === 0 ) {
  39276. this._removeInactiveBinding( binding );
  39277. }
  39278. }
  39279. }
  39280. _lendAction( action ) {
  39281. // [ active actions | inactive actions ]
  39282. // [ active actions >| inactive actions ]
  39283. // s a
  39284. // <-swap->
  39285. // a s
  39286. const actions = this._actions,
  39287. prevIndex = action._cacheIndex,
  39288. lastActiveIndex = this._nActiveActions ++,
  39289. firstInactiveAction = actions[ lastActiveIndex ];
  39290. action._cacheIndex = lastActiveIndex;
  39291. actions[ lastActiveIndex ] = action;
  39292. firstInactiveAction._cacheIndex = prevIndex;
  39293. actions[ prevIndex ] = firstInactiveAction;
  39294. }
  39295. _takeBackAction( action ) {
  39296. // [ active actions | inactive actions ]
  39297. // [ active actions |< inactive actions ]
  39298. // a s
  39299. // <-swap->
  39300. // s a
  39301. const actions = this._actions,
  39302. prevIndex = action._cacheIndex,
  39303. firstInactiveIndex = -- this._nActiveActions,
  39304. lastActiveAction = actions[ firstInactiveIndex ];
  39305. action._cacheIndex = firstInactiveIndex;
  39306. actions[ firstInactiveIndex ] = action;
  39307. lastActiveAction._cacheIndex = prevIndex;
  39308. actions[ prevIndex ] = lastActiveAction;
  39309. }
  39310. // Memory management for PropertyMixer objects
  39311. _addInactiveBinding( binding, rootUuid, trackName ) {
  39312. const bindingsByRoot = this._bindingsByRootAndName,
  39313. bindings = this._bindings;
  39314. let bindingByName = bindingsByRoot[ rootUuid ];
  39315. if ( bindingByName === undefined ) {
  39316. bindingByName = {};
  39317. bindingsByRoot[ rootUuid ] = bindingByName;
  39318. }
  39319. bindingByName[ trackName ] = binding;
  39320. binding._cacheIndex = bindings.length;
  39321. bindings.push( binding );
  39322. }
  39323. _removeInactiveBinding( binding ) {
  39324. const bindings = this._bindings,
  39325. propBinding = binding.binding,
  39326. rootUuid = propBinding.rootNode.uuid,
  39327. trackName = propBinding.path,
  39328. bindingsByRoot = this._bindingsByRootAndName,
  39329. bindingByName = bindingsByRoot[ rootUuid ],
  39330. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39331. cacheIndex = binding._cacheIndex;
  39332. lastInactiveBinding._cacheIndex = cacheIndex;
  39333. bindings[ cacheIndex ] = lastInactiveBinding;
  39334. bindings.pop();
  39335. delete bindingByName[ trackName ];
  39336. if ( Object.keys( bindingByName ).length === 0 ) {
  39337. delete bindingsByRoot[ rootUuid ];
  39338. }
  39339. }
  39340. _lendBinding( binding ) {
  39341. const bindings = this._bindings,
  39342. prevIndex = binding._cacheIndex,
  39343. lastActiveIndex = this._nActiveBindings ++,
  39344. firstInactiveBinding = bindings[ lastActiveIndex ];
  39345. binding._cacheIndex = lastActiveIndex;
  39346. bindings[ lastActiveIndex ] = binding;
  39347. firstInactiveBinding._cacheIndex = prevIndex;
  39348. bindings[ prevIndex ] = firstInactiveBinding;
  39349. }
  39350. _takeBackBinding( binding ) {
  39351. const bindings = this._bindings,
  39352. prevIndex = binding._cacheIndex,
  39353. firstInactiveIndex = -- this._nActiveBindings,
  39354. lastActiveBinding = bindings[ firstInactiveIndex ];
  39355. binding._cacheIndex = firstInactiveIndex;
  39356. bindings[ firstInactiveIndex ] = binding;
  39357. lastActiveBinding._cacheIndex = prevIndex;
  39358. bindings[ prevIndex ] = lastActiveBinding;
  39359. }
  39360. // Memory management of Interpolants for weight and time scale
  39361. _lendControlInterpolant() {
  39362. const interpolants = this._controlInterpolants,
  39363. lastActiveIndex = this._nActiveControlInterpolants ++;
  39364. let interpolant = interpolants[ lastActiveIndex ];
  39365. if ( interpolant === undefined ) {
  39366. interpolant = new LinearInterpolant(
  39367. new Float32Array( 2 ), new Float32Array( 2 ),
  39368. 1, _controlInterpolantsResultBuffer );
  39369. interpolant.__cacheIndex = lastActiveIndex;
  39370. interpolants[ lastActiveIndex ] = interpolant;
  39371. }
  39372. return interpolant;
  39373. }
  39374. _takeBackControlInterpolant( interpolant ) {
  39375. const interpolants = this._controlInterpolants,
  39376. prevIndex = interpolant.__cacheIndex,
  39377. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39378. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39379. interpolant.__cacheIndex = firstInactiveIndex;
  39380. interpolants[ firstInactiveIndex ] = interpolant;
  39381. lastActiveInterpolant.__cacheIndex = prevIndex;
  39382. interpolants[ prevIndex ] = lastActiveInterpolant;
  39383. }
  39384. /**
  39385. * Returns an instance of {@link AnimationAction} for the passed clip.
  39386. *
  39387. * If an action fitting the clip and root parameters doesn't yet exist, it
  39388. * will be created by this method. Calling this method several times with the
  39389. * same clip and root parameters always returns the same action.
  39390. *
  39391. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39392. * @param {Object3D} [optionalRoot] - An alternative root object.
  39393. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39394. * @return {?AnimationAction} The animation action.
  39395. */
  39396. clipAction( clip, optionalRoot, blendMode ) {
  39397. const root = optionalRoot || this._root,
  39398. rootUuid = root.uuid;
  39399. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39400. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39401. const actionsForClip = this._actionsByClip[ clipUuid ];
  39402. let prototypeAction = null;
  39403. if ( blendMode === undefined ) {
  39404. if ( clipObject !== null ) {
  39405. blendMode = clipObject.blendMode;
  39406. } else {
  39407. blendMode = NormalAnimationBlendMode;
  39408. }
  39409. }
  39410. if ( actionsForClip !== undefined ) {
  39411. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39412. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39413. return existingAction;
  39414. }
  39415. // we know the clip, so we don't have to parse all
  39416. // the bindings again but can just copy
  39417. prototypeAction = actionsForClip.knownActions[ 0 ];
  39418. // also, take the clip from the prototype action
  39419. if ( clipObject === null )
  39420. clipObject = prototypeAction._clip;
  39421. }
  39422. // clip must be known when specified via string
  39423. if ( clipObject === null ) return null;
  39424. // allocate all resources required to run it
  39425. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39426. this._bindAction( newAction, prototypeAction );
  39427. // and make the action known to the memory manager
  39428. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39429. return newAction;
  39430. }
  39431. /**
  39432. * Returns an existing animation action for the passed clip.
  39433. *
  39434. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39435. * @param {Object3D} [optionalRoot] - An alternative root object.
  39436. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39437. */
  39438. existingAction( clip, optionalRoot ) {
  39439. const root = optionalRoot || this._root,
  39440. rootUuid = root.uuid,
  39441. clipObject = typeof clip === 'string' ?
  39442. AnimationClip.findByName( root, clip ) : clip,
  39443. clipUuid = clipObject ? clipObject.uuid : clip,
  39444. actionsForClip = this._actionsByClip[ clipUuid ];
  39445. if ( actionsForClip !== undefined ) {
  39446. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39447. }
  39448. return null;
  39449. }
  39450. /**
  39451. * Deactivates all previously scheduled actions on this mixer.
  39452. *
  39453. * @return {AnimationMixer} A reference to this animation mixer.
  39454. */
  39455. stopAllAction() {
  39456. const actions = this._actions,
  39457. nActions = this._nActiveActions;
  39458. for ( let i = nActions - 1; i >= 0; -- i ) {
  39459. actions[ i ].stop();
  39460. }
  39461. return this;
  39462. }
  39463. /**
  39464. * Advances the global mixer time and updates the animation.
  39465. *
  39466. * This is usually done in the render loop by passing the delta
  39467. * time from {@link Clock} or {@link Timer}.
  39468. *
  39469. * @param {number} deltaTime - The delta time in seconds.
  39470. * @return {AnimationMixer} A reference to this animation mixer.
  39471. */
  39472. update( deltaTime ) {
  39473. deltaTime *= this.timeScale;
  39474. const actions = this._actions,
  39475. nActions = this._nActiveActions,
  39476. time = this.time += deltaTime,
  39477. timeDirection = Math.sign( deltaTime ),
  39478. accuIndex = this._accuIndex ^= 1;
  39479. // run active actions
  39480. for ( let i = 0; i !== nActions; ++ i ) {
  39481. const action = actions[ i ];
  39482. action._update( time, deltaTime, timeDirection, accuIndex );
  39483. }
  39484. // update scene graph
  39485. const bindings = this._bindings,
  39486. nBindings = this._nActiveBindings;
  39487. for ( let i = 0; i !== nBindings; ++ i ) {
  39488. bindings[ i ].apply( accuIndex );
  39489. }
  39490. return this;
  39491. }
  39492. /**
  39493. * Sets the global mixer to a specific time and updates the animation accordingly.
  39494. *
  39495. * This is useful when you need to jump to an exact time in an animation. The
  39496. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39497. *
  39498. * @param {number} time - The time to set in seconds.
  39499. * @return {AnimationMixer} A reference to this animation mixer.
  39500. */
  39501. setTime( time ) {
  39502. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39503. for ( let i = 0; i < this._actions.length; i ++ ) {
  39504. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39505. }
  39506. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39507. }
  39508. /**
  39509. * Returns this mixer's root object.
  39510. *
  39511. * @return {Object3D} The mixer's root object.
  39512. */
  39513. getRoot() {
  39514. return this._root;
  39515. }
  39516. /**
  39517. * Deallocates all memory resources for a clip. Before using this method make
  39518. * sure to call {@link AnimationAction#stop} for all related actions.
  39519. *
  39520. * @param {AnimationClip} clip - The clip to uncache.
  39521. */
  39522. uncacheClip( clip ) {
  39523. const actions = this._actions,
  39524. clipUuid = clip.uuid,
  39525. actionsByClip = this._actionsByClip,
  39526. actionsForClip = actionsByClip[ clipUuid ];
  39527. if ( actionsForClip !== undefined ) {
  39528. // note: just calling _removeInactiveAction would mess up the
  39529. // iteration state and also require updating the state we can
  39530. // just throw away
  39531. const actionsToRemove = actionsForClip.knownActions;
  39532. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39533. const action = actionsToRemove[ i ];
  39534. this._deactivateAction( action );
  39535. const cacheIndex = action._cacheIndex,
  39536. lastInactiveAction = actions[ actions.length - 1 ];
  39537. action._cacheIndex = null;
  39538. action._byClipCacheIndex = null;
  39539. lastInactiveAction._cacheIndex = cacheIndex;
  39540. actions[ cacheIndex ] = lastInactiveAction;
  39541. actions.pop();
  39542. this._removeInactiveBindingsForAction( action );
  39543. }
  39544. delete actionsByClip[ clipUuid ];
  39545. }
  39546. }
  39547. /**
  39548. * Deallocates all memory resources for a root object. Before using this
  39549. * method make sure to call {@link AnimationAction#stop} for all related
  39550. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39551. * mixer operates on a single root.
  39552. *
  39553. * @param {Object3D} root - The root object to uncache.
  39554. */
  39555. uncacheRoot( root ) {
  39556. const rootUuid = root.uuid,
  39557. actionsByClip = this._actionsByClip;
  39558. for ( const clipUuid in actionsByClip ) {
  39559. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39560. action = actionByRoot[ rootUuid ];
  39561. if ( action !== undefined ) {
  39562. this._deactivateAction( action );
  39563. this._removeInactiveAction( action );
  39564. }
  39565. }
  39566. const bindingsByRoot = this._bindingsByRootAndName,
  39567. bindingByName = bindingsByRoot[ rootUuid ];
  39568. if ( bindingByName !== undefined ) {
  39569. for ( const trackName in bindingByName ) {
  39570. const binding = bindingByName[ trackName ];
  39571. binding.restoreOriginalState();
  39572. this._removeInactiveBinding( binding );
  39573. }
  39574. }
  39575. }
  39576. /**
  39577. * Deallocates all memory resources for an action. The action is identified by the
  39578. * given clip and an optional root object. Before using this method make
  39579. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39580. *
  39581. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39582. * @param {Object3D} [optionalRoot] - An alternative root object.
  39583. */
  39584. uncacheAction( clip, optionalRoot ) {
  39585. const action = this.existingAction( clip, optionalRoot );
  39586. if ( action !== null ) {
  39587. this._deactivateAction( action );
  39588. this._removeInactiveAction( action );
  39589. }
  39590. }
  39591. }
  39592. /**
  39593. * Represents a 3D render target.
  39594. *
  39595. * @augments RenderTarget
  39596. */
  39597. class RenderTarget3D extends RenderTarget {
  39598. /**
  39599. * Constructs a new 3D render target.
  39600. *
  39601. * @param {number} [width=1] - The width of the render target.
  39602. * @param {number} [height=1] - The height of the render target.
  39603. * @param {number} [depth=1] - The height of the render target.
  39604. * @param {RenderTarget~Options} [options] - The configuration object.
  39605. */
  39606. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39607. super( width, height, options );
  39608. /**
  39609. * This flag can be used for type testing.
  39610. *
  39611. * @type {boolean}
  39612. * @readonly
  39613. * @default true
  39614. */
  39615. this.isRenderTarget3D = true;
  39616. this.depth = depth;
  39617. /**
  39618. * Overwritten with a different texture type.
  39619. *
  39620. * @type {Data3DTexture}
  39621. */
  39622. this.texture = new Data3DTexture( null, width, height, depth );
  39623. this._setTextureOptions( options );
  39624. this.texture.isRenderTargetTexture = true;
  39625. }
  39626. }
  39627. /**
  39628. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39629. *
  39630. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39631. * ```js
  39632. * uniforms: {
  39633. * time: { value: 1.0 },
  39634. * resolution: new Uniform( new Vector2() )
  39635. * };
  39636. * ```
  39637. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39638. * in {@link WebGLRenderer}.
  39639. */
  39640. class Uniform {
  39641. /**
  39642. * Constructs a new uniform.
  39643. *
  39644. * @param {any} value - The uniform value.
  39645. */
  39646. constructor( value ) {
  39647. /**
  39648. * The uniform value.
  39649. *
  39650. * @type {any}
  39651. */
  39652. this.value = value;
  39653. }
  39654. /**
  39655. * Returns a new uniform with copied values from this instance.
  39656. * If the value has a `clone()` method, the value is cloned as well.
  39657. *
  39658. * @return {Uniform} A clone of this instance.
  39659. */
  39660. clone() {
  39661. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39662. }
  39663. }
  39664. let _id$1 = 0;
  39665. /**
  39666. * A class for managing multiple uniforms in a single group. The renderer will process
  39667. * such a definition as a single UBO.
  39668. *
  39669. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39670. * in {@link WebGLRenderer}.
  39671. *
  39672. * @augments EventDispatcher
  39673. */
  39674. class UniformsGroup extends EventDispatcher {
  39675. /**
  39676. * Constructs a new uniforms group.
  39677. */
  39678. constructor() {
  39679. super();
  39680. /**
  39681. * This flag can be used for type testing.
  39682. *
  39683. * @type {boolean}
  39684. * @readonly
  39685. * @default true
  39686. */
  39687. this.isUniformsGroup = true;
  39688. /**
  39689. * The ID of the 3D object.
  39690. *
  39691. * @name UniformsGroup#id
  39692. * @type {number}
  39693. * @readonly
  39694. */
  39695. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39696. /**
  39697. * The name of the uniforms group.
  39698. *
  39699. * @type {string}
  39700. */
  39701. this.name = '';
  39702. /**
  39703. * The buffer usage.
  39704. *
  39705. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39706. * @default StaticDrawUsage
  39707. */
  39708. this.usage = StaticDrawUsage;
  39709. /**
  39710. * An array holding the uniforms.
  39711. *
  39712. * @type {Array<Uniform>}
  39713. */
  39714. this.uniforms = [];
  39715. }
  39716. /**
  39717. * Adds the given uniform to this uniforms group.
  39718. *
  39719. * @param {Uniform} uniform - The uniform to add.
  39720. * @return {UniformsGroup} A reference to this uniforms group.
  39721. */
  39722. add( uniform ) {
  39723. this.uniforms.push( uniform );
  39724. return this;
  39725. }
  39726. /**
  39727. * Removes the given uniform from this uniforms group.
  39728. *
  39729. * @param {Uniform} uniform - The uniform to remove.
  39730. * @return {UniformsGroup} A reference to this uniforms group.
  39731. */
  39732. remove( uniform ) {
  39733. const index = this.uniforms.indexOf( uniform );
  39734. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39735. return this;
  39736. }
  39737. /**
  39738. * Sets the name of this uniforms group.
  39739. *
  39740. * @param {string} name - The name to set.
  39741. * @return {UniformsGroup} A reference to this uniforms group.
  39742. */
  39743. setName( name ) {
  39744. this.name = name;
  39745. return this;
  39746. }
  39747. /**
  39748. * Sets the usage of this uniforms group.
  39749. *
  39750. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39751. * @return {UniformsGroup} A reference to this uniforms group.
  39752. */
  39753. setUsage( value ) {
  39754. this.usage = value;
  39755. return this;
  39756. }
  39757. /**
  39758. * Frees the GPU-related resources allocated by this instance. Call this
  39759. * method whenever this instance is no longer used in your app.
  39760. *
  39761. * @fires Texture#dispose
  39762. */
  39763. dispose() {
  39764. this.dispatchEvent( { type: 'dispose' } );
  39765. }
  39766. /**
  39767. * Copies the values of the given uniforms group to this instance.
  39768. *
  39769. * @param {UniformsGroup} source - The uniforms group to copy.
  39770. * @return {UniformsGroup} A reference to this uniforms group.
  39771. */
  39772. copy( source ) {
  39773. this.name = source.name;
  39774. this.usage = source.usage;
  39775. const uniformsSource = source.uniforms;
  39776. this.uniforms.length = 0;
  39777. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39778. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39779. for ( let j = 0; j < uniforms.length; j ++ ) {
  39780. this.uniforms.push( uniforms[ j ].clone() );
  39781. }
  39782. }
  39783. return this;
  39784. }
  39785. /**
  39786. * Returns a new uniforms group with copied values from this instance.
  39787. *
  39788. * @return {UniformsGroup} A clone of this instance.
  39789. */
  39790. clone() {
  39791. return new this.constructor().copy( this );
  39792. }
  39793. }
  39794. /**
  39795. * An instanced version of an interleaved buffer.
  39796. *
  39797. * @augments InterleavedBuffer
  39798. */
  39799. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39800. /**
  39801. * Constructs a new instanced interleaved buffer.
  39802. *
  39803. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39804. * @param {number} stride - The number of typed-array elements per vertex.
  39805. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39806. */
  39807. constructor( array, stride, meshPerAttribute = 1 ) {
  39808. super( array, stride );
  39809. /**
  39810. * This flag can be used for type testing.
  39811. *
  39812. * @type {boolean}
  39813. * @readonly
  39814. * @default true
  39815. */
  39816. this.isInstancedInterleavedBuffer = true;
  39817. /**
  39818. * Defines how often a value of this buffer attribute should be repeated,
  39819. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39820. *
  39821. * @type {number}
  39822. * @default 1
  39823. */
  39824. this.meshPerAttribute = meshPerAttribute;
  39825. }
  39826. copy( source ) {
  39827. super.copy( source );
  39828. this.meshPerAttribute = source.meshPerAttribute;
  39829. return this;
  39830. }
  39831. clone( data ) {
  39832. const ib = super.clone( data );
  39833. ib.meshPerAttribute = this.meshPerAttribute;
  39834. return ib;
  39835. }
  39836. toJSON( data ) {
  39837. const json = super.toJSON( data );
  39838. json.isInstancedInterleavedBuffer = true;
  39839. json.meshPerAttribute = this.meshPerAttribute;
  39840. return json;
  39841. }
  39842. }
  39843. /**
  39844. * An alternative version of a buffer attribute with more control over the VBO.
  39845. *
  39846. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39847. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39848. *
  39849. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39850. * or even produces the VBOs in question.
  39851. *
  39852. * Notice that this class can only be used with {@link WebGLRenderer}.
  39853. */
  39854. class GLBufferAttribute {
  39855. /**
  39856. * Constructs a new GL buffer attribute.
  39857. *
  39858. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39859. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39860. * @param {number} itemSize - The item size.
  39861. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39862. * @param {number} count - The expected number of vertices in VBO.
  39863. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39864. */
  39865. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39866. /**
  39867. * This flag can be used for type testing.
  39868. *
  39869. * @type {boolean}
  39870. * @readonly
  39871. * @default true
  39872. */
  39873. this.isGLBufferAttribute = true;
  39874. /**
  39875. * The name of the buffer attribute.
  39876. *
  39877. * @type {string}
  39878. */
  39879. this.name = '';
  39880. /**
  39881. * The native WebGL buffer.
  39882. *
  39883. * @type {WebGLBuffer}
  39884. */
  39885. this.buffer = buffer;
  39886. /**
  39887. * The native data type.
  39888. *
  39889. * @type {number}
  39890. */
  39891. this.type = type;
  39892. /**
  39893. * The item size, see {@link BufferAttribute#itemSize}.
  39894. *
  39895. * @type {number}
  39896. */
  39897. this.itemSize = itemSize;
  39898. /**
  39899. * The corresponding size (in bytes) for the given `type` parameter.
  39900. *
  39901. * @type {number}
  39902. */
  39903. this.elementSize = elementSize;
  39904. /**
  39905. * The expected number of vertices in VBO.
  39906. *
  39907. * @type {number}
  39908. */
  39909. this.count = count;
  39910. /**
  39911. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39912. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39913. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39914. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39915. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39916. *
  39917. * @type {boolean}
  39918. */
  39919. this.normalized = normalized;
  39920. /**
  39921. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39922. *
  39923. * @type {number}
  39924. */
  39925. this.version = 0;
  39926. }
  39927. /**
  39928. * Flag to indicate that this attribute has changed and should be re-sent to
  39929. * the GPU. Set this to `true` when you modify the value of the array.
  39930. *
  39931. * @type {number}
  39932. * @default false
  39933. * @param {boolean} value
  39934. */
  39935. set needsUpdate( value ) {
  39936. if ( value === true ) this.version ++;
  39937. }
  39938. /**
  39939. * Sets the given native WebGL buffer.
  39940. *
  39941. * @param {WebGLBuffer} buffer - The buffer to set.
  39942. * @return {BufferAttribute} A reference to this instance.
  39943. */
  39944. setBuffer( buffer ) {
  39945. this.buffer = buffer;
  39946. return this;
  39947. }
  39948. /**
  39949. * Sets the given native data type and element size.
  39950. *
  39951. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39952. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39953. * @return {BufferAttribute} A reference to this instance.
  39954. */
  39955. setType( type, elementSize ) {
  39956. this.type = type;
  39957. this.elementSize = elementSize;
  39958. return this;
  39959. }
  39960. /**
  39961. * Sets the item size.
  39962. *
  39963. * @param {number} itemSize - The item size.
  39964. * @return {BufferAttribute} A reference to this instance.
  39965. */
  39966. setItemSize( itemSize ) {
  39967. this.itemSize = itemSize;
  39968. return this;
  39969. }
  39970. /**
  39971. * Sets the count (the expected number of vertices in VBO).
  39972. *
  39973. * @param {number} count - The count.
  39974. * @return {BufferAttribute} A reference to this instance.
  39975. */
  39976. setCount( count ) {
  39977. this.count = count;
  39978. return this;
  39979. }
  39980. }
  39981. const _matrix = /*@__PURE__*/ new Matrix4();
  39982. /**
  39983. * This class is designed to assist with raycasting. Raycasting is used for
  39984. * mouse picking (working out what objects in the 3d space the mouse is over)
  39985. * amongst other things.
  39986. */
  39987. class Raycaster {
  39988. /**
  39989. * Constructs a new raycaster.
  39990. *
  39991. * @param {Vector3} origin - The origin vector where the ray casts from.
  39992. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39993. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39994. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39995. */
  39996. constructor( origin, direction, near = 0, far = Infinity ) {
  39997. /**
  39998. * The ray used for raycasting.
  39999. *
  40000. * @type {Ray}
  40001. */
  40002. this.ray = new Ray( origin, direction );
  40003. /**
  40004. * All results returned are further away than near. Near can't be negative.
  40005. *
  40006. * @type {number}
  40007. * @default 0
  40008. */
  40009. this.near = near;
  40010. /**
  40011. * All results returned are closer than far. Far can't be lower than near.
  40012. *
  40013. * @type {number}
  40014. * @default Infinity
  40015. */
  40016. this.far = far;
  40017. /**
  40018. * The camera to use when raycasting against view-dependent objects such as
  40019. * billboarded objects like sprites. This field can be set manually or
  40020. * is set when calling `setFromCamera()`.
  40021. *
  40022. * @type {?Camera}
  40023. * @default null
  40024. */
  40025. this.camera = null;
  40026. /**
  40027. * Allows to selectively ignore 3D objects when performing intersection tests.
  40028. * The following code example ensures that only 3D objects on layer `1` will be
  40029. * honored by raycaster.
  40030. * ```js
  40031. * raycaster.layers.set( 1 );
  40032. * object.layers.enable( 1 );
  40033. * ```
  40034. *
  40035. * @type {Layers}
  40036. */
  40037. this.layers = new Layers();
  40038. /**
  40039. * A parameter object that configures the raycasting. It has the structure:
  40040. *
  40041. * ```
  40042. * {
  40043. * Mesh: {},
  40044. * Line: { threshold: 1 },
  40045. * LOD: {},
  40046. * Points: { threshold: 1 },
  40047. * Sprite: {}
  40048. * }
  40049. * ```
  40050. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  40051. *
  40052. * @type {Object}
  40053. */
  40054. this.params = {
  40055. Mesh: {},
  40056. Line: { threshold: 1 },
  40057. LOD: {},
  40058. Points: { threshold: 1 },
  40059. Sprite: {}
  40060. };
  40061. }
  40062. /**
  40063. * Updates the ray with a new origin and direction by copying the values from the arguments.
  40064. *
  40065. * @param {Vector3} origin - The origin vector where the ray casts from.
  40066. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  40067. */
  40068. set( origin, direction ) {
  40069. // direction is assumed to be normalized (for accurate distance calculations)
  40070. this.ray.set( origin, direction );
  40071. }
  40072. /**
  40073. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  40074. *
  40075. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  40076. * X and Y components should be between `-1` and `1`.
  40077. * @param {Camera} camera - The camera from which the ray should originate.
  40078. */
  40079. setFromCamera( coords, camera ) {
  40080. if ( camera.isPerspectiveCamera ) {
  40081. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  40082. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  40083. this.camera = camera;
  40084. } else if ( camera.isOrthographicCamera ) {
  40085. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  40086. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  40087. this.camera = camera;
  40088. } else {
  40089. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  40090. }
  40091. }
  40092. /**
  40093. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  40094. *
  40095. * @param {WebXRController} controller - The controller to copy the position and direction from.
  40096. * @return {Raycaster} A reference to this raycaster.
  40097. */
  40098. setFromXRController( controller ) {
  40099. _matrix.identity().extractRotation( controller.matrixWorld );
  40100. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  40101. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  40102. return this;
  40103. }
  40104. /**
  40105. * The intersection point of a raycaster intersection test.
  40106. * @typedef {Object} Raycaster~Intersection
  40107. * @property {number} distance - The distance from the ray's origin to the intersection point.
  40108. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  40109. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  40110. * @property {Vector3} point - The intersection point, in world coordinates.
  40111. * @property {Object} face - The face that has been intersected.
  40112. * @property {number} faceIndex - The face index.
  40113. * @property {Object3D} object - The 3D object that has been intersected.
  40114. * @property {Vector2} uv - U,V coordinates at point of intersection.
  40115. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  40116. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  40117. * @property {number} instanceId - The index number of the instance where the ray
  40118. * intersects the {@link InstancedMesh}.
  40119. */
  40120. /**
  40121. * Checks all intersection between the ray and the object with or without the
  40122. * descendants. Intersections are returned sorted by distance, closest first.
  40123. *
  40124. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  40125. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  40126. * differently to ray casting than lines or points.
  40127. *
  40128. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  40129. * to be detected; intersections of the ray passing through the back of a face will not
  40130. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  40131. * to `THREE.DoubleSide`.
  40132. *
  40133. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  40134. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40135. * Otherwise it only checks intersection with the object.
  40136. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40137. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40138. */
  40139. intersectObject( object, recursive = true, intersects = [] ) {
  40140. intersect( object, this, intersects, recursive );
  40141. intersects.sort( ascSort );
  40142. return intersects;
  40143. }
  40144. /**
  40145. * Checks all intersection between the ray and the objects with or without
  40146. * the descendants. Intersections are returned sorted by distance, closest first.
  40147. *
  40148. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  40149. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  40150. * Otherwise it only checks intersection with the object.
  40151. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  40152. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  40153. */
  40154. intersectObjects( objects, recursive = true, intersects = [] ) {
  40155. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  40156. intersect( objects[ i ], this, intersects, recursive );
  40157. }
  40158. intersects.sort( ascSort );
  40159. return intersects;
  40160. }
  40161. }
  40162. function ascSort( a, b ) {
  40163. return a.distance - b.distance;
  40164. }
  40165. function intersect( object, raycaster, intersects, recursive ) {
  40166. let propagate = true;
  40167. if ( object.layers.test( raycaster.layers ) ) {
  40168. const result = object.raycast( raycaster, intersects );
  40169. if ( result === false ) propagate = false;
  40170. }
  40171. if ( propagate === true && recursive === true ) {
  40172. const children = object.children;
  40173. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40174. intersect( children[ i ], raycaster, intersects, true );
  40175. }
  40176. }
  40177. }
  40178. /**
  40179. * This class is an alternative to {@link Clock} with a different API design and behavior.
  40180. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  40181. *
  40182. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  40183. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  40184. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  40185. * is inactive (e.g. tab switched or browser hidden).
  40186. *
  40187. * ```js
  40188. * const timer = new Timer();
  40189. * timer.connect( document ); // use Page Visibility API
  40190. * ```
  40191. */
  40192. class Timer {
  40193. /**
  40194. * Constructs a new timer.
  40195. */
  40196. constructor() {
  40197. this._previousTime = 0;
  40198. this._currentTime = 0;
  40199. this._startTime = performance.now();
  40200. this._delta = 0;
  40201. this._elapsed = 0;
  40202. this._timescale = 1;
  40203. this._document = null;
  40204. this._pageVisibilityHandler = null;
  40205. }
  40206. /**
  40207. * Connect the timer to the given document.Calling this method is not mandatory to
  40208. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40209. * delta values.
  40210. *
  40211. * @param {Document} document - The document.
  40212. */
  40213. connect( document ) {
  40214. this._document = document;
  40215. // use Page Visibility API to avoid large time delta values
  40216. if ( document.hidden !== undefined ) {
  40217. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40218. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40219. }
  40220. }
  40221. /**
  40222. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40223. */
  40224. disconnect() {
  40225. if ( this._pageVisibilityHandler !== null ) {
  40226. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40227. this._pageVisibilityHandler = null;
  40228. }
  40229. this._document = null;
  40230. }
  40231. /**
  40232. * Returns the time delta in seconds.
  40233. *
  40234. * @return {number} The time delta in second.
  40235. */
  40236. getDelta() {
  40237. return this._delta / 1000;
  40238. }
  40239. /**
  40240. * Returns the elapsed time in seconds.
  40241. *
  40242. * @return {number} The elapsed time in second.
  40243. */
  40244. getElapsed() {
  40245. return this._elapsed / 1000;
  40246. }
  40247. /**
  40248. * Returns the timescale.
  40249. *
  40250. * @return {number} The timescale.
  40251. */
  40252. getTimescale() {
  40253. return this._timescale;
  40254. }
  40255. /**
  40256. * Sets the given timescale which scale the time delta computation
  40257. * in `update()`.
  40258. *
  40259. * @param {number} timescale - The timescale to set.
  40260. * @return {Timer} A reference to this timer.
  40261. */
  40262. setTimescale( timescale ) {
  40263. this._timescale = timescale;
  40264. return this;
  40265. }
  40266. /**
  40267. * Resets the time computation for the current simulation step.
  40268. *
  40269. * @return {Timer} A reference to this timer.
  40270. */
  40271. reset() {
  40272. this._currentTime = performance.now() - this._startTime;
  40273. return this;
  40274. }
  40275. /**
  40276. * Can be used to free all internal resources. Usually called when
  40277. * the timer instance isn't required anymore.
  40278. */
  40279. dispose() {
  40280. this.disconnect();
  40281. }
  40282. /**
  40283. * Updates the internal state of the timer. This method should be called
  40284. * once per simulation step and before you perform queries against the timer
  40285. * (e.g. via `getDelta()`).
  40286. *
  40287. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40288. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40289. * time will be determined with `performance.now`.
  40290. * @return {Timer} A reference to this timer.
  40291. */
  40292. update( timestamp ) {
  40293. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40294. this._delta = 0;
  40295. } else {
  40296. this._previousTime = this._currentTime;
  40297. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40298. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40299. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40300. }
  40301. return this;
  40302. }
  40303. }
  40304. function handleVisibilityChange() {
  40305. if ( this._document.hidden === false ) this.reset();
  40306. }
  40307. /**
  40308. * This class can be used to represent points in 3D space as
  40309. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40310. */
  40311. class Spherical {
  40312. /**
  40313. * Constructs a new spherical.
  40314. *
  40315. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40316. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40317. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40318. */
  40319. constructor( radius = 1, phi = 0, theta = 0 ) {
  40320. /**
  40321. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40322. *
  40323. * @type {number}
  40324. * @default 1
  40325. */
  40326. this.radius = radius;
  40327. /**
  40328. * The polar angle in radians from the y (up) axis.
  40329. *
  40330. * @type {number}
  40331. * @default 0
  40332. */
  40333. this.phi = phi;
  40334. /**
  40335. * The equator/azimuthal angle in radians around the y (up) axis.
  40336. *
  40337. * @type {number}
  40338. * @default 0
  40339. */
  40340. this.theta = theta;
  40341. }
  40342. /**
  40343. * Sets the spherical components by copying the given values.
  40344. *
  40345. * @param {number} radius - The radius.
  40346. * @param {number} phi - The polar angle.
  40347. * @param {number} theta - The azimuthal angle.
  40348. * @return {Spherical} A reference to this spherical.
  40349. */
  40350. set( radius, phi, theta ) {
  40351. this.radius = radius;
  40352. this.phi = phi;
  40353. this.theta = theta;
  40354. return this;
  40355. }
  40356. /**
  40357. * Copies the values of the given spherical to this instance.
  40358. *
  40359. * @param {Spherical} other - The spherical to copy.
  40360. * @return {Spherical} A reference to this spherical.
  40361. */
  40362. copy( other ) {
  40363. this.radius = other.radius;
  40364. this.phi = other.phi;
  40365. this.theta = other.theta;
  40366. return this;
  40367. }
  40368. /**
  40369. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40370. * `0.000001`.
  40371. *
  40372. * @return {Spherical} A reference to this spherical.
  40373. */
  40374. makeSafe() {
  40375. const EPS = 0.000001;
  40376. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40377. return this;
  40378. }
  40379. /**
  40380. * Sets the spherical components from the given vector which is assumed to hold
  40381. * Cartesian coordinates.
  40382. *
  40383. * @param {Vector3} v - The vector to set.
  40384. * @return {Spherical} A reference to this spherical.
  40385. */
  40386. setFromVector3( v ) {
  40387. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40388. }
  40389. /**
  40390. * Sets the spherical components from the given Cartesian coordinates.
  40391. *
  40392. * @param {number} x - The x value.
  40393. * @param {number} y - The y value.
  40394. * @param {number} z - The z value.
  40395. * @return {Spherical} A reference to this spherical.
  40396. */
  40397. setFromCartesianCoords( x, y, z ) {
  40398. this.radius = Math.sqrt( x * x + y * y + z * z );
  40399. if ( this.radius === 0 ) {
  40400. this.theta = 0;
  40401. this.phi = 0;
  40402. } else {
  40403. this.theta = Math.atan2( x, z );
  40404. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40405. }
  40406. return this;
  40407. }
  40408. /**
  40409. * Returns a new spherical with copied values from this instance.
  40410. *
  40411. * @return {Spherical} A clone of this instance.
  40412. */
  40413. clone() {
  40414. return new this.constructor().copy( this );
  40415. }
  40416. }
  40417. /**
  40418. * This class can be used to represent points in 3D space as
  40419. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40420. */
  40421. class Cylindrical {
  40422. /**
  40423. * Constructs a new cylindrical.
  40424. *
  40425. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40426. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40427. * @param {number} [y=0] - The height above the x-z plane.
  40428. */
  40429. constructor( radius = 1, theta = 0, y = 0 ) {
  40430. /**
  40431. * The distance from the origin to a point in the x-z plane.
  40432. *
  40433. * @type {number}
  40434. * @default 1
  40435. */
  40436. this.radius = radius;
  40437. /**
  40438. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40439. *
  40440. * @type {number}
  40441. * @default 0
  40442. */
  40443. this.theta = theta;
  40444. /**
  40445. * The height above the x-z plane.
  40446. *
  40447. * @type {number}
  40448. * @default 0
  40449. */
  40450. this.y = y;
  40451. }
  40452. /**
  40453. * Sets the cylindrical components by copying the given values.
  40454. *
  40455. * @param {number} radius - The radius.
  40456. * @param {number} theta - The theta angle.
  40457. * @param {number} y - The height value.
  40458. * @return {Cylindrical} A reference to this cylindrical.
  40459. */
  40460. set( radius, theta, y ) {
  40461. this.radius = radius;
  40462. this.theta = theta;
  40463. this.y = y;
  40464. return this;
  40465. }
  40466. /**
  40467. * Copies the values of the given cylindrical to this instance.
  40468. *
  40469. * @param {Cylindrical} other - The cylindrical to copy.
  40470. * @return {Cylindrical} A reference to this cylindrical.
  40471. */
  40472. copy( other ) {
  40473. this.radius = other.radius;
  40474. this.theta = other.theta;
  40475. this.y = other.y;
  40476. return this;
  40477. }
  40478. /**
  40479. * Sets the cylindrical components from the given vector which is assumed to hold
  40480. * Cartesian coordinates.
  40481. *
  40482. * @param {Vector3} v - The vector to set.
  40483. * @return {Cylindrical} A reference to this cylindrical.
  40484. */
  40485. setFromVector3( v ) {
  40486. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40487. }
  40488. /**
  40489. * Sets the cylindrical components from the given Cartesian coordinates.
  40490. *
  40491. * @param {number} x - The x value.
  40492. * @param {number} y - The x value.
  40493. * @param {number} z - The x value.
  40494. * @return {Cylindrical} A reference to this cylindrical.
  40495. */
  40496. setFromCartesianCoords( x, y, z ) {
  40497. this.radius = Math.sqrt( x * x + z * z );
  40498. this.theta = Math.atan2( x, z );
  40499. this.y = y;
  40500. return this;
  40501. }
  40502. /**
  40503. * Returns a new cylindrical with copied values from this instance.
  40504. *
  40505. * @return {Cylindrical} A clone of this instance.
  40506. */
  40507. clone() {
  40508. return new this.constructor().copy( this );
  40509. }
  40510. }
  40511. /**
  40512. * Represents a 2x2 matrix.
  40513. *
  40514. * A Note on Row-Major and Column-Major Ordering:
  40515. *
  40516. * The constructor and {@link Matrix2#set} method take arguments in
  40517. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40518. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40519. * This means that calling:
  40520. * ```js
  40521. * const m = new THREE.Matrix2();
  40522. * m.set( 11, 12,
  40523. * 21, 22 );
  40524. * ```
  40525. * will result in the elements array containing:
  40526. * ```js
  40527. * m.elements = [ 11, 21,
  40528. * 12, 22 ];
  40529. * ```
  40530. * and internally all calculations are performed using column-major ordering.
  40531. * However, as the actual ordering makes no difference mathematically and
  40532. * most people are used to thinking about matrices in row-major order, the
  40533. * three.js documentation shows matrices in row-major order. Just bear in
  40534. * mind that if you are reading the source code, you'll have to take the
  40535. * transpose of any matrices outlined here to make sense of the calculations.
  40536. */
  40537. class Matrix2 {
  40538. /**
  40539. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40540. * in row-major order. If no arguments are provided, the constructor
  40541. * initializes the matrix as an identity matrix.
  40542. *
  40543. * @param {number} [n11] - 1-1 matrix element.
  40544. * @param {number} [n12] - 1-2 matrix element.
  40545. * @param {number} [n21] - 2-1 matrix element.
  40546. * @param {number} [n22] - 2-2 matrix element.
  40547. */
  40548. constructor( n11, n12, n21, n22 ) {
  40549. /**
  40550. * This flag can be used for type testing.
  40551. *
  40552. * @type {boolean}
  40553. * @readonly
  40554. * @default true
  40555. */
  40556. Matrix2.prototype.isMatrix2 = true;
  40557. /**
  40558. * A column-major list of matrix values.
  40559. *
  40560. * @type {Array<number>}
  40561. */
  40562. this.elements = [
  40563. 1, 0,
  40564. 0, 1,
  40565. ];
  40566. if ( n11 !== undefined ) {
  40567. this.set( n11, n12, n21, n22 );
  40568. }
  40569. }
  40570. /**
  40571. * Sets this matrix to the 2x2 identity matrix.
  40572. *
  40573. * @return {Matrix2} A reference to this matrix.
  40574. */
  40575. identity() {
  40576. this.set(
  40577. 1, 0,
  40578. 0, 1,
  40579. );
  40580. return this;
  40581. }
  40582. /**
  40583. * Sets the elements of the matrix from the given array.
  40584. *
  40585. * @param {Array<number>} array - The matrix elements in column-major order.
  40586. * @param {number} [offset=0] - Index of the first element in the array.
  40587. * @return {Matrix2} A reference to this matrix.
  40588. */
  40589. fromArray( array, offset = 0 ) {
  40590. for ( let i = 0; i < 4; i ++ ) {
  40591. this.elements[ i ] = array[ i + offset ];
  40592. }
  40593. return this;
  40594. }
  40595. /**
  40596. * Sets the elements of the matrix.The arguments are supposed to be
  40597. * in row-major order.
  40598. *
  40599. * @param {number} n11 - 1-1 matrix element.
  40600. * @param {number} n12 - 1-2 matrix element.
  40601. * @param {number} n21 - 2-1 matrix element.
  40602. * @param {number} n22 - 2-2 matrix element.
  40603. * @return {Matrix2} A reference to this matrix.
  40604. */
  40605. set( n11, n12, n21, n22 ) {
  40606. const te = this.elements;
  40607. te[ 0 ] = n11; te[ 2 ] = n12;
  40608. te[ 1 ] = n21; te[ 3 ] = n22;
  40609. return this;
  40610. }
  40611. }
  40612. const _vector$4 = /*@__PURE__*/ new Vector2();
  40613. /**
  40614. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40615. */
  40616. class Box2 {
  40617. /**
  40618. * Constructs a new bounding box.
  40619. *
  40620. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40621. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40622. */
  40623. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40624. /**
  40625. * This flag can be used for type testing.
  40626. *
  40627. * @type {boolean}
  40628. * @readonly
  40629. * @default true
  40630. */
  40631. this.isBox2 = true;
  40632. /**
  40633. * The lower boundary of the box.
  40634. *
  40635. * @type {Vector2}
  40636. */
  40637. this.min = min;
  40638. /**
  40639. * The upper boundary of the box.
  40640. *
  40641. * @type {Vector2}
  40642. */
  40643. this.max = max;
  40644. }
  40645. /**
  40646. * Sets the lower and upper boundaries of this box.
  40647. * Please note that this method only copies the values from the given objects.
  40648. *
  40649. * @param {Vector2} min - The lower boundary of the box.
  40650. * @param {Vector2} max - The upper boundary of the box.
  40651. * @return {Box2} A reference to this bounding box.
  40652. */
  40653. set( min, max ) {
  40654. this.min.copy( min );
  40655. this.max.copy( max );
  40656. return this;
  40657. }
  40658. /**
  40659. * Sets the upper and lower bounds of this box so it encloses the position data
  40660. * in the given array.
  40661. *
  40662. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40663. * @return {Box2} A reference to this bounding box.
  40664. */
  40665. setFromPoints( points ) {
  40666. this.makeEmpty();
  40667. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40668. this.expandByPoint( points[ i ] );
  40669. }
  40670. return this;
  40671. }
  40672. /**
  40673. * Centers this box on the given center vector and sets this box's width, height and
  40674. * depth to the given size values.
  40675. *
  40676. * @param {Vector2} center - The center of the box.
  40677. * @param {Vector2} size - The x and y dimensions of the box.
  40678. * @return {Box2} A reference to this bounding box.
  40679. */
  40680. setFromCenterAndSize( center, size ) {
  40681. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40682. this.min.copy( center ).sub( halfSize );
  40683. this.max.copy( center ).add( halfSize );
  40684. return this;
  40685. }
  40686. /**
  40687. * Returns a new box with copied values from this instance.
  40688. *
  40689. * @return {Box2} A clone of this instance.
  40690. */
  40691. clone() {
  40692. return new this.constructor().copy( this );
  40693. }
  40694. /**
  40695. * Copies the values of the given box to this instance.
  40696. *
  40697. * @param {Box2} box - The box to copy.
  40698. * @return {Box2} A reference to this bounding box.
  40699. */
  40700. copy( box ) {
  40701. this.min.copy( box.min );
  40702. this.max.copy( box.max );
  40703. return this;
  40704. }
  40705. /**
  40706. * Makes this box empty which means in encloses a zero space in 2D.
  40707. *
  40708. * @return {Box2} A reference to this bounding box.
  40709. */
  40710. makeEmpty() {
  40711. this.min.x = this.min.y = + Infinity;
  40712. this.max.x = this.max.y = - Infinity;
  40713. return this;
  40714. }
  40715. /**
  40716. * Returns true if this box includes zero points within its bounds.
  40717. * Note that a box with equal lower and upper bounds still includes one
  40718. * point, the one both bounds share.
  40719. *
  40720. * @return {boolean} Whether this box is empty or not.
  40721. */
  40722. isEmpty() {
  40723. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40724. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40725. }
  40726. /**
  40727. * Returns the center point of this box.
  40728. *
  40729. * @param {Vector2} target - The target vector that is used to store the method's result.
  40730. * @return {Vector2} The center point.
  40731. */
  40732. getCenter( target ) {
  40733. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40734. }
  40735. /**
  40736. * Returns the dimensions of this box.
  40737. *
  40738. * @param {Vector2} target - The target vector that is used to store the method's result.
  40739. * @return {Vector2} The size.
  40740. */
  40741. getSize( target ) {
  40742. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40743. }
  40744. /**
  40745. * Expands the boundaries of this box to include the given point.
  40746. *
  40747. * @param {Vector2} point - The point that should be included by the bounding box.
  40748. * @return {Box2} A reference to this bounding box.
  40749. */
  40750. expandByPoint( point ) {
  40751. this.min.min( point );
  40752. this.max.max( point );
  40753. return this;
  40754. }
  40755. /**
  40756. * Expands this box equilaterally by the given vector. The width of this
  40757. * box will be expanded by the x component of the vector in both
  40758. * directions. The height of this box will be expanded by the y component of
  40759. * the vector in both directions.
  40760. *
  40761. * @param {Vector2} vector - The vector that should expand the bounding box.
  40762. * @return {Box2} A reference to this bounding box.
  40763. */
  40764. expandByVector( vector ) {
  40765. this.min.sub( vector );
  40766. this.max.add( vector );
  40767. return this;
  40768. }
  40769. /**
  40770. * Expands each dimension of the box by the given scalar. If negative, the
  40771. * dimensions of the box will be contracted.
  40772. *
  40773. * @param {number} scalar - The scalar value that should expand the bounding box.
  40774. * @return {Box2} A reference to this bounding box.
  40775. */
  40776. expandByScalar( scalar ) {
  40777. this.min.addScalar( - scalar );
  40778. this.max.addScalar( scalar );
  40779. return this;
  40780. }
  40781. /**
  40782. * Returns `true` if the given point lies within or on the boundaries of this box.
  40783. *
  40784. * @param {Vector2} point - The point to test.
  40785. * @return {boolean} Whether the bounding box contains the given point or not.
  40786. */
  40787. containsPoint( point ) {
  40788. return point.x >= this.min.x && point.x <= this.max.x &&
  40789. point.y >= this.min.y && point.y <= this.max.y;
  40790. }
  40791. /**
  40792. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40793. * If this box and the given one are identical, this function also returns `true`.
  40794. *
  40795. * @param {Box2} box - The bounding box to test.
  40796. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40797. */
  40798. containsBox( box ) {
  40799. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40800. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40801. }
  40802. /**
  40803. * Returns a point as a proportion of this box's width and height.
  40804. *
  40805. * @param {Vector2} point - A point in 2D space.
  40806. * @param {Vector2} target - The target vector that is used to store the method's result.
  40807. * @return {Vector2} A point as a proportion of this box's width and height.
  40808. */
  40809. getParameter( point, target ) {
  40810. // This can potentially have a divide by zero if the box
  40811. // has a size dimension of 0.
  40812. return target.set(
  40813. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40814. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40815. );
  40816. }
  40817. /**
  40818. * Returns `true` if the given bounding box intersects with this bounding box.
  40819. *
  40820. * @param {Box2} box - The bounding box to test.
  40821. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40822. */
  40823. intersectsBox( box ) {
  40824. // using 4 splitting planes to rule out intersections
  40825. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40826. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40827. }
  40828. /**
  40829. * Clamps the given point within the bounds of this box.
  40830. *
  40831. * @param {Vector2} point - The point to clamp.
  40832. * @param {Vector2} target - The target vector that is used to store the method's result.
  40833. * @return {Vector2} The clamped point.
  40834. */
  40835. clampPoint( point, target ) {
  40836. return target.copy( point ).clamp( this.min, this.max );
  40837. }
  40838. /**
  40839. * Returns the euclidean distance from any edge of this box to the specified point. If
  40840. * the given point lies inside of this box, the distance will be `0`.
  40841. *
  40842. * @param {Vector2} point - The point to compute the distance to.
  40843. * @return {number} The euclidean distance.
  40844. */
  40845. distanceToPoint( point ) {
  40846. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40847. }
  40848. /**
  40849. * Computes the intersection of this bounding box and the given one, setting the upper
  40850. * bound of this box to the lesser of the two boxes' upper bounds and the
  40851. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40852. * there's no overlap, makes this box empty.
  40853. *
  40854. * @param {Box2} box - The bounding box to intersect with.
  40855. * @return {Box2} A reference to this bounding box.
  40856. */
  40857. intersect( box ) {
  40858. this.min.max( box.min );
  40859. this.max.min( box.max );
  40860. if ( this.isEmpty() ) this.makeEmpty();
  40861. return this;
  40862. }
  40863. /**
  40864. * Computes the union of this box and another and the given one, setting the upper
  40865. * bound of this box to the greater of the two boxes' upper bounds and the
  40866. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40867. *
  40868. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40869. * @return {Box2} A reference to this bounding box.
  40870. */
  40871. union( box ) {
  40872. this.min.min( box.min );
  40873. this.max.max( box.max );
  40874. return this;
  40875. }
  40876. /**
  40877. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40878. * effectively moving it in 2D space.
  40879. *
  40880. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40881. * @return {Box2} A reference to this bounding box.
  40882. */
  40883. translate( offset ) {
  40884. this.min.add( offset );
  40885. this.max.add( offset );
  40886. return this;
  40887. }
  40888. /**
  40889. * Returns `true` if this bounding box is equal with the given one.
  40890. *
  40891. * @param {Box2} box - The box to test for equality.
  40892. * @return {boolean} Whether this bounding box is equal with the given one.
  40893. */
  40894. equals( box ) {
  40895. return box.min.equals( this.min ) && box.max.equals( this.max );
  40896. }
  40897. }
  40898. const _startP = /*@__PURE__*/ new Vector3();
  40899. const _startEnd = /*@__PURE__*/ new Vector3();
  40900. const _d1 = /*@__PURE__*/ new Vector3();
  40901. const _d2 = /*@__PURE__*/ new Vector3();
  40902. const _r = /*@__PURE__*/ new Vector3();
  40903. const _c1 = /*@__PURE__*/ new Vector3();
  40904. const _c2 = /*@__PURE__*/ new Vector3();
  40905. /**
  40906. * An analytical line segment in 3D space represented by a start and end point.
  40907. */
  40908. class Line3 {
  40909. /**
  40910. * Constructs a new line segment.
  40911. *
  40912. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40913. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40914. */
  40915. constructor( start = new Vector3(), end = new Vector3() ) {
  40916. /**
  40917. * Start of the line segment.
  40918. *
  40919. * @type {Vector3}
  40920. */
  40921. this.start = start;
  40922. /**
  40923. * End of the line segment.
  40924. *
  40925. * @type {Vector3}
  40926. */
  40927. this.end = end;
  40928. }
  40929. /**
  40930. * Sets the start and end values by copying the given vectors.
  40931. *
  40932. * @param {Vector3} start - The start point.
  40933. * @param {Vector3} end - The end point.
  40934. * @return {Line3} A reference to this line segment.
  40935. */
  40936. set( start, end ) {
  40937. this.start.copy( start );
  40938. this.end.copy( end );
  40939. return this;
  40940. }
  40941. /**
  40942. * Copies the values of the given line segment to this instance.
  40943. *
  40944. * @param {Line3} line - The line segment to copy.
  40945. * @return {Line3} A reference to this line segment.
  40946. */
  40947. copy( line ) {
  40948. this.start.copy( line.start );
  40949. this.end.copy( line.end );
  40950. return this;
  40951. }
  40952. /**
  40953. * Returns the center of the line segment.
  40954. *
  40955. * @param {Vector3} target - The target vector that is used to store the method's result.
  40956. * @return {Vector3} The center point.
  40957. */
  40958. getCenter( target ) {
  40959. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40960. }
  40961. /**
  40962. * Returns the delta vector of the line segment's start and end point.
  40963. *
  40964. * @param {Vector3} target - The target vector that is used to store the method's result.
  40965. * @return {Vector3} The delta vector.
  40966. */
  40967. delta( target ) {
  40968. return target.subVectors( this.end, this.start );
  40969. }
  40970. /**
  40971. * Returns the squared Euclidean distance between the line' start and end point.
  40972. *
  40973. * @return {number} The squared Euclidean distance.
  40974. */
  40975. distanceSq() {
  40976. return this.start.distanceToSquared( this.end );
  40977. }
  40978. /**
  40979. * Returns the Euclidean distance between the line' start and end point.
  40980. *
  40981. * @return {number} The Euclidean distance.
  40982. */
  40983. distance() {
  40984. return this.start.distanceTo( this.end );
  40985. }
  40986. /**
  40987. * Returns a vector at a certain position along the line segment.
  40988. *
  40989. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40990. * @param {Vector3} target - The target vector that is used to store the method's result.
  40991. * @return {Vector3} The delta vector.
  40992. */
  40993. at( t, target ) {
  40994. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40995. }
  40996. /**
  40997. * Returns a point parameter based on the closest point as projected on the line segment.
  40998. *
  40999. * @param {Vector3} point - The point for which to return a point parameter.
  41000. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41001. * @return {number} The point parameter.
  41002. */
  41003. closestPointToPointParameter( point, clampToLine ) {
  41004. _startP.subVectors( point, this.start );
  41005. _startEnd.subVectors( this.end, this.start );
  41006. const startEnd2 = _startEnd.dot( _startEnd );
  41007. const startEnd_startP = _startEnd.dot( _startP );
  41008. let t = startEnd_startP / startEnd2;
  41009. if ( clampToLine ) {
  41010. t = clamp( t, 0, 1 );
  41011. }
  41012. return t;
  41013. }
  41014. /**
  41015. * Returns the closest point on the line for a given point.
  41016. *
  41017. * @param {Vector3} point - The point to compute the closest point on the line for.
  41018. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  41019. * @param {Vector3} target - The target vector that is used to store the method's result.
  41020. * @return {Vector3} The closest point on the line.
  41021. */
  41022. closestPointToPoint( point, clampToLine, target ) {
  41023. const t = this.closestPointToPointParameter( point, clampToLine );
  41024. return this.delta( target ).multiplyScalar( t ).add( this.start );
  41025. }
  41026. /**
  41027. * Returns the closest squared distance between this line segment and the given one.
  41028. *
  41029. * @param {Line3} line - The line segment to compute the closest squared distance to.
  41030. * @param {Vector3} [c1] - The closest point on this line segment.
  41031. * @param {Vector3} [c2] - The closest point on the given line segment.
  41032. * @return {number} The squared distance between this line segment and the given one.
  41033. */
  41034. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  41035. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  41036. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  41037. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  41038. // distance between between S1(s) and S2(t)
  41039. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  41040. let s, t;
  41041. const p1 = this.start;
  41042. const p2 = line.start;
  41043. const q1 = this.end;
  41044. const q2 = line.end;
  41045. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  41046. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  41047. _r.subVectors( p1, p2 );
  41048. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  41049. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  41050. const f = _d2.dot( _r );
  41051. // Check if either or both segments degenerate into points
  41052. if ( a <= EPSILON && e <= EPSILON ) {
  41053. // Both segments degenerate into points
  41054. c1.copy( p1 );
  41055. c2.copy( p2 );
  41056. c1.sub( c2 );
  41057. return c1.dot( c1 );
  41058. }
  41059. if ( a <= EPSILON ) {
  41060. // First segment degenerates into a point
  41061. s = 0;
  41062. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  41063. t = clamp( t, 0, 1 );
  41064. } else {
  41065. const c = _d1.dot( _r );
  41066. if ( e <= EPSILON ) {
  41067. // Second segment degenerates into a point
  41068. t = 0;
  41069. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  41070. } else {
  41071. // The general nondegenerate case starts here
  41072. const b = _d1.dot( _d2 );
  41073. const denom = a * e - b * b; // Always nonnegative
  41074. // If segments not parallel, compute closest point on L1 to L2 and
  41075. // clamp to segment S1. Else pick arbitrary s (here 0)
  41076. if ( denom !== 0 ) {
  41077. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  41078. } else {
  41079. s = 0;
  41080. }
  41081. // Compute point on L2 closest to S1(s) using
  41082. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  41083. t = ( b * s + f ) / e;
  41084. // If t in [0,1] done. Else clamp t, recompute s for the new value
  41085. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  41086. // and clamp s to [0, 1]
  41087. if ( t < 0 ) {
  41088. t = 0.;
  41089. s = clamp( - c / a, 0, 1 );
  41090. } else if ( t > 1 ) {
  41091. t = 1;
  41092. s = clamp( ( b - c ) / a, 0, 1 );
  41093. }
  41094. }
  41095. }
  41096. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  41097. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  41098. c1.sub( c2 );
  41099. return c1.dot( c1 );
  41100. }
  41101. /**
  41102. * Applies a 4x4 transformation matrix to this line segment.
  41103. *
  41104. * @param {Matrix4} matrix - The transformation matrix.
  41105. * @return {Line3} A reference to this line segment.
  41106. */
  41107. applyMatrix4( matrix ) {
  41108. this.start.applyMatrix4( matrix );
  41109. this.end.applyMatrix4( matrix );
  41110. return this;
  41111. }
  41112. /**
  41113. * Returns `true` if this line segment is equal with the given one.
  41114. *
  41115. * @param {Line3} line - The line segment to test for equality.
  41116. * @return {boolean} Whether this line segment is equal with the given one.
  41117. */
  41118. equals( line ) {
  41119. return line.start.equals( this.start ) && line.end.equals( this.end );
  41120. }
  41121. /**
  41122. * Returns a new line segment with copied values from this instance.
  41123. *
  41124. * @return {Line3} A clone of this instance.
  41125. */
  41126. clone() {
  41127. return new this.constructor().copy( this );
  41128. }
  41129. }
  41130. const _vector$3 = /*@__PURE__*/ new Vector3();
  41131. /**
  41132. * This displays a cone shaped helper object for a {@link SpotLight}.
  41133. *
  41134. * When the spot light or its target are transformed or light properties are
  41135. * changed, it's necessary to call the `update()` method of the respective helper.
  41136. *
  41137. * ```js
  41138. * const spotLight = new THREE.SpotLight( 0xffffff );
  41139. * spotLight.position.set( 10, 10, 10 );
  41140. * scene.add( spotLight );
  41141. *
  41142. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  41143. * scene.add( spotLightHelper );
  41144. * ```
  41145. *
  41146. * @augments Object3D
  41147. */
  41148. class SpotLightHelper extends Object3D {
  41149. /**
  41150. * Constructs a new spot light helper.
  41151. *
  41152. * @param {HemisphereLight} light - The light to be visualized.
  41153. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41154. * the color of the light.
  41155. */
  41156. constructor( light, color ) {
  41157. super();
  41158. /**
  41159. * The light being visualized.
  41160. *
  41161. * @type {SpotLight}
  41162. */
  41163. this.light = light;
  41164. this.matrixAutoUpdate = false;
  41165. /**
  41166. * The color parameter passed in the constructor.
  41167. * If not set, the helper will take the color of the light.
  41168. *
  41169. * @type {number|Color|string}
  41170. */
  41171. this.color = color;
  41172. this.type = 'SpotLightHelper';
  41173. const geometry = new BufferGeometry();
  41174. const positions = [
  41175. 0, 0, 0, 0, 0, 1,
  41176. 0, 0, 0, 1, 0, 1,
  41177. 0, 0, 0, -1, 0, 1,
  41178. 0, 0, 0, 0, 1, 1,
  41179. 0, 0, 0, 0, -1, 1
  41180. ];
  41181. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  41182. const p1 = ( i / l ) * Math.PI * 2;
  41183. const p2 = ( j / l ) * Math.PI * 2;
  41184. positions.push(
  41185. Math.cos( p1 ), Math.sin( p1 ), 1,
  41186. Math.cos( p2 ), Math.sin( p2 ), 1
  41187. );
  41188. }
  41189. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41190. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41191. this.cone = new LineSegments( geometry, material );
  41192. this.add( this.cone );
  41193. this.update();
  41194. }
  41195. /**
  41196. * Frees the GPU-related resources allocated by this instance. Call this
  41197. * method whenever this instance is no longer used in your app.
  41198. */
  41199. dispose() {
  41200. this.cone.geometry.dispose();
  41201. this.cone.material.dispose();
  41202. }
  41203. /**
  41204. * Updates the helper to match the position and direction of the
  41205. * light being visualized.
  41206. */
  41207. update() {
  41208. this.light.updateWorldMatrix( true, false );
  41209. this.light.target.updateWorldMatrix( true, false );
  41210. // update the local matrix based on the parent and light target transforms
  41211. if ( this.parent ) {
  41212. this.parent.updateWorldMatrix( true );
  41213. this.matrix
  41214. .copy( this.parent.matrixWorld )
  41215. .invert()
  41216. .multiply( this.light.matrixWorld );
  41217. } else {
  41218. this.matrix.copy( this.light.matrixWorld );
  41219. }
  41220. this.matrixWorld.copy( this.light.matrixWorld );
  41221. const coneLength = this.light.distance ? this.light.distance : 1000;
  41222. const coneWidth = coneLength * Math.tan( this.light.angle );
  41223. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41224. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41225. this.cone.lookAt( _vector$3 );
  41226. if ( this.color !== undefined ) {
  41227. this.cone.material.color.set( this.color );
  41228. } else {
  41229. this.cone.material.color.copy( this.light.color );
  41230. }
  41231. }
  41232. }
  41233. const _vector$2 = /*@__PURE__*/ new Vector3();
  41234. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41235. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41236. /**
  41237. * A helper object to assist with visualizing a {@link Skeleton}.
  41238. *
  41239. * ```js
  41240. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41241. * scene.add( helper );
  41242. * ```
  41243. *
  41244. * @augments LineSegments
  41245. */
  41246. class SkeletonHelper extends LineSegments {
  41247. /**
  41248. * Constructs a new skeleton helper.
  41249. *
  41250. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41251. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41252. */
  41253. constructor( object ) {
  41254. const bones = getBoneList( object );
  41255. const geometry = new BufferGeometry();
  41256. const vertices = [];
  41257. const colors = [];
  41258. for ( let i = 0; i < bones.length; i ++ ) {
  41259. const bone = bones[ i ];
  41260. if ( bone.parent && bone.parent.isBone ) {
  41261. vertices.push( 0, 0, 0 );
  41262. vertices.push( 0, 0, 0 );
  41263. colors.push( 0, 0, 0 );
  41264. colors.push( 0, 0, 0 );
  41265. }
  41266. }
  41267. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41268. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41269. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41270. super( geometry, material );
  41271. /**
  41272. * This flag can be used for type testing.
  41273. *
  41274. * @type {boolean}
  41275. * @readonly
  41276. * @default true
  41277. */
  41278. this.isSkeletonHelper = true;
  41279. this.type = 'SkeletonHelper';
  41280. /**
  41281. * The object being visualized.
  41282. *
  41283. * @type {Object3D}
  41284. */
  41285. this.root = object;
  41286. /**
  41287. * The list of bones that the helper visualizes.
  41288. *
  41289. * @type {Array<Bone>}
  41290. */
  41291. this.bones = bones;
  41292. this.matrix = object.matrixWorld;
  41293. this.matrixAutoUpdate = false;
  41294. // colors
  41295. const color1 = new Color( 0x0000ff );
  41296. const color2 = new Color( 0x00ff00 );
  41297. this.setColors( color1, color2 );
  41298. }
  41299. updateMatrixWorld( force ) {
  41300. const bones = this.bones;
  41301. const geometry = this.geometry;
  41302. const position = geometry.getAttribute( 'position' );
  41303. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41304. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41305. const bone = bones[ i ];
  41306. if ( bone.parent && bone.parent.isBone ) {
  41307. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41308. _vector$2.setFromMatrixPosition( _boneMatrix );
  41309. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41310. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41311. _vector$2.setFromMatrixPosition( _boneMatrix );
  41312. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41313. j += 2;
  41314. }
  41315. }
  41316. geometry.getAttribute( 'position' ).needsUpdate = true;
  41317. super.updateMatrixWorld( force );
  41318. }
  41319. /**
  41320. * Defines the colors of the helper.
  41321. *
  41322. * @param {Color} color1 - The first line color for each bone.
  41323. * @param {Color} color2 - The second line color for each bone.
  41324. * @return {SkeletonHelper} A reference to this helper.
  41325. */
  41326. setColors( color1, color2 ) {
  41327. const geometry = this.geometry;
  41328. const colorAttribute = geometry.getAttribute( 'color' );
  41329. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41330. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41331. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41332. }
  41333. colorAttribute.needsUpdate = true;
  41334. return this;
  41335. }
  41336. /**
  41337. * Frees the GPU-related resources allocated by this instance. Call this
  41338. * method whenever this instance is no longer used in your app.
  41339. */
  41340. dispose() {
  41341. this.geometry.dispose();
  41342. this.material.dispose();
  41343. }
  41344. }
  41345. function getBoneList( object ) {
  41346. const boneList = [];
  41347. if ( object.isBone === true ) {
  41348. boneList.push( object );
  41349. }
  41350. for ( let i = 0; i < object.children.length; i ++ ) {
  41351. boneList.push( ...getBoneList( object.children[ i ] ) );
  41352. }
  41353. return boneList;
  41354. }
  41355. /**
  41356. * This displays a helper object consisting of a spherical mesh for
  41357. * visualizing an instance of {@link PointLight}.
  41358. *
  41359. * ```js
  41360. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41361. * pointLight.position.set( 10, 10, 10 );
  41362. * scene.add( pointLight );
  41363. *
  41364. * const sphereSize = 1;
  41365. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41366. * scene.add( pointLightHelper );
  41367. * ```
  41368. *
  41369. * @augments Mesh
  41370. */
  41371. class PointLightHelper extends Mesh {
  41372. /**
  41373. * Constructs a new point light helper.
  41374. *
  41375. * @param {PointLight} light - The light to be visualized.
  41376. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41377. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41378. * the color of the light.
  41379. */
  41380. constructor( light, sphereSize, color ) {
  41381. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41382. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41383. super( geometry, material );
  41384. /**
  41385. * The light being visualized.
  41386. *
  41387. * @type {PointLight}
  41388. */
  41389. this.light = light;
  41390. /**
  41391. * The color parameter passed in the constructor.
  41392. * If not set, the helper will take the color of the light.
  41393. *
  41394. * @type {number|Color|string}
  41395. */
  41396. this.color = color;
  41397. this.type = 'PointLightHelper';
  41398. this.matrix = this.light.matrixWorld;
  41399. this.matrixAutoUpdate = false;
  41400. this.update();
  41401. /*
  41402. // TODO: delete this comment?
  41403. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41404. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41405. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41406. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41407. const d = light.distance;
  41408. if ( d === 0.0 ) {
  41409. this.lightDistance.visible = false;
  41410. } else {
  41411. this.lightDistance.scale.set( d, d, d );
  41412. }
  41413. this.add( this.lightDistance );
  41414. */
  41415. }
  41416. /**
  41417. * Frees the GPU-related resources allocated by this instance. Call this
  41418. * method whenever this instance is no longer used in your app.
  41419. */
  41420. dispose() {
  41421. this.geometry.dispose();
  41422. this.material.dispose();
  41423. }
  41424. /**
  41425. * Updates the helper to match the position of the
  41426. * light being visualized.
  41427. */
  41428. update() {
  41429. this.light.updateWorldMatrix( true, false );
  41430. if ( this.color !== undefined ) {
  41431. this.material.color.set( this.color );
  41432. } else {
  41433. this.material.color.copy( this.light.color );
  41434. }
  41435. /*
  41436. const d = this.light.distance;
  41437. if ( d === 0.0 ) {
  41438. this.lightDistance.visible = false;
  41439. } else {
  41440. this.lightDistance.visible = true;
  41441. this.lightDistance.scale.set( d, d, d );
  41442. }
  41443. */
  41444. }
  41445. }
  41446. const _vector$1 = /*@__PURE__*/ new Vector3();
  41447. const _color1 = /*@__PURE__*/ new Color();
  41448. const _color2 = /*@__PURE__*/ new Color();
  41449. /**
  41450. * Creates a visual aid consisting of a spherical mesh for a
  41451. * given {@link HemisphereLight}.
  41452. *
  41453. * When the hemisphere light is transformed or its light properties are changed,
  41454. * it's necessary to call the `update()` method of the respective helper.
  41455. *
  41456. * ```js
  41457. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41458. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41459. * scene.add( helper );
  41460. * ```
  41461. *
  41462. * @augments Object3D
  41463. */
  41464. class HemisphereLightHelper extends Object3D {
  41465. /**
  41466. * Constructs a new hemisphere light helper.
  41467. *
  41468. * @param {HemisphereLight} light - The light to be visualized.
  41469. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41470. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41471. * the color of the light.
  41472. */
  41473. constructor( light, size, color ) {
  41474. super();
  41475. /**
  41476. * The light being visualized.
  41477. *
  41478. * @type {HemisphereLight}
  41479. */
  41480. this.light = light;
  41481. this.matrix = light.matrixWorld;
  41482. this.matrixAutoUpdate = false;
  41483. /**
  41484. * The color parameter passed in the constructor.
  41485. * If not set, the helper will take the color of the light.
  41486. *
  41487. * @type {number|Color|string}
  41488. */
  41489. this.color = color;
  41490. this.type = 'HemisphereLightHelper';
  41491. const geometry = new OctahedronGeometry( size );
  41492. geometry.rotateY( Math.PI * 0.5 );
  41493. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41494. if ( this.color === undefined ) this.material.vertexColors = true;
  41495. const position = geometry.getAttribute( 'position' );
  41496. const colors = new Float32Array( position.count * 3 );
  41497. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41498. this.add( new Mesh( geometry, this.material ) );
  41499. this.update();
  41500. }
  41501. /**
  41502. * Frees the GPU-related resources allocated by this instance. Call this
  41503. * method whenever this instance is no longer used in your app.
  41504. */
  41505. dispose() {
  41506. this.children[ 0 ].geometry.dispose();
  41507. this.children[ 0 ].material.dispose();
  41508. }
  41509. /**
  41510. * Updates the helper to match the position and direction of the
  41511. * light being visualized.
  41512. */
  41513. update() {
  41514. const mesh = this.children[ 0 ];
  41515. if ( this.color !== undefined ) {
  41516. this.material.color.set( this.color );
  41517. } else {
  41518. const colors = mesh.geometry.getAttribute( 'color' );
  41519. _color1.copy( this.light.color );
  41520. _color2.copy( this.light.groundColor );
  41521. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41522. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41523. colors.setXYZ( i, color.r, color.g, color.b );
  41524. }
  41525. colors.needsUpdate = true;
  41526. }
  41527. this.light.updateWorldMatrix( true, false );
  41528. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41529. }
  41530. }
  41531. /**
  41532. * The helper is an object to define grids. Grids are two-dimensional
  41533. * arrays of lines.
  41534. *
  41535. * ```js
  41536. * const size = 10;
  41537. * const divisions = 10;
  41538. *
  41539. * const gridHelper = new THREE.GridHelper( size, divisions );
  41540. * scene.add( gridHelper );
  41541. * ```
  41542. *
  41543. * @augments LineSegments
  41544. */
  41545. class GridHelper extends LineSegments {
  41546. /**
  41547. * Constructs a new grid helper.
  41548. *
  41549. * @param {number} [size=10] - The size of the grid.
  41550. * @param {number} [divisions=10] - The number of divisions across the grid.
  41551. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41552. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41553. */
  41554. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41555. color1 = new Color( color1 );
  41556. color2 = new Color( color2 );
  41557. const center = divisions / 2;
  41558. const step = size / divisions;
  41559. const halfSize = size / 2;
  41560. const vertices = [], colors = [];
  41561. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41562. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41563. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41564. const color = i === center ? color1 : color2;
  41565. color.toArray( colors, j ); j += 3;
  41566. color.toArray( colors, j ); j += 3;
  41567. color.toArray( colors, j ); j += 3;
  41568. color.toArray( colors, j ); j += 3;
  41569. }
  41570. const geometry = new BufferGeometry();
  41571. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41572. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41573. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41574. super( geometry, material );
  41575. this.type = 'GridHelper';
  41576. }
  41577. /**
  41578. * Frees the GPU-related resources allocated by this instance. Call this
  41579. * method whenever this instance is no longer used in your app.
  41580. */
  41581. dispose() {
  41582. this.geometry.dispose();
  41583. this.material.dispose();
  41584. }
  41585. }
  41586. /**
  41587. * This helper is an object to define polar grids. Grids are
  41588. * two-dimensional arrays of lines.
  41589. *
  41590. * ```js
  41591. * const radius = 10;
  41592. * const sectors = 16;
  41593. * const rings = 8;
  41594. * const divisions = 64;
  41595. *
  41596. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41597. * scene.add( helper );
  41598. * ```
  41599. *
  41600. * @augments LineSegments
  41601. */
  41602. class PolarGridHelper extends LineSegments {
  41603. /**
  41604. * Constructs a new polar grid helper.
  41605. *
  41606. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41607. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41608. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41609. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41610. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41611. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41612. */
  41613. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41614. color1 = new Color( color1 );
  41615. color2 = new Color( color2 );
  41616. const vertices = [];
  41617. const colors = [];
  41618. // create the sectors
  41619. if ( sectors > 1 ) {
  41620. for ( let i = 0; i < sectors; i ++ ) {
  41621. const v = ( i / sectors ) * ( Math.PI * 2 );
  41622. const x = Math.sin( v ) * radius;
  41623. const z = Math.cos( v ) * radius;
  41624. vertices.push( 0, 0, 0 );
  41625. vertices.push( x, 0, z );
  41626. const color = ( i & 1 ) ? color1 : color2;
  41627. colors.push( color.r, color.g, color.b );
  41628. colors.push( color.r, color.g, color.b );
  41629. }
  41630. }
  41631. // create the rings
  41632. for ( let i = 0; i < rings; i ++ ) {
  41633. const color = ( i & 1 ) ? color1 : color2;
  41634. const r = radius - ( radius / rings * i );
  41635. for ( let j = 0; j < divisions; j ++ ) {
  41636. // first vertex
  41637. let v = ( j / divisions ) * ( Math.PI * 2 );
  41638. let x = Math.sin( v ) * r;
  41639. let z = Math.cos( v ) * r;
  41640. vertices.push( x, 0, z );
  41641. colors.push( color.r, color.g, color.b );
  41642. // second vertex
  41643. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41644. x = Math.sin( v ) * r;
  41645. z = Math.cos( v ) * r;
  41646. vertices.push( x, 0, z );
  41647. colors.push( color.r, color.g, color.b );
  41648. }
  41649. }
  41650. const geometry = new BufferGeometry();
  41651. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41652. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41653. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41654. super( geometry, material );
  41655. this.type = 'PolarGridHelper';
  41656. }
  41657. /**
  41658. * Frees the GPU-related resources allocated by this instance. Call this
  41659. * method whenever this instance is no longer used in your app.
  41660. */
  41661. dispose() {
  41662. this.geometry.dispose();
  41663. this.material.dispose();
  41664. }
  41665. }
  41666. const _v1 = /*@__PURE__*/ new Vector3();
  41667. const _v2 = /*@__PURE__*/ new Vector3();
  41668. const _v3 = /*@__PURE__*/ new Vector3();
  41669. /**
  41670. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41671. * effect on the scene. This consists of a plane and a line representing the
  41672. * light's position and direction.
  41673. *
  41674. * When the directional light or its target are transformed or light properties
  41675. * are changed, it's necessary to call the `update()` method of the respective helper.
  41676. *
  41677. * ```js
  41678. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41679. * scene.add( light );
  41680. *
  41681. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41682. * scene.add( helper );
  41683. * ```
  41684. *
  41685. * @augments Object3D
  41686. */
  41687. class DirectionalLightHelper extends Object3D {
  41688. /**
  41689. * Constructs a new directional light helper.
  41690. *
  41691. * @param {DirectionalLight} light - The light to be visualized.
  41692. * @param {number} [size=1] - The dimensions of the plane.
  41693. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41694. * the color of the light.
  41695. */
  41696. constructor( light, size, color ) {
  41697. super();
  41698. /**
  41699. * The light being visualized.
  41700. *
  41701. * @type {DirectionalLight}
  41702. */
  41703. this.light = light;
  41704. this.matrix = light.matrixWorld;
  41705. this.matrixAutoUpdate = false;
  41706. /**
  41707. * The color parameter passed in the constructor.
  41708. * If not set, the helper will take the color of the light.
  41709. *
  41710. * @type {number|Color|string}
  41711. */
  41712. this.color = color;
  41713. this.type = 'DirectionalLightHelper';
  41714. if ( size === undefined ) size = 1;
  41715. let geometry = new BufferGeometry();
  41716. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41717. - size, size, 0,
  41718. size, size, 0,
  41719. size, - size, 0,
  41720. - size, - size, 0,
  41721. - size, size, 0
  41722. ], 3 ) );
  41723. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41724. /**
  41725. * Contains the line showing the location of the directional light.
  41726. *
  41727. * @type {Line}
  41728. */
  41729. this.lightPlane = new Line( geometry, material );
  41730. this.add( this.lightPlane );
  41731. geometry = new BufferGeometry();
  41732. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41733. /**
  41734. * Represents the target line of the directional light.
  41735. *
  41736. * @type {Line}
  41737. */
  41738. this.targetLine = new Line( geometry, material );
  41739. this.add( this.targetLine );
  41740. this.update();
  41741. }
  41742. /**
  41743. * Frees the GPU-related resources allocated by this instance. Call this
  41744. * method whenever this instance is no longer used in your app.
  41745. */
  41746. dispose() {
  41747. this.lightPlane.geometry.dispose();
  41748. this.lightPlane.material.dispose();
  41749. this.targetLine.geometry.dispose();
  41750. this.targetLine.material.dispose();
  41751. }
  41752. /**
  41753. * Updates the helper to match the position and direction of the
  41754. * light being visualized.
  41755. */
  41756. update() {
  41757. this.light.updateWorldMatrix( true, false );
  41758. this.light.target.updateWorldMatrix( true, false );
  41759. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41760. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41761. _v3.subVectors( _v2, _v1 );
  41762. this.lightPlane.lookAt( _v2 );
  41763. if ( this.color !== undefined ) {
  41764. this.lightPlane.material.color.set( this.color );
  41765. this.targetLine.material.color.set( this.color );
  41766. } else {
  41767. this.lightPlane.material.color.copy( this.light.color );
  41768. this.targetLine.material.color.copy( this.light.color );
  41769. }
  41770. this.targetLine.lookAt( _v2 );
  41771. this.targetLine.scale.z = _v3.length();
  41772. }
  41773. }
  41774. const _vector = /*@__PURE__*/ new Vector3();
  41775. const _camera = /*@__PURE__*/ new Camera();
  41776. /**
  41777. * This helps with visualizing what a camera contains in its frustum. It
  41778. * visualizes the frustum of a camera using a line segments.
  41779. *
  41780. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41781. *
  41782. * `CameraHelper` must be a child of the scene.
  41783. *
  41784. * When the camera is transformed or its projection matrix is changed, it's necessary
  41785. * to call the `update()` method of the respective helper.
  41786. *
  41787. * ```js
  41788. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41789. * const helper = new THREE.CameraHelper( camera );
  41790. * scene.add( helper );
  41791. * ```
  41792. *
  41793. * @augments LineSegments
  41794. */
  41795. class CameraHelper extends LineSegments {
  41796. /**
  41797. * Constructs a new arrow helper.
  41798. *
  41799. * @param {Camera} camera - The camera to visualize.
  41800. */
  41801. constructor( camera ) {
  41802. const geometry = new BufferGeometry();
  41803. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41804. const vertices = [];
  41805. const colors = [];
  41806. const pointMap = {};
  41807. // near
  41808. addLine( 'n1', 'n2' );
  41809. addLine( 'n2', 'n4' );
  41810. addLine( 'n4', 'n3' );
  41811. addLine( 'n3', 'n1' );
  41812. // far
  41813. addLine( 'f1', 'f2' );
  41814. addLine( 'f2', 'f4' );
  41815. addLine( 'f4', 'f3' );
  41816. addLine( 'f3', 'f1' );
  41817. // sides
  41818. addLine( 'n1', 'f1' );
  41819. addLine( 'n2', 'f2' );
  41820. addLine( 'n3', 'f3' );
  41821. addLine( 'n4', 'f4' );
  41822. // cone
  41823. addLine( 'p', 'n1' );
  41824. addLine( 'p', 'n2' );
  41825. addLine( 'p', 'n3' );
  41826. addLine( 'p', 'n4' );
  41827. // up
  41828. addLine( 'u1', 'u2' );
  41829. addLine( 'u2', 'u3' );
  41830. addLine( 'u3', 'u1' );
  41831. // target
  41832. addLine( 'c', 't' );
  41833. addLine( 'p', 'c' );
  41834. // cross
  41835. addLine( 'cn1', 'cn2' );
  41836. addLine( 'cn3', 'cn4' );
  41837. addLine( 'cf1', 'cf2' );
  41838. addLine( 'cf3', 'cf4' );
  41839. function addLine( a, b ) {
  41840. addPoint( a );
  41841. addPoint( b );
  41842. }
  41843. function addPoint( id ) {
  41844. vertices.push( 0, 0, 0 );
  41845. colors.push( 0, 0, 0 );
  41846. if ( pointMap[ id ] === undefined ) {
  41847. pointMap[ id ] = [];
  41848. }
  41849. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41850. }
  41851. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41852. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41853. super( geometry, material );
  41854. this.type = 'CameraHelper';
  41855. /**
  41856. * The camera being visualized.
  41857. *
  41858. * @type {Camera}
  41859. */
  41860. this.camera = camera;
  41861. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41862. this.matrix = camera.matrixWorld;
  41863. this.matrixAutoUpdate = false;
  41864. /**
  41865. * This contains the points used to visualize the camera.
  41866. *
  41867. * @type {Object<string,Array<number>>}
  41868. */
  41869. this.pointMap = pointMap;
  41870. this.update();
  41871. // colors
  41872. const colorFrustum = new Color( 0xffaa00 );
  41873. const colorCone = new Color( 0xff0000 );
  41874. const colorUp = new Color( 0x00aaff );
  41875. const colorTarget = new Color( 0xffffff );
  41876. const colorCross = new Color( 0x333333 );
  41877. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41878. }
  41879. /**
  41880. * Defines the colors of the helper.
  41881. *
  41882. * @param {Color} frustum - The frustum line color.
  41883. * @param {Color} cone - The cone line color.
  41884. * @param {Color} up - The up line color.
  41885. * @param {Color} target - The target line color.
  41886. * @param {Color} cross - The cross line color.
  41887. * @return {CameraHelper} A reference to this helper.
  41888. */
  41889. setColors( frustum, cone, up, target, cross ) {
  41890. const geometry = this.geometry;
  41891. const colorAttribute = geometry.getAttribute( 'color' );
  41892. // near
  41893. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41894. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41895. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41896. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41897. // far
  41898. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41899. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41900. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41901. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41902. // sides
  41903. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41904. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41905. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41906. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41907. // cone
  41908. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41909. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41910. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41911. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41912. // up
  41913. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41914. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41915. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41916. // target
  41917. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41918. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41919. // cross
  41920. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41921. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41922. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41923. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41924. colorAttribute.needsUpdate = true;
  41925. return this;
  41926. }
  41927. /**
  41928. * Updates the helper based on the projection matrix of the camera.
  41929. */
  41930. update() {
  41931. const geometry = this.geometry;
  41932. const pointMap = this.pointMap;
  41933. const w = 1, h = 1;
  41934. let nearZ, farZ;
  41935. // we need just camera projection matrix inverse
  41936. // world matrix must be identity
  41937. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41938. // Adjust z values based on coordinate system
  41939. if ( this.camera.reversedDepth === true ) {
  41940. nearZ = 1;
  41941. farZ = 0;
  41942. } else {
  41943. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41944. nearZ = -1;
  41945. farZ = 1;
  41946. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41947. nearZ = 0;
  41948. farZ = 1;
  41949. } else {
  41950. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41951. }
  41952. }
  41953. // center / target
  41954. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41955. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41956. // near
  41957. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41958. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41959. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41960. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41961. // far
  41962. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41963. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41964. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41965. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41966. // up
  41967. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41968. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41969. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41970. // cross
  41971. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41972. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41973. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41974. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41975. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41976. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41977. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41978. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41979. geometry.getAttribute( 'position' ).needsUpdate = true;
  41980. }
  41981. /**
  41982. * Frees the GPU-related resources allocated by this instance. Call this
  41983. * method whenever this instance is no longer used in your app.
  41984. */
  41985. dispose() {
  41986. this.geometry.dispose();
  41987. this.material.dispose();
  41988. }
  41989. }
  41990. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41991. _vector.set( x, y, z ).unproject( camera );
  41992. const points = pointMap[ point ];
  41993. if ( points !== undefined ) {
  41994. const position = geometry.getAttribute( 'position' );
  41995. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41996. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41997. }
  41998. }
  41999. }
  42000. const _box = /*@__PURE__*/ new Box3();
  42001. /**
  42002. * Helper object to graphically show the world-axis-aligned bounding box
  42003. * around an object. The actual bounding box is handled with {@link Box3},
  42004. * this is just a visual helper for debugging. It can be automatically
  42005. * resized with {@link BoxHelper#update} when the object it's created from
  42006. * is transformed. Note that the object must have a geometry for this to work,
  42007. * so it won't work with sprites.
  42008. *
  42009. * ```js
  42010. * const sphere = new THREE.SphereGeometry();
  42011. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  42012. * const box = new THREE.BoxHelper( object, 0xffff00 );
  42013. * scene.add( box );
  42014. * ```
  42015. *
  42016. * @augments LineSegments
  42017. */
  42018. class BoxHelper extends LineSegments {
  42019. /**
  42020. * Constructs a new box helper.
  42021. *
  42022. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  42023. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42024. */
  42025. constructor( object, color = 0xffff00 ) {
  42026. 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 ] );
  42027. const positions = new Float32Array( 8 * 3 );
  42028. const geometry = new BufferGeometry();
  42029. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42030. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  42031. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42032. /**
  42033. * The 3D object being visualized.
  42034. *
  42035. * @type {Object3D}
  42036. */
  42037. this.object = object;
  42038. this.type = 'BoxHelper';
  42039. this.matrixAutoUpdate = false;
  42040. this.update();
  42041. }
  42042. /**
  42043. * Updates the helper's geometry to match the dimensions of the object,
  42044. * including any children.
  42045. */
  42046. update() {
  42047. if ( this.object !== undefined ) {
  42048. _box.setFromObject( this.object );
  42049. }
  42050. if ( _box.isEmpty() ) return;
  42051. const min = _box.min;
  42052. const max = _box.max;
  42053. /*
  42054. 5____4
  42055. 1/___0/|
  42056. | 6__|_7
  42057. 2/___3/
  42058. 0: max.x, max.y, max.z
  42059. 1: min.x, max.y, max.z
  42060. 2: min.x, min.y, max.z
  42061. 3: max.x, min.y, max.z
  42062. 4: max.x, max.y, min.z
  42063. 5: min.x, max.y, min.z
  42064. 6: min.x, min.y, min.z
  42065. 7: max.x, min.y, min.z
  42066. */
  42067. const position = this.geometry.attributes.position;
  42068. const array = position.array;
  42069. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  42070. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  42071. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  42072. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  42073. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  42074. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  42075. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  42076. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  42077. position.needsUpdate = true;
  42078. this.geometry.computeBoundingSphere();
  42079. }
  42080. /**
  42081. * Updates the wireframe box for the passed object.
  42082. *
  42083. * @param {Object3D} object - The 3D object to create the helper for.
  42084. * @return {BoxHelper} A reference to this instance.
  42085. */
  42086. setFromObject( object ) {
  42087. this.object = object;
  42088. this.update();
  42089. return this;
  42090. }
  42091. copy( source, recursive ) {
  42092. super.copy( source, recursive );
  42093. this.object = source.object;
  42094. return this;
  42095. }
  42096. /**
  42097. * Frees the GPU-related resources allocated by this instance. Call this
  42098. * method whenever this instance is no longer used in your app.
  42099. */
  42100. dispose() {
  42101. this.geometry.dispose();
  42102. this.material.dispose();
  42103. }
  42104. }
  42105. /**
  42106. * A helper object to visualize an instance of {@link Box3}.
  42107. *
  42108. * ```js
  42109. * const box = new THREE.Box3();
  42110. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  42111. *
  42112. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  42113. * scene.add( helper )
  42114. * ```
  42115. *
  42116. * @augments LineSegments
  42117. */
  42118. class Box3Helper extends LineSegments {
  42119. /**
  42120. * Constructs a new box3 helper.
  42121. *
  42122. * @param {Box3} box - The box to visualize.
  42123. * @param {number|Color|string} [color=0xffff00] - The box's color.
  42124. */
  42125. constructor( box, color = 0xffff00 ) {
  42126. 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 ] );
  42127. 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 ];
  42128. const geometry = new BufferGeometry();
  42129. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  42130. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42131. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42132. /**
  42133. * The box being visualized.
  42134. *
  42135. * @type {Box3}
  42136. */
  42137. this.box = box;
  42138. this.type = 'Box3Helper';
  42139. this.geometry.computeBoundingSphere();
  42140. }
  42141. updateMatrixWorld( force ) {
  42142. const box = this.box;
  42143. if ( box.isEmpty() ) return;
  42144. box.getCenter( this.position );
  42145. box.getSize( this.scale );
  42146. this.scale.multiplyScalar( 0.5 );
  42147. super.updateMatrixWorld( force );
  42148. }
  42149. /**
  42150. * Frees the GPU-related resources allocated by this instance. Call this
  42151. * method whenever this instance is no longer used in your app.
  42152. */
  42153. dispose() {
  42154. this.geometry.dispose();
  42155. this.material.dispose();
  42156. }
  42157. }
  42158. /**
  42159. * A helper object to visualize an instance of {@link Plane}.
  42160. *
  42161. * ```js
  42162. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  42163. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  42164. * scene.add( helper );
  42165. * ```
  42166. *
  42167. * @augments Line
  42168. */
  42169. class PlaneHelper extends Line {
  42170. /**
  42171. * Constructs a new plane helper.
  42172. *
  42173. * @param {Plane} plane - The plane to be visualized.
  42174. * @param {number} [size=1] - The side length of plane helper.
  42175. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  42176. */
  42177. constructor( plane, size = 1, hex = 0xffff00 ) {
  42178. const color = hex;
  42179. 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 ];
  42180. const geometry = new BufferGeometry();
  42181. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  42182. geometry.computeBoundingSphere();
  42183. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42184. this.type = 'PlaneHelper';
  42185. /**
  42186. * The plane being visualized.
  42187. *
  42188. * @type {Plane}
  42189. */
  42190. this.plane = plane;
  42191. /**
  42192. * The side length of plane helper.
  42193. *
  42194. * @type {number}
  42195. * @default 1
  42196. */
  42197. this.size = size;
  42198. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  42199. const geometry2 = new BufferGeometry();
  42200. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  42201. geometry2.computeBoundingSphere();
  42202. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  42203. }
  42204. updateMatrixWorld( force ) {
  42205. this.position.set( 0, 0, 0 );
  42206. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  42207. this.lookAt( this.plane.normal );
  42208. this.translateZ( - this.plane.constant );
  42209. super.updateMatrixWorld( force );
  42210. }
  42211. /**
  42212. * Updates the helper to match the position and direction of the
  42213. * light being visualized.
  42214. */
  42215. dispose() {
  42216. this.geometry.dispose();
  42217. this.material.dispose();
  42218. this.children[ 0 ].geometry.dispose();
  42219. this.children[ 0 ].material.dispose();
  42220. }
  42221. }
  42222. const _axis = /*@__PURE__*/ new Vector3();
  42223. let _lineGeometry, _coneGeometry;
  42224. /**
  42225. * An 3D arrow object for visualizing directions.
  42226. *
  42227. * ```js
  42228. * const dir = new THREE.Vector3( 1, 2, 0 );
  42229. *
  42230. * //normalize the direction vector (convert to vector of length 1)
  42231. * dir.normalize();
  42232. *
  42233. * const origin = new THREE.Vector3( 0, 0, 0 );
  42234. * const length = 1;
  42235. * const hex = 0xffff00;
  42236. *
  42237. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42238. * scene.add( arrowHelper );
  42239. * ```
  42240. *
  42241. * @augments Object3D
  42242. */
  42243. class ArrowHelper extends Object3D {
  42244. /**
  42245. * Constructs a new arrow helper.
  42246. *
  42247. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42248. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42249. * @param {number} [length=1] - Length of the arrow in world units.
  42250. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42251. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42252. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42253. */
  42254. 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 ) {
  42255. super();
  42256. this.type = 'ArrowHelper';
  42257. if ( _lineGeometry === undefined ) {
  42258. _lineGeometry = new BufferGeometry();
  42259. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42260. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42261. _coneGeometry.translate( 0, -0.5, 0 );
  42262. }
  42263. this.position.copy( origin );
  42264. /**
  42265. * The line part of the arrow helper.
  42266. *
  42267. * @type {Line}
  42268. */
  42269. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42270. this.line.matrixAutoUpdate = false;
  42271. this.add( this.line );
  42272. /**
  42273. * The cone part of the arrow helper.
  42274. *
  42275. * @type {Mesh}
  42276. */
  42277. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42278. this.cone.matrixAutoUpdate = false;
  42279. this.add( this.cone );
  42280. this.setDirection( dir );
  42281. this.setLength( length, headLength, headWidth );
  42282. }
  42283. /**
  42284. * Sets the direction of the helper.
  42285. *
  42286. * @param {Vector3} dir - The normalized direction vector.
  42287. */
  42288. setDirection( dir ) {
  42289. // dir is assumed to be normalized
  42290. if ( dir.y > 0.99999 ) {
  42291. this.quaternion.set( 0, 0, 0, 1 );
  42292. } else if ( dir.y < -0.99999 ) {
  42293. this.quaternion.set( 1, 0, 0, 0 );
  42294. } else {
  42295. _axis.set( dir.z, 0, - dir.x ).normalize();
  42296. const radians = Math.acos( dir.y );
  42297. this.quaternion.setFromAxisAngle( _axis, radians );
  42298. }
  42299. }
  42300. /**
  42301. * Sets the length of the helper.
  42302. *
  42303. * @param {number} length - Length of the arrow in world units.
  42304. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42305. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42306. */
  42307. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42308. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42309. this.line.updateMatrix();
  42310. this.cone.scale.set( headWidth, headLength, headWidth );
  42311. this.cone.position.y = length;
  42312. this.cone.updateMatrix();
  42313. }
  42314. /**
  42315. * Sets the color of the helper.
  42316. *
  42317. * @param {number|Color|string} color - The color to set.
  42318. */
  42319. setColor( color ) {
  42320. this.line.material.color.set( color );
  42321. this.cone.material.color.set( color );
  42322. }
  42323. copy( source ) {
  42324. super.copy( source, false );
  42325. this.line.copy( source.line );
  42326. this.cone.copy( source.cone );
  42327. return this;
  42328. }
  42329. /**
  42330. * Frees the GPU-related resources allocated by this instance. Call this
  42331. * method whenever this instance is no longer used in your app.
  42332. */
  42333. dispose() {
  42334. this.line.geometry.dispose();
  42335. this.line.material.dispose();
  42336. this.cone.geometry.dispose();
  42337. this.cone.material.dispose();
  42338. }
  42339. }
  42340. /**
  42341. * An axis object to visualize the 3 axes in a simple way.
  42342. * The X axis is red. The Y axis is green. The Z axis is blue.
  42343. *
  42344. * ```js
  42345. * const axesHelper = new THREE.AxesHelper( 5 );
  42346. * scene.add( axesHelper );
  42347. * ```
  42348. *
  42349. * @augments LineSegments
  42350. */
  42351. class AxesHelper extends LineSegments {
  42352. /**
  42353. * Constructs a new axes helper.
  42354. *
  42355. * @param {number} [size=1] - Size of the lines representing the axes.
  42356. */
  42357. constructor( size = 1 ) {
  42358. const vertices = [
  42359. 0, 0, 0, size, 0, 0,
  42360. 0, 0, 0, 0, size, 0,
  42361. 0, 0, 0, 0, 0, size
  42362. ];
  42363. const colors = [
  42364. 1, 0, 0, 1, 0.6, 0,
  42365. 0, 1, 0, 0.6, 1, 0,
  42366. 0, 0, 1, 0, 0.6, 1
  42367. ];
  42368. const geometry = new BufferGeometry();
  42369. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42370. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42371. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42372. super( geometry, material );
  42373. this.type = 'AxesHelper';
  42374. }
  42375. /**
  42376. * Defines the colors of the axes helper.
  42377. *
  42378. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42379. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42380. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42381. * @return {AxesHelper} A reference to this axes helper.
  42382. */
  42383. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42384. const color = new Color();
  42385. const array = this.geometry.attributes.color.array;
  42386. color.set( xAxisColor );
  42387. color.toArray( array, 0 );
  42388. color.toArray( array, 3 );
  42389. color.set( yAxisColor );
  42390. color.toArray( array, 6 );
  42391. color.toArray( array, 9 );
  42392. color.set( zAxisColor );
  42393. color.toArray( array, 12 );
  42394. color.toArray( array, 15 );
  42395. this.geometry.attributes.color.needsUpdate = true;
  42396. return this;
  42397. }
  42398. /**
  42399. * Frees the GPU-related resources allocated by this instance. Call this
  42400. * method whenever this instance is no longer used in your app.
  42401. */
  42402. dispose() {
  42403. this.geometry.dispose();
  42404. this.material.dispose();
  42405. }
  42406. }
  42407. /**
  42408. * This class is used to convert a series of paths to an array of
  42409. * shapes. It is specifically used in context of fonts and SVG.
  42410. */
  42411. class ShapePath {
  42412. /**
  42413. * Constructs a new shape path.
  42414. */
  42415. constructor() {
  42416. this.type = 'ShapePath';
  42417. /**
  42418. * The color of the shape.
  42419. *
  42420. * @type {Color}
  42421. */
  42422. this.color = new Color();
  42423. /**
  42424. * The paths that have been generated for this shape.
  42425. *
  42426. * @type {Array<Path>}
  42427. * @default null
  42428. */
  42429. this.subPaths = [];
  42430. /**
  42431. * The current path that is being generated.
  42432. *
  42433. * @type {?Path}
  42434. * @default null
  42435. */
  42436. this.currentPath = null;
  42437. }
  42438. /**
  42439. * Creates a new path and moves it current point to the given one.
  42440. *
  42441. * @param {number} x - The x coordinate.
  42442. * @param {number} y - The y coordinate.
  42443. * @return {ShapePath} A reference to this shape path.
  42444. */
  42445. moveTo( x, y ) {
  42446. this.currentPath = new Path();
  42447. this.subPaths.push( this.currentPath );
  42448. this.currentPath.moveTo( x, y );
  42449. return this;
  42450. }
  42451. /**
  42452. * Adds an instance of {@link LineCurve} to the path by connecting
  42453. * the current point with the given one.
  42454. *
  42455. * @param {number} x - The x coordinate of the end point.
  42456. * @param {number} y - The y coordinate of the end point.
  42457. * @return {ShapePath} A reference to this shape path.
  42458. */
  42459. lineTo( x, y ) {
  42460. this.currentPath.lineTo( x, y );
  42461. return this;
  42462. }
  42463. /**
  42464. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42465. * the current point with the given one.
  42466. *
  42467. * @param {number} aCPx - The x coordinate of the control point.
  42468. * @param {number} aCPy - The y coordinate of the control point.
  42469. * @param {number} aX - The x coordinate of the end point.
  42470. * @param {number} aY - The y coordinate of the end point.
  42471. * @return {ShapePath} A reference to this shape path.
  42472. */
  42473. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42474. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42475. return this;
  42476. }
  42477. /**
  42478. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42479. * the current point with the given one.
  42480. *
  42481. * @param {number} aCP1x - The x coordinate of the first control point.
  42482. * @param {number} aCP1y - The y coordinate of the first control point.
  42483. * @param {number} aCP2x - The x coordinate of the second control point.
  42484. * @param {number} aCP2y - The y coordinate of the second control point.
  42485. * @param {number} aX - The x coordinate of the end point.
  42486. * @param {number} aY - The y coordinate of the end point.
  42487. * @return {ShapePath} A reference to this shape path.
  42488. */
  42489. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42490. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42491. return this;
  42492. }
  42493. /**
  42494. * Adds an instance of {@link SplineCurve} to the path by connecting
  42495. * the current point with the given list of points.
  42496. *
  42497. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42498. * @return {ShapePath} A reference to this shape path.
  42499. */
  42500. splineThru( pts ) {
  42501. this.currentPath.splineThru( pts );
  42502. return this;
  42503. }
  42504. /**
  42505. * Converts the paths into an array of shapes.
  42506. *
  42507. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42508. * If this flag is set to `true`, then those are flipped.
  42509. * @return {Array<Shape>} An array of shapes.
  42510. */
  42511. toShapes( isCCW ) {
  42512. function toShapesNoHoles( inSubpaths ) {
  42513. const shapes = [];
  42514. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42515. const tmpPath = inSubpaths[ i ];
  42516. const tmpShape = new Shape();
  42517. tmpShape.curves = tmpPath.curves;
  42518. shapes.push( tmpShape );
  42519. }
  42520. return shapes;
  42521. }
  42522. function isPointInsidePolygon( inPt, inPolygon ) {
  42523. const polyLen = inPolygon.length;
  42524. // inPt on polygon contour => immediate success or
  42525. // toggling of inside/outside at every single! intersection point of an edge
  42526. // with the horizontal line through inPt, left of inPt
  42527. // not counting lowerY endpoints of edges and whole edges on that line
  42528. let inside = false;
  42529. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42530. let edgeLowPt = inPolygon[ p ];
  42531. let edgeHighPt = inPolygon[ q ];
  42532. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42533. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42534. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42535. // not parallel
  42536. if ( edgeDy < 0 ) {
  42537. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42538. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42539. }
  42540. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42541. if ( inPt.y === edgeLowPt.y ) {
  42542. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42543. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42544. } else {
  42545. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42546. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42547. if ( perpEdge < 0 ) continue;
  42548. inside = ! inside; // true intersection left of inPt
  42549. }
  42550. } else {
  42551. // parallel or collinear
  42552. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42553. // edge lies on the same horizontal line as inPt
  42554. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42555. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42556. // continue;
  42557. }
  42558. }
  42559. return inside;
  42560. }
  42561. const isClockWise = ShapeUtils.isClockWise;
  42562. const subPaths = this.subPaths;
  42563. if ( subPaths.length === 0 ) return [];
  42564. let solid, tmpPath, tmpShape;
  42565. const shapes = [];
  42566. if ( subPaths.length === 1 ) {
  42567. tmpPath = subPaths[ 0 ];
  42568. tmpShape = new Shape();
  42569. tmpShape.curves = tmpPath.curves;
  42570. shapes.push( tmpShape );
  42571. return shapes;
  42572. }
  42573. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42574. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42575. // log("Holes first", holesFirst);
  42576. const betterShapeHoles = [];
  42577. const newShapes = [];
  42578. let newShapeHoles = [];
  42579. let mainIdx = 0;
  42580. let tmpPoints;
  42581. newShapes[ mainIdx ] = undefined;
  42582. newShapeHoles[ mainIdx ] = [];
  42583. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42584. tmpPath = subPaths[ i ];
  42585. tmpPoints = tmpPath.getPoints();
  42586. solid = isClockWise( tmpPoints );
  42587. solid = isCCW ? ! solid : solid;
  42588. if ( solid ) {
  42589. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42590. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42591. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42592. if ( holesFirst ) mainIdx ++;
  42593. newShapeHoles[ mainIdx ] = [];
  42594. //log('cw', i);
  42595. } else {
  42596. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42597. //log('ccw', i);
  42598. }
  42599. }
  42600. // only Holes? -> probably all Shapes with wrong orientation
  42601. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42602. if ( newShapes.length > 1 ) {
  42603. let ambiguous = false;
  42604. let toChange = 0;
  42605. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42606. betterShapeHoles[ sIdx ] = [];
  42607. }
  42608. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42609. const sho = newShapeHoles[ sIdx ];
  42610. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42611. const ho = sho[ hIdx ];
  42612. let hole_unassigned = true;
  42613. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42614. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42615. if ( sIdx !== s2Idx ) toChange ++;
  42616. if ( hole_unassigned ) {
  42617. hole_unassigned = false;
  42618. betterShapeHoles[ s2Idx ].push( ho );
  42619. } else {
  42620. ambiguous = true;
  42621. }
  42622. }
  42623. }
  42624. if ( hole_unassigned ) {
  42625. betterShapeHoles[ sIdx ].push( ho );
  42626. }
  42627. }
  42628. }
  42629. if ( toChange > 0 && ambiguous === false ) {
  42630. newShapeHoles = betterShapeHoles;
  42631. }
  42632. }
  42633. let tmpHoles;
  42634. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42635. tmpShape = newShapes[ i ].s;
  42636. shapes.push( tmpShape );
  42637. tmpHoles = newShapeHoles[ i ];
  42638. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42639. tmpShape.holes.push( tmpHoles[ j ].h );
  42640. }
  42641. }
  42642. //log("shape", shapes);
  42643. return shapes;
  42644. }
  42645. }
  42646. /**
  42647. * Abstract base class for controls.
  42648. *
  42649. * @abstract
  42650. * @augments EventDispatcher
  42651. */
  42652. class Controls extends EventDispatcher {
  42653. /**
  42654. * Constructs a new controls instance.
  42655. *
  42656. * @param {Object3D} object - The object that is managed by the controls.
  42657. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42658. */
  42659. constructor( object, domElement = null ) {
  42660. super();
  42661. /**
  42662. * The object that is managed by the controls.
  42663. *
  42664. * @type {Object3D}
  42665. */
  42666. this.object = object;
  42667. /**
  42668. * The HTML element used for event listeners.
  42669. *
  42670. * @type {?HTMLElement}
  42671. * @default null
  42672. */
  42673. this.domElement = domElement;
  42674. /**
  42675. * Whether the controls responds to user input or not.
  42676. *
  42677. * @type {boolean}
  42678. * @default true
  42679. */
  42680. this.enabled = true;
  42681. /**
  42682. * The internal state of the controls.
  42683. *
  42684. * @type {number}
  42685. * @default -1
  42686. */
  42687. this.state = -1;
  42688. /**
  42689. * This object defines the keyboard input of the controls.
  42690. *
  42691. * @type {Object}
  42692. */
  42693. this.keys = {};
  42694. /**
  42695. * This object defines what type of actions are assigned to the available mouse buttons.
  42696. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42697. *
  42698. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42699. */
  42700. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42701. /**
  42702. * This object defines what type of actions are assigned to what kind of touch interaction.
  42703. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42704. *
  42705. * @type {{ONE: ?number, TWO: ?number}}
  42706. */
  42707. this.touches = { ONE: null, TWO: null };
  42708. }
  42709. /**
  42710. * Connects the controls to the DOM. This method has so called "side effects" since
  42711. * it adds the module's event listeners to the DOM.
  42712. *
  42713. * @param {HTMLElement} element - The DOM element to connect to.
  42714. */
  42715. connect( element ) {
  42716. if ( element === undefined ) {
  42717. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42718. return;
  42719. }
  42720. if ( this.domElement !== null ) this.disconnect();
  42721. this.domElement = element;
  42722. }
  42723. /**
  42724. * Disconnects the controls from the DOM.
  42725. */
  42726. disconnect() {}
  42727. /**
  42728. * Call this method if you no longer want use to the controls. It frees all internal
  42729. * resources and removes all event listeners.
  42730. */
  42731. dispose() {}
  42732. /**
  42733. * Controls should implement this method if they have to update their internal state
  42734. * per simulation step.
  42735. *
  42736. * @param {number} [delta] - The time delta in seconds.
  42737. */
  42738. update( /* delta */ ) {}
  42739. }
  42740. /**
  42741. * Scales the texture as large as possible within its surface without cropping
  42742. * or stretching the texture. The method preserves the original aspect ratio of
  42743. * the texture. Akin to CSS `object-fit: contain`
  42744. *
  42745. * @param {Texture} texture - The texture.
  42746. * @param {number} aspect - The texture's aspect ratio.
  42747. * @return {Texture} The updated texture.
  42748. */
  42749. function contain( texture, aspect ) {
  42750. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42751. if ( imageAspect > aspect ) {
  42752. texture.repeat.x = 1;
  42753. texture.repeat.y = imageAspect / aspect;
  42754. texture.offset.x = 0;
  42755. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42756. } else {
  42757. texture.repeat.x = aspect / imageAspect;
  42758. texture.repeat.y = 1;
  42759. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42760. texture.offset.y = 0;
  42761. }
  42762. return texture;
  42763. }
  42764. /**
  42765. * Scales the texture to the smallest possible size to fill the surface, leaving
  42766. * no empty space. The method preserves the original aspect ratio of the texture.
  42767. * Akin to CSS `object-fit: cover`.
  42768. *
  42769. * @param {Texture} texture - The texture.
  42770. * @param {number} aspect - The texture's aspect ratio.
  42771. * @return {Texture} The updated texture.
  42772. */
  42773. function cover( texture, aspect ) {
  42774. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42775. if ( imageAspect > aspect ) {
  42776. texture.repeat.x = aspect / imageAspect;
  42777. texture.repeat.y = 1;
  42778. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42779. texture.offset.y = 0;
  42780. } else {
  42781. texture.repeat.x = 1;
  42782. texture.repeat.y = imageAspect / aspect;
  42783. texture.offset.x = 0;
  42784. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42785. }
  42786. return texture;
  42787. }
  42788. /**
  42789. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42790. *
  42791. * @param {Texture} texture - The texture.
  42792. * @return {Texture} The updated texture.
  42793. */
  42794. function fill( texture ) {
  42795. texture.repeat.x = 1;
  42796. texture.repeat.y = 1;
  42797. texture.offset.x = 0;
  42798. texture.offset.y = 0;
  42799. return texture;
  42800. }
  42801. /**
  42802. * Determines how many bytes must be used to represent the texture.
  42803. *
  42804. * @param {number} width - The width of the texture.
  42805. * @param {number} height - The height of the texture.
  42806. * @param {number} format - The texture's format.
  42807. * @param {number} type - The texture's type.
  42808. * @return {number} The byte length.
  42809. */
  42810. function getByteLength( width, height, format, type ) {
  42811. const typeByteLength = getTextureTypeByteLength( type );
  42812. switch ( format ) {
  42813. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42814. case AlphaFormat:
  42815. return width * height;
  42816. case RedFormat:
  42817. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42818. case RedIntegerFormat:
  42819. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42820. case RGFormat:
  42821. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42822. case RGIntegerFormat:
  42823. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42824. case RGBFormat:
  42825. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42826. case RGBAFormat:
  42827. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42828. case RGBAIntegerFormat:
  42829. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42830. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42831. case RGB_S3TC_DXT1_Format:
  42832. case RGBA_S3TC_DXT1_Format:
  42833. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42834. case RGBA_S3TC_DXT3_Format:
  42835. case RGBA_S3TC_DXT5_Format:
  42836. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42837. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42838. case RGB_PVRTC_2BPPV1_Format:
  42839. case RGBA_PVRTC_2BPPV1_Format:
  42840. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42841. case RGB_PVRTC_4BPPV1_Format:
  42842. case RGBA_PVRTC_4BPPV1_Format:
  42843. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42844. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42845. case RGB_ETC1_Format:
  42846. case RGB_ETC2_Format:
  42847. case R11_EAC_Format:
  42848. case SIGNED_R11_EAC_Format:
  42849. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42850. case RGBA_ETC2_EAC_Format:
  42851. case RG11_EAC_Format:
  42852. case SIGNED_RG11_EAC_Format:
  42853. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42854. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42855. case RGBA_ASTC_4x4_Format:
  42856. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42857. case RGBA_ASTC_5x4_Format:
  42858. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42859. case RGBA_ASTC_5x5_Format:
  42860. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42861. case RGBA_ASTC_6x5_Format:
  42862. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42863. case RGBA_ASTC_6x6_Format:
  42864. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42865. case RGBA_ASTC_8x5_Format:
  42866. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42867. case RGBA_ASTC_8x6_Format:
  42868. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42869. case RGBA_ASTC_8x8_Format:
  42870. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42871. case RGBA_ASTC_10x5_Format:
  42872. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42873. case RGBA_ASTC_10x6_Format:
  42874. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42875. case RGBA_ASTC_10x8_Format:
  42876. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42877. case RGBA_ASTC_10x10_Format:
  42878. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42879. case RGBA_ASTC_12x10_Format:
  42880. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42881. case RGBA_ASTC_12x12_Format:
  42882. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42883. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42884. case RGBA_BPTC_Format:
  42885. case RGB_BPTC_SIGNED_Format:
  42886. case RGB_BPTC_UNSIGNED_Format:
  42887. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42888. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42889. case RED_RGTC1_Format:
  42890. case SIGNED_RED_RGTC1_Format:
  42891. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42892. case RED_GREEN_RGTC2_Format:
  42893. case SIGNED_RED_GREEN_RGTC2_Format:
  42894. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42895. }
  42896. throw new Error(
  42897. `Unable to determine texture byte length for ${format} format.`,
  42898. );
  42899. }
  42900. function getTextureTypeByteLength( type ) {
  42901. switch ( type ) {
  42902. case UnsignedByteType:
  42903. case ByteType:
  42904. return { byteLength: 1, components: 1 };
  42905. case UnsignedShortType:
  42906. case ShortType:
  42907. case HalfFloatType:
  42908. return { byteLength: 2, components: 1 };
  42909. case UnsignedShort4444Type:
  42910. case UnsignedShort5551Type:
  42911. return { byteLength: 2, components: 4 };
  42912. case UnsignedIntType:
  42913. case IntType:
  42914. case FloatType:
  42915. return { byteLength: 4, components: 1 };
  42916. case UnsignedInt5999Type:
  42917. case UnsignedInt101111Type:
  42918. return { byteLength: 4, components: 3 };
  42919. }
  42920. throw new Error( `Unknown texture type ${type}.` );
  42921. }
  42922. /**
  42923. * A class containing utility functions for textures.
  42924. *
  42925. * @hideconstructor
  42926. */
  42927. class TextureUtils {
  42928. /**
  42929. * Scales the texture as large as possible within its surface without cropping
  42930. * or stretching the texture. The method preserves the original aspect ratio of
  42931. * the texture. Akin to CSS `object-fit: contain`
  42932. *
  42933. * @param {Texture} texture - The texture.
  42934. * @param {number} aspect - The texture's aspect ratio.
  42935. * @return {Texture} The updated texture.
  42936. */
  42937. static contain( texture, aspect ) {
  42938. return contain( texture, aspect );
  42939. }
  42940. /**
  42941. * Scales the texture to the smallest possible size to fill the surface, leaving
  42942. * no empty space. The method preserves the original aspect ratio of the texture.
  42943. * Akin to CSS `object-fit: cover`.
  42944. *
  42945. * @param {Texture} texture - The texture.
  42946. * @param {number} aspect - The texture's aspect ratio.
  42947. * @return {Texture} The updated texture.
  42948. */
  42949. static cover( texture, aspect ) {
  42950. return cover( texture, aspect );
  42951. }
  42952. /**
  42953. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42954. *
  42955. * @param {Texture} texture - The texture.
  42956. * @return {Texture} The updated texture.
  42957. */
  42958. static fill( texture ) {
  42959. return fill( texture );
  42960. }
  42961. /**
  42962. * Determines how many bytes must be used to represent the texture.
  42963. *
  42964. * @param {number} width - The width of the texture.
  42965. * @param {number} height - The height of the texture.
  42966. * @param {number} format - The texture's format.
  42967. * @param {number} type - The texture's type.
  42968. * @return {number} The byte length.
  42969. */
  42970. static getByteLength( width, height, format, type ) {
  42971. return getByteLength( width, height, format, type );
  42972. }
  42973. }
  42974. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42975. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42976. revision: REVISION,
  42977. } } ) );
  42978. }
  42979. if ( typeof window !== 'undefined' ) {
  42980. if ( window.__THREE__ ) {
  42981. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42982. } else {
  42983. window.__THREE__ = REVISION;
  42984. }
  42985. }
  42986. function WebGLAnimation() {
  42987. let context = null;
  42988. let isAnimating = false;
  42989. let animationLoop = null;
  42990. let requestId = null;
  42991. function onAnimationFrame( time, frame ) {
  42992. animationLoop( time, frame );
  42993. requestId = context.requestAnimationFrame( onAnimationFrame );
  42994. }
  42995. return {
  42996. start: function () {
  42997. if ( isAnimating === true ) return;
  42998. if ( animationLoop === null ) return;
  42999. requestId = context.requestAnimationFrame( onAnimationFrame );
  43000. isAnimating = true;
  43001. },
  43002. stop: function () {
  43003. context.cancelAnimationFrame( requestId );
  43004. isAnimating = false;
  43005. },
  43006. setAnimationLoop: function ( callback ) {
  43007. animationLoop = callback;
  43008. },
  43009. setContext: function ( value ) {
  43010. context = value;
  43011. }
  43012. };
  43013. }
  43014. function WebGLAttributes( gl ) {
  43015. const buffers = new WeakMap();
  43016. function createBuffer( attribute, bufferType ) {
  43017. const array = attribute.array;
  43018. const usage = attribute.usage;
  43019. const size = array.byteLength;
  43020. const buffer = gl.createBuffer();
  43021. gl.bindBuffer( bufferType, buffer );
  43022. gl.bufferData( bufferType, array, usage );
  43023. attribute.onUploadCallback();
  43024. let type;
  43025. if ( array instanceof Float32Array ) {
  43026. type = gl.FLOAT;
  43027. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  43028. type = gl.HALF_FLOAT;
  43029. } else if ( array instanceof Uint16Array ) {
  43030. if ( attribute.isFloat16BufferAttribute ) {
  43031. type = gl.HALF_FLOAT;
  43032. } else {
  43033. type = gl.UNSIGNED_SHORT;
  43034. }
  43035. } else if ( array instanceof Int16Array ) {
  43036. type = gl.SHORT;
  43037. } else if ( array instanceof Uint32Array ) {
  43038. type = gl.UNSIGNED_INT;
  43039. } else if ( array instanceof Int32Array ) {
  43040. type = gl.INT;
  43041. } else if ( array instanceof Int8Array ) {
  43042. type = gl.BYTE;
  43043. } else if ( array instanceof Uint8Array ) {
  43044. type = gl.UNSIGNED_BYTE;
  43045. } else if ( array instanceof Uint8ClampedArray ) {
  43046. type = gl.UNSIGNED_BYTE;
  43047. } else {
  43048. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  43049. }
  43050. return {
  43051. buffer: buffer,
  43052. type: type,
  43053. bytesPerElement: array.BYTES_PER_ELEMENT,
  43054. version: attribute.version,
  43055. size: size
  43056. };
  43057. }
  43058. function updateBuffer( buffer, attribute, bufferType ) {
  43059. const array = attribute.array;
  43060. const updateRanges = attribute.updateRanges;
  43061. gl.bindBuffer( bufferType, buffer );
  43062. if ( updateRanges.length === 0 ) {
  43063. // Not using update ranges
  43064. gl.bufferSubData( bufferType, 0, array );
  43065. } else {
  43066. // Before applying update ranges, we merge any adjacent / overlapping
  43067. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  43068. // to performance improvements for applications which make heavy use of
  43069. // update ranges. Likely due to GPU command overhead.
  43070. //
  43071. // Note that to reduce garbage collection between frames, we merge the
  43072. // update ranges in-place. This is safe because this method will clear the
  43073. // update ranges once updated.
  43074. updateRanges.sort( ( a, b ) => a.start - b.start );
  43075. // To merge the update ranges in-place, we work from left to right in the
  43076. // existing updateRanges array, merging ranges. This may result in a final
  43077. // array which is smaller than the original. This index tracks the last
  43078. // index representing a merged range, any data after this index can be
  43079. // trimmed once the merge algorithm is completed.
  43080. let mergeIndex = 0;
  43081. for ( let i = 1; i < updateRanges.length; i ++ ) {
  43082. const previousRange = updateRanges[ mergeIndex ];
  43083. const range = updateRanges[ i ];
  43084. // We add one here to merge adjacent ranges. This is safe because ranges
  43085. // operate over positive integers.
  43086. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  43087. previousRange.count = Math.max(
  43088. previousRange.count,
  43089. range.start + range.count - previousRange.start
  43090. );
  43091. } else {
  43092. ++ mergeIndex;
  43093. updateRanges[ mergeIndex ] = range;
  43094. }
  43095. }
  43096. // Trim the array to only contain the merged ranges.
  43097. updateRanges.length = mergeIndex + 1;
  43098. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43099. const range = updateRanges[ i ];
  43100. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  43101. array, range.start, range.count );
  43102. }
  43103. attribute.clearUpdateRanges();
  43104. }
  43105. attribute.onUploadCallback();
  43106. }
  43107. //
  43108. function get( attribute ) {
  43109. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43110. return buffers.get( attribute );
  43111. }
  43112. function remove( attribute ) {
  43113. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43114. const data = buffers.get( attribute );
  43115. if ( data ) {
  43116. gl.deleteBuffer( data.buffer );
  43117. buffers.delete( attribute );
  43118. }
  43119. }
  43120. function update( attribute, bufferType ) {
  43121. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  43122. if ( attribute.isGLBufferAttribute ) {
  43123. const cached = buffers.get( attribute );
  43124. if ( ! cached || cached.version < attribute.version ) {
  43125. buffers.set( attribute, {
  43126. buffer: attribute.buffer,
  43127. type: attribute.type,
  43128. bytesPerElement: attribute.elementSize,
  43129. version: attribute.version
  43130. } );
  43131. }
  43132. return;
  43133. }
  43134. const data = buffers.get( attribute );
  43135. if ( data === undefined ) {
  43136. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  43137. } else if ( data.version < attribute.version ) {
  43138. if ( data.size !== attribute.array.byteLength ) {
  43139. 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.' );
  43140. }
  43141. updateBuffer( data.buffer, attribute, bufferType );
  43142. data.version = attribute.version;
  43143. }
  43144. }
  43145. return {
  43146. get: get,
  43147. remove: remove,
  43148. update: update
  43149. };
  43150. }
  43151. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  43152. 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";
  43153. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  43154. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  43155. 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";
  43156. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  43157. 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";
  43158. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  43159. 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";
  43160. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  43161. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  43162. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  43163. 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";
  43164. 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";
  43165. 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";
  43166. 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";
  43167. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  43168. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  43169. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  43170. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  43171. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  43172. 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";
  43173. 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";
  43174. 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";
  43175. 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";
  43176. 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";
  43177. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  43178. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  43179. 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";
  43180. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  43181. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  43182. 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}";
  43183. 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";
  43184. 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";
  43185. 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";
  43186. 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";
  43187. 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";
  43188. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  43189. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  43190. 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";
  43191. 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";
  43192. 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}";
  43193. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  43194. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  43195. 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";
  43196. 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";
  43197. 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";
  43198. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  43199. 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";
  43200. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  43201. 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";
  43202. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  43203. var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  43204. 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";
  43205. 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";
  43206. 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";
  43207. 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";
  43208. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43209. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  43210. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  43211. 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";
  43212. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  43213. 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";
  43214. 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";
  43215. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  43216. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  43217. 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";
  43218. 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";
  43219. 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";
  43220. 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";
  43221. 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";
  43222. 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;";
  43223. 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";
  43224. 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";
  43225. 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";
  43226. 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";
  43227. 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";
  43228. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43229. 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";
  43230. 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";
  43231. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43232. 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 );";
  43233. 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}";
  43234. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43235. 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;";
  43236. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43237. 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";
  43238. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43239. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43240. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat dp = 1.0 - shadowCoord.z;\n\t\t\t\t#else\n\t\t\t\t\tfloat dp = shadowCoord.z;\n\t\t\t\t#endif\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, dp ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, dp ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, dp ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, dp ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, dp ) )\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\tfloat hard_shadow = step( shadowCoord.z, mean );\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\tdepth = 1.0 - depth;\n\t\t\t\t#endif\n\t\t\t\tshadow = step( shadowCoord.z, depth );\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\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tfloat dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp -= shadowBias;\n\t\t\t#else\n\t\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\t\tdp += shadowBias;\n\t\t\t#endif\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 ) * PI2;\n\t\t\tvec2 sample0 = vogelDiskSample( 0, 5, phi );\n\t\t\tvec2 sample1 = vogelDiskSample( 1, 5, phi );\n\t\t\tvec2 sample2 = vogelDiskSample( 2, 5, phi );\n\t\t\tvec2 sample3 = vogelDiskSample( 3, 5, phi );\n\t\t\tvec2 sample4 = vogelDiskSample( 4, 5, phi );\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.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 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\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tshadow = step( dp, depth );\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43241. 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";
  43242. 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";
  43243. 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}";
  43244. 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";
  43245. 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";
  43246. 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";
  43247. 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";
  43248. 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";
  43249. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43250. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43251. 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; }";
  43252. 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";
  43253. 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";
  43254. 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";
  43255. 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";
  43256. 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";
  43257. 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";
  43258. 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}";
  43259. 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}";
  43260. 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}";
  43261. 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}";
  43262. 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}";
  43263. 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}";
  43264. 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}";
  43265. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  43266. 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}";
  43267. 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}";
  43268. 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}";
  43269. 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}";
  43270. 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}";
  43271. 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}";
  43272. 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}";
  43273. 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}";
  43274. 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}";
  43275. 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}";
  43276. 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}";
  43277. 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}";
  43278. 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}";
  43279. 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}";
  43280. 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}";
  43281. 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}";
  43282. 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}";
  43283. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43284. 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}";
  43285. 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}";
  43286. 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}";
  43287. 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}";
  43288. 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}";
  43289. 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\t#include <premultiplied_alpha_fragment>\n}";
  43290. 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}";
  43291. 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}";
  43292. const ShaderChunk = {
  43293. alphahash_fragment: alphahash_fragment,
  43294. alphahash_pars_fragment: alphahash_pars_fragment,
  43295. alphamap_fragment: alphamap_fragment,
  43296. alphamap_pars_fragment: alphamap_pars_fragment,
  43297. alphatest_fragment: alphatest_fragment,
  43298. alphatest_pars_fragment: alphatest_pars_fragment,
  43299. aomap_fragment: aomap_fragment,
  43300. aomap_pars_fragment: aomap_pars_fragment,
  43301. batching_pars_vertex: batching_pars_vertex,
  43302. batching_vertex: batching_vertex,
  43303. begin_vertex: begin_vertex,
  43304. beginnormal_vertex: beginnormal_vertex,
  43305. bsdfs: bsdfs,
  43306. iridescence_fragment: iridescence_fragment,
  43307. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43308. clipping_planes_fragment: clipping_planes_fragment,
  43309. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43310. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43311. clipping_planes_vertex: clipping_planes_vertex,
  43312. color_fragment: color_fragment,
  43313. color_pars_fragment: color_pars_fragment,
  43314. color_pars_vertex: color_pars_vertex,
  43315. color_vertex: color_vertex,
  43316. common: common,
  43317. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43318. defaultnormal_vertex: defaultnormal_vertex,
  43319. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43320. displacementmap_vertex: displacementmap_vertex,
  43321. emissivemap_fragment: emissivemap_fragment,
  43322. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43323. colorspace_fragment: colorspace_fragment,
  43324. colorspace_pars_fragment: colorspace_pars_fragment,
  43325. envmap_fragment: envmap_fragment,
  43326. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43327. envmap_pars_fragment: envmap_pars_fragment,
  43328. envmap_pars_vertex: envmap_pars_vertex,
  43329. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43330. envmap_vertex: envmap_vertex,
  43331. fog_vertex: fog_vertex,
  43332. fog_pars_vertex: fog_pars_vertex,
  43333. fog_fragment: fog_fragment,
  43334. fog_pars_fragment: fog_pars_fragment,
  43335. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43336. lightmap_pars_fragment: lightmap_pars_fragment,
  43337. lights_lambert_fragment: lights_lambert_fragment,
  43338. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43339. lights_pars_begin: lights_pars_begin,
  43340. lights_toon_fragment: lights_toon_fragment,
  43341. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43342. lights_phong_fragment: lights_phong_fragment,
  43343. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43344. lights_physical_fragment: lights_physical_fragment,
  43345. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43346. lights_fragment_begin: lights_fragment_begin,
  43347. lights_fragment_maps: lights_fragment_maps,
  43348. lights_fragment_end: lights_fragment_end,
  43349. logdepthbuf_fragment: logdepthbuf_fragment,
  43350. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43351. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43352. logdepthbuf_vertex: logdepthbuf_vertex,
  43353. map_fragment: map_fragment,
  43354. map_pars_fragment: map_pars_fragment,
  43355. map_particle_fragment: map_particle_fragment,
  43356. map_particle_pars_fragment: map_particle_pars_fragment,
  43357. metalnessmap_fragment: metalnessmap_fragment,
  43358. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43359. morphinstance_vertex: morphinstance_vertex,
  43360. morphcolor_vertex: morphcolor_vertex,
  43361. morphnormal_vertex: morphnormal_vertex,
  43362. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43363. morphtarget_vertex: morphtarget_vertex,
  43364. normal_fragment_begin: normal_fragment_begin,
  43365. normal_fragment_maps: normal_fragment_maps,
  43366. normal_pars_fragment: normal_pars_fragment,
  43367. normal_pars_vertex: normal_pars_vertex,
  43368. normal_vertex: normal_vertex,
  43369. normalmap_pars_fragment: normalmap_pars_fragment,
  43370. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43371. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43372. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43373. iridescence_pars_fragment: iridescence_pars_fragment,
  43374. opaque_fragment: opaque_fragment,
  43375. packing: packing,
  43376. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43377. project_vertex: project_vertex,
  43378. dithering_fragment: dithering_fragment,
  43379. dithering_pars_fragment: dithering_pars_fragment,
  43380. roughnessmap_fragment: roughnessmap_fragment,
  43381. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43382. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43383. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43384. shadowmap_vertex: shadowmap_vertex,
  43385. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43386. skinbase_vertex: skinbase_vertex,
  43387. skinning_pars_vertex: skinning_pars_vertex,
  43388. skinning_vertex: skinning_vertex,
  43389. skinnormal_vertex: skinnormal_vertex,
  43390. specularmap_fragment: specularmap_fragment,
  43391. specularmap_pars_fragment: specularmap_pars_fragment,
  43392. tonemapping_fragment: tonemapping_fragment,
  43393. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43394. transmission_fragment: transmission_fragment,
  43395. transmission_pars_fragment: transmission_pars_fragment,
  43396. uv_pars_fragment: uv_pars_fragment,
  43397. uv_pars_vertex: uv_pars_vertex,
  43398. uv_vertex: uv_vertex,
  43399. worldpos_vertex: worldpos_vertex,
  43400. background_vert: vertex$h,
  43401. background_frag: fragment$h,
  43402. backgroundCube_vert: vertex$g,
  43403. backgroundCube_frag: fragment$g,
  43404. cube_vert: vertex$f,
  43405. cube_frag: fragment$f,
  43406. depth_vert: vertex$e,
  43407. depth_frag: fragment$e,
  43408. distance_vert: vertex$d,
  43409. distance_frag: fragment$d,
  43410. equirect_vert: vertex$c,
  43411. equirect_frag: fragment$c,
  43412. linedashed_vert: vertex$b,
  43413. linedashed_frag: fragment$b,
  43414. meshbasic_vert: vertex$a,
  43415. meshbasic_frag: fragment$a,
  43416. meshlambert_vert: vertex$9,
  43417. meshlambert_frag: fragment$9,
  43418. meshmatcap_vert: vertex$8,
  43419. meshmatcap_frag: fragment$8,
  43420. meshnormal_vert: vertex$7,
  43421. meshnormal_frag: fragment$7,
  43422. meshphong_vert: vertex$6,
  43423. meshphong_frag: fragment$6,
  43424. meshphysical_vert: vertex$5,
  43425. meshphysical_frag: fragment$5,
  43426. meshtoon_vert: vertex$4,
  43427. meshtoon_frag: fragment$4,
  43428. points_vert: vertex$3,
  43429. points_frag: fragment$3,
  43430. shadow_vert: vertex$2,
  43431. shadow_frag: fragment$2,
  43432. sprite_vert: vertex$1,
  43433. sprite_frag: fragment$1
  43434. };
  43435. // Uniforms library for shared webgl shaders
  43436. const UniformsLib = {
  43437. common: {
  43438. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43439. opacity: { value: 1.0 },
  43440. map: { value: null },
  43441. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43442. alphaMap: { value: null },
  43443. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43444. alphaTest: { value: 0 }
  43445. },
  43446. specularmap: {
  43447. specularMap: { value: null },
  43448. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43449. },
  43450. envmap: {
  43451. envMap: { value: null },
  43452. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43453. flipEnvMap: { value: -1 },
  43454. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43455. ior: { value: 1.5 }, // physical
  43456. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43457. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43458. },
  43459. aomap: {
  43460. aoMap: { value: null },
  43461. aoMapIntensity: { value: 1 },
  43462. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43463. },
  43464. lightmap: {
  43465. lightMap: { value: null },
  43466. lightMapIntensity: { value: 1 },
  43467. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43468. },
  43469. bumpmap: {
  43470. bumpMap: { value: null },
  43471. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43472. bumpScale: { value: 1 }
  43473. },
  43474. normalmap: {
  43475. normalMap: { value: null },
  43476. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43477. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43478. },
  43479. displacementmap: {
  43480. displacementMap: { value: null },
  43481. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43482. displacementScale: { value: 1 },
  43483. displacementBias: { value: 0 }
  43484. },
  43485. emissivemap: {
  43486. emissiveMap: { value: null },
  43487. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43488. },
  43489. metalnessmap: {
  43490. metalnessMap: { value: null },
  43491. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43492. },
  43493. roughnessmap: {
  43494. roughnessMap: { value: null },
  43495. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43496. },
  43497. gradientmap: {
  43498. gradientMap: { value: null }
  43499. },
  43500. fog: {
  43501. fogDensity: { value: 0.00025 },
  43502. fogNear: { value: 1 },
  43503. fogFar: { value: 2000 },
  43504. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43505. },
  43506. lights: {
  43507. ambientLightColor: { value: [] },
  43508. lightProbe: { value: [] },
  43509. directionalLights: { value: [], properties: {
  43510. direction: {},
  43511. color: {}
  43512. } },
  43513. directionalLightShadows: { value: [], properties: {
  43514. shadowIntensity: 1,
  43515. shadowBias: {},
  43516. shadowNormalBias: {},
  43517. shadowRadius: {},
  43518. shadowMapSize: {}
  43519. } },
  43520. directionalShadowMatrix: { value: [] },
  43521. spotLights: { value: [], properties: {
  43522. color: {},
  43523. position: {},
  43524. direction: {},
  43525. distance: {},
  43526. coneCos: {},
  43527. penumbraCos: {},
  43528. decay: {}
  43529. } },
  43530. spotLightShadows: { value: [], properties: {
  43531. shadowIntensity: 1,
  43532. shadowBias: {},
  43533. shadowNormalBias: {},
  43534. shadowRadius: {},
  43535. shadowMapSize: {}
  43536. } },
  43537. spotLightMap: { value: [] },
  43538. spotLightMatrix: { value: [] },
  43539. pointLights: { value: [], properties: {
  43540. color: {},
  43541. position: {},
  43542. decay: {},
  43543. distance: {}
  43544. } },
  43545. pointLightShadows: { value: [], properties: {
  43546. shadowIntensity: 1,
  43547. shadowBias: {},
  43548. shadowNormalBias: {},
  43549. shadowRadius: {},
  43550. shadowMapSize: {},
  43551. shadowCameraNear: {},
  43552. shadowCameraFar: {}
  43553. } },
  43554. pointShadowMatrix: { value: [] },
  43555. hemisphereLights: { value: [], properties: {
  43556. direction: {},
  43557. skyColor: {},
  43558. groundColor: {}
  43559. } },
  43560. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43561. rectAreaLights: { value: [], properties: {
  43562. color: {},
  43563. position: {},
  43564. width: {},
  43565. height: {}
  43566. } },
  43567. ltc_1: { value: null },
  43568. ltc_2: { value: null }
  43569. },
  43570. points: {
  43571. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43572. opacity: { value: 1.0 },
  43573. size: { value: 1.0 },
  43574. scale: { value: 1.0 },
  43575. map: { value: null },
  43576. alphaMap: { value: null },
  43577. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43578. alphaTest: { value: 0 },
  43579. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43580. },
  43581. sprite: {
  43582. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43583. opacity: { value: 1.0 },
  43584. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43585. rotation: { value: 0.0 },
  43586. map: { value: null },
  43587. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43588. alphaMap: { value: null },
  43589. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43590. alphaTest: { value: 0 }
  43591. }
  43592. };
  43593. const ShaderLib = {
  43594. basic: {
  43595. uniforms: /*@__PURE__*/ mergeUniforms( [
  43596. UniformsLib.common,
  43597. UniformsLib.specularmap,
  43598. UniformsLib.envmap,
  43599. UniformsLib.aomap,
  43600. UniformsLib.lightmap,
  43601. UniformsLib.fog
  43602. ] ),
  43603. vertexShader: ShaderChunk.meshbasic_vert,
  43604. fragmentShader: ShaderChunk.meshbasic_frag
  43605. },
  43606. lambert: {
  43607. uniforms: /*@__PURE__*/ mergeUniforms( [
  43608. UniformsLib.common,
  43609. UniformsLib.specularmap,
  43610. UniformsLib.envmap,
  43611. UniformsLib.aomap,
  43612. UniformsLib.lightmap,
  43613. UniformsLib.emissivemap,
  43614. UniformsLib.bumpmap,
  43615. UniformsLib.normalmap,
  43616. UniformsLib.displacementmap,
  43617. UniformsLib.fog,
  43618. UniformsLib.lights,
  43619. {
  43620. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43621. }
  43622. ] ),
  43623. vertexShader: ShaderChunk.meshlambert_vert,
  43624. fragmentShader: ShaderChunk.meshlambert_frag
  43625. },
  43626. phong: {
  43627. uniforms: /*@__PURE__*/ mergeUniforms( [
  43628. UniformsLib.common,
  43629. UniformsLib.specularmap,
  43630. UniformsLib.envmap,
  43631. UniformsLib.aomap,
  43632. UniformsLib.lightmap,
  43633. UniformsLib.emissivemap,
  43634. UniformsLib.bumpmap,
  43635. UniformsLib.normalmap,
  43636. UniformsLib.displacementmap,
  43637. UniformsLib.fog,
  43638. UniformsLib.lights,
  43639. {
  43640. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43641. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43642. shininess: { value: 30 }
  43643. }
  43644. ] ),
  43645. vertexShader: ShaderChunk.meshphong_vert,
  43646. fragmentShader: ShaderChunk.meshphong_frag
  43647. },
  43648. standard: {
  43649. uniforms: /*@__PURE__*/ mergeUniforms( [
  43650. UniformsLib.common,
  43651. UniformsLib.envmap,
  43652. UniformsLib.aomap,
  43653. UniformsLib.lightmap,
  43654. UniformsLib.emissivemap,
  43655. UniformsLib.bumpmap,
  43656. UniformsLib.normalmap,
  43657. UniformsLib.displacementmap,
  43658. UniformsLib.roughnessmap,
  43659. UniformsLib.metalnessmap,
  43660. UniformsLib.fog,
  43661. UniformsLib.lights,
  43662. {
  43663. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43664. roughness: { value: 1.0 },
  43665. metalness: { value: 0.0 },
  43666. envMapIntensity: { value: 1 }
  43667. }
  43668. ] ),
  43669. vertexShader: ShaderChunk.meshphysical_vert,
  43670. fragmentShader: ShaderChunk.meshphysical_frag
  43671. },
  43672. toon: {
  43673. uniforms: /*@__PURE__*/ mergeUniforms( [
  43674. UniformsLib.common,
  43675. UniformsLib.aomap,
  43676. UniformsLib.lightmap,
  43677. UniformsLib.emissivemap,
  43678. UniformsLib.bumpmap,
  43679. UniformsLib.normalmap,
  43680. UniformsLib.displacementmap,
  43681. UniformsLib.gradientmap,
  43682. UniformsLib.fog,
  43683. UniformsLib.lights,
  43684. {
  43685. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43686. }
  43687. ] ),
  43688. vertexShader: ShaderChunk.meshtoon_vert,
  43689. fragmentShader: ShaderChunk.meshtoon_frag
  43690. },
  43691. matcap: {
  43692. uniforms: /*@__PURE__*/ mergeUniforms( [
  43693. UniformsLib.common,
  43694. UniformsLib.bumpmap,
  43695. UniformsLib.normalmap,
  43696. UniformsLib.displacementmap,
  43697. UniformsLib.fog,
  43698. {
  43699. matcap: { value: null }
  43700. }
  43701. ] ),
  43702. vertexShader: ShaderChunk.meshmatcap_vert,
  43703. fragmentShader: ShaderChunk.meshmatcap_frag
  43704. },
  43705. points: {
  43706. uniforms: /*@__PURE__*/ mergeUniforms( [
  43707. UniformsLib.points,
  43708. UniformsLib.fog
  43709. ] ),
  43710. vertexShader: ShaderChunk.points_vert,
  43711. fragmentShader: ShaderChunk.points_frag
  43712. },
  43713. dashed: {
  43714. uniforms: /*@__PURE__*/ mergeUniforms( [
  43715. UniformsLib.common,
  43716. UniformsLib.fog,
  43717. {
  43718. scale: { value: 1 },
  43719. dashSize: { value: 1 },
  43720. totalSize: { value: 2 }
  43721. }
  43722. ] ),
  43723. vertexShader: ShaderChunk.linedashed_vert,
  43724. fragmentShader: ShaderChunk.linedashed_frag
  43725. },
  43726. depth: {
  43727. uniforms: /*@__PURE__*/ mergeUniforms( [
  43728. UniformsLib.common,
  43729. UniformsLib.displacementmap
  43730. ] ),
  43731. vertexShader: ShaderChunk.depth_vert,
  43732. fragmentShader: ShaderChunk.depth_frag
  43733. },
  43734. normal: {
  43735. uniforms: /*@__PURE__*/ mergeUniforms( [
  43736. UniformsLib.common,
  43737. UniformsLib.bumpmap,
  43738. UniformsLib.normalmap,
  43739. UniformsLib.displacementmap,
  43740. {
  43741. opacity: { value: 1.0 }
  43742. }
  43743. ] ),
  43744. vertexShader: ShaderChunk.meshnormal_vert,
  43745. fragmentShader: ShaderChunk.meshnormal_frag
  43746. },
  43747. sprite: {
  43748. uniforms: /*@__PURE__*/ mergeUniforms( [
  43749. UniformsLib.sprite,
  43750. UniformsLib.fog
  43751. ] ),
  43752. vertexShader: ShaderChunk.sprite_vert,
  43753. fragmentShader: ShaderChunk.sprite_frag
  43754. },
  43755. background: {
  43756. uniforms: {
  43757. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43758. t2D: { value: null },
  43759. backgroundIntensity: { value: 1 }
  43760. },
  43761. vertexShader: ShaderChunk.background_vert,
  43762. fragmentShader: ShaderChunk.background_frag
  43763. },
  43764. backgroundCube: {
  43765. uniforms: {
  43766. envMap: { value: null },
  43767. flipEnvMap: { value: -1 },
  43768. backgroundBlurriness: { value: 0 },
  43769. backgroundIntensity: { value: 1 },
  43770. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43771. },
  43772. vertexShader: ShaderChunk.backgroundCube_vert,
  43773. fragmentShader: ShaderChunk.backgroundCube_frag
  43774. },
  43775. cube: {
  43776. uniforms: {
  43777. tCube: { value: null },
  43778. tFlip: { value: -1 },
  43779. opacity: { value: 1.0 }
  43780. },
  43781. vertexShader: ShaderChunk.cube_vert,
  43782. fragmentShader: ShaderChunk.cube_frag
  43783. },
  43784. equirect: {
  43785. uniforms: {
  43786. tEquirect: { value: null },
  43787. },
  43788. vertexShader: ShaderChunk.equirect_vert,
  43789. fragmentShader: ShaderChunk.equirect_frag
  43790. },
  43791. distance: {
  43792. uniforms: /*@__PURE__*/ mergeUniforms( [
  43793. UniformsLib.common,
  43794. UniformsLib.displacementmap,
  43795. {
  43796. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43797. nearDistance: { value: 1 },
  43798. farDistance: { value: 1000 }
  43799. }
  43800. ] ),
  43801. vertexShader: ShaderChunk.distance_vert,
  43802. fragmentShader: ShaderChunk.distance_frag
  43803. },
  43804. shadow: {
  43805. uniforms: /*@__PURE__*/ mergeUniforms( [
  43806. UniformsLib.lights,
  43807. UniformsLib.fog,
  43808. {
  43809. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43810. opacity: { value: 1.0 }
  43811. },
  43812. ] ),
  43813. vertexShader: ShaderChunk.shadow_vert,
  43814. fragmentShader: ShaderChunk.shadow_frag
  43815. }
  43816. };
  43817. ShaderLib.physical = {
  43818. uniforms: /*@__PURE__*/ mergeUniforms( [
  43819. ShaderLib.standard.uniforms,
  43820. {
  43821. clearcoat: { value: 0 },
  43822. clearcoatMap: { value: null },
  43823. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43824. clearcoatNormalMap: { value: null },
  43825. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43826. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43827. clearcoatRoughness: { value: 0 },
  43828. clearcoatRoughnessMap: { value: null },
  43829. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43830. dispersion: { value: 0 },
  43831. iridescence: { value: 0 },
  43832. iridescenceMap: { value: null },
  43833. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43834. iridescenceIOR: { value: 1.3 },
  43835. iridescenceThicknessMinimum: { value: 100 },
  43836. iridescenceThicknessMaximum: { value: 400 },
  43837. iridescenceThicknessMap: { value: null },
  43838. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43839. sheen: { value: 0 },
  43840. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43841. sheenColorMap: { value: null },
  43842. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43843. sheenRoughness: { value: 1 },
  43844. sheenRoughnessMap: { value: null },
  43845. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43846. transmission: { value: 0 },
  43847. transmissionMap: { value: null },
  43848. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43849. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43850. transmissionSamplerMap: { value: null },
  43851. thickness: { value: 0 },
  43852. thicknessMap: { value: null },
  43853. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43854. attenuationDistance: { value: 0 },
  43855. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43856. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43857. specularColorMap: { value: null },
  43858. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43859. specularIntensity: { value: 1 },
  43860. specularIntensityMap: { value: null },
  43861. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43862. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43863. anisotropyMap: { value: null },
  43864. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43865. }
  43866. ] ),
  43867. vertexShader: ShaderChunk.meshphysical_vert,
  43868. fragmentShader: ShaderChunk.meshphysical_frag
  43869. };
  43870. const _rgb = { r: 0, b: 0, g: 0 };
  43871. const _e1$1 = /*@__PURE__*/ new Euler();
  43872. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43873. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43874. const clearColor = new Color( 0x000000 );
  43875. let clearAlpha = alpha === true ? 0 : 1;
  43876. let planeMesh;
  43877. let boxMesh;
  43878. let currentBackground = null;
  43879. let currentBackgroundVersion = 0;
  43880. let currentTonemapping = null;
  43881. function getBackground( scene ) {
  43882. let background = scene.isScene === true ? scene.background : null;
  43883. if ( background && background.isTexture ) {
  43884. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43885. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43886. }
  43887. return background;
  43888. }
  43889. function render( scene ) {
  43890. let forceClear = false;
  43891. const background = getBackground( scene );
  43892. if ( background === null ) {
  43893. setClear( clearColor, clearAlpha );
  43894. } else if ( background && background.isColor ) {
  43895. setClear( background, 1 );
  43896. forceClear = true;
  43897. }
  43898. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43899. if ( environmentBlendMode === 'additive' ) {
  43900. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43901. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43902. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43903. }
  43904. if ( renderer.autoClear || forceClear ) {
  43905. // buffers might not be writable which is required to ensure a correct clear
  43906. state.buffers.depth.setTest( true );
  43907. state.buffers.depth.setMask( true );
  43908. state.buffers.color.setMask( true );
  43909. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43910. }
  43911. }
  43912. function addToRenderList( renderList, scene ) {
  43913. const background = getBackground( scene );
  43914. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43915. if ( boxMesh === undefined ) {
  43916. boxMesh = new Mesh(
  43917. new BoxGeometry( 1, 1, 1 ),
  43918. new ShaderMaterial( {
  43919. name: 'BackgroundCubeMaterial',
  43920. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43921. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43922. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43923. side: BackSide,
  43924. depthTest: false,
  43925. depthWrite: false,
  43926. fog: false,
  43927. allowOverride: false
  43928. } )
  43929. );
  43930. boxMesh.geometry.deleteAttribute( 'normal' );
  43931. boxMesh.geometry.deleteAttribute( 'uv' );
  43932. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43933. this.matrixWorld.copyPosition( camera.matrixWorld );
  43934. };
  43935. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43936. Object.defineProperty( boxMesh.material, 'envMap', {
  43937. get: function () {
  43938. return this.uniforms.envMap.value;
  43939. }
  43940. } );
  43941. objects.update( boxMesh );
  43942. }
  43943. _e1$1.copy( scene.backgroundRotation );
  43944. // accommodate left-handed frame
  43945. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43946. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43947. // environment maps which are not cube render targets or PMREMs follow a different convention
  43948. _e1$1.y *= -1;
  43949. _e1$1.z *= -1;
  43950. }
  43951. boxMesh.material.uniforms.envMap.value = background;
  43952. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43953. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43954. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43955. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43956. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43957. if ( currentBackground !== background ||
  43958. currentBackgroundVersion !== background.version ||
  43959. currentTonemapping !== renderer.toneMapping ) {
  43960. boxMesh.material.needsUpdate = true;
  43961. currentBackground = background;
  43962. currentBackgroundVersion = background.version;
  43963. currentTonemapping = renderer.toneMapping;
  43964. }
  43965. boxMesh.layers.enableAll();
  43966. // push to the pre-sorted opaque render list
  43967. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43968. } else if ( background && background.isTexture ) {
  43969. if ( planeMesh === undefined ) {
  43970. planeMesh = new Mesh(
  43971. new PlaneGeometry( 2, 2 ),
  43972. new ShaderMaterial( {
  43973. name: 'BackgroundMaterial',
  43974. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43975. vertexShader: ShaderLib.background.vertexShader,
  43976. fragmentShader: ShaderLib.background.fragmentShader,
  43977. side: FrontSide,
  43978. depthTest: false,
  43979. depthWrite: false,
  43980. fog: false,
  43981. allowOverride: false
  43982. } )
  43983. );
  43984. planeMesh.geometry.deleteAttribute( 'normal' );
  43985. // add "map" material property so the renderer can evaluate it like for built-in materials
  43986. Object.defineProperty( planeMesh.material, 'map', {
  43987. get: function () {
  43988. return this.uniforms.t2D.value;
  43989. }
  43990. } );
  43991. objects.update( planeMesh );
  43992. }
  43993. planeMesh.material.uniforms.t2D.value = background;
  43994. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43995. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43996. if ( background.matrixAutoUpdate === true ) {
  43997. background.updateMatrix();
  43998. }
  43999. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  44000. if ( currentBackground !== background ||
  44001. currentBackgroundVersion !== background.version ||
  44002. currentTonemapping !== renderer.toneMapping ) {
  44003. planeMesh.material.needsUpdate = true;
  44004. currentBackground = background;
  44005. currentBackgroundVersion = background.version;
  44006. currentTonemapping = renderer.toneMapping;
  44007. }
  44008. planeMesh.layers.enableAll();
  44009. // push to the pre-sorted opaque render list
  44010. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  44011. }
  44012. }
  44013. function setClear( color, alpha ) {
  44014. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  44015. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  44016. }
  44017. function dispose() {
  44018. if ( boxMesh !== undefined ) {
  44019. boxMesh.geometry.dispose();
  44020. boxMesh.material.dispose();
  44021. boxMesh = undefined;
  44022. }
  44023. if ( planeMesh !== undefined ) {
  44024. planeMesh.geometry.dispose();
  44025. planeMesh.material.dispose();
  44026. planeMesh = undefined;
  44027. }
  44028. }
  44029. return {
  44030. getClearColor: function () {
  44031. return clearColor;
  44032. },
  44033. setClearColor: function ( color, alpha = 1 ) {
  44034. clearColor.set( color );
  44035. clearAlpha = alpha;
  44036. setClear( clearColor, clearAlpha );
  44037. },
  44038. getClearAlpha: function () {
  44039. return clearAlpha;
  44040. },
  44041. setClearAlpha: function ( alpha ) {
  44042. clearAlpha = alpha;
  44043. setClear( clearColor, clearAlpha );
  44044. },
  44045. render: render,
  44046. addToRenderList: addToRenderList,
  44047. dispose: dispose
  44048. };
  44049. }
  44050. function WebGLBindingStates( gl, attributes ) {
  44051. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44052. const bindingStates = {};
  44053. const defaultState = createBindingState( null );
  44054. let currentState = defaultState;
  44055. let forceUpdate = false;
  44056. function setup( object, material, program, geometry, index ) {
  44057. let updateBuffers = false;
  44058. const state = getBindingState( object, geometry, program, material );
  44059. if ( currentState !== state ) {
  44060. currentState = state;
  44061. bindVertexArrayObject( currentState.object );
  44062. }
  44063. updateBuffers = needsUpdate( object, geometry, program, index );
  44064. if ( updateBuffers ) saveCache( object, geometry, program, index );
  44065. if ( index !== null ) {
  44066. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  44067. }
  44068. if ( updateBuffers || forceUpdate ) {
  44069. forceUpdate = false;
  44070. setupVertexAttributes( object, material, program, geometry );
  44071. if ( index !== null ) {
  44072. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  44073. }
  44074. }
  44075. }
  44076. function createVertexArrayObject() {
  44077. return gl.createVertexArray();
  44078. }
  44079. function bindVertexArrayObject( vao ) {
  44080. return gl.bindVertexArray( vao );
  44081. }
  44082. function deleteVertexArrayObject( vao ) {
  44083. return gl.deleteVertexArray( vao );
  44084. }
  44085. function getBindingState( object, geometry, program, material ) {
  44086. const wireframe = ( material.wireframe === true );
  44087. let objectMap = bindingStates[ geometry.id ];
  44088. if ( objectMap === undefined ) {
  44089. objectMap = {};
  44090. bindingStates[ geometry.id ] = objectMap;
  44091. }
  44092. // Each InstancedMesh requires unique binding states because it contains instanced attributes.
  44093. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44094. let programMap = objectMap[ objectId ];
  44095. if ( programMap === undefined ) {
  44096. programMap = {};
  44097. objectMap[ objectId ] = programMap;
  44098. }
  44099. let stateMap = programMap[ program.id ];
  44100. if ( stateMap === undefined ) {
  44101. stateMap = {};
  44102. programMap[ program.id ] = stateMap;
  44103. }
  44104. let state = stateMap[ wireframe ];
  44105. if ( state === undefined ) {
  44106. state = createBindingState( createVertexArrayObject() );
  44107. stateMap[ wireframe ] = state;
  44108. }
  44109. return state;
  44110. }
  44111. function createBindingState( vao ) {
  44112. const newAttributes = [];
  44113. const enabledAttributes = [];
  44114. const attributeDivisors = [];
  44115. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  44116. newAttributes[ i ] = 0;
  44117. enabledAttributes[ i ] = 0;
  44118. attributeDivisors[ i ] = 0;
  44119. }
  44120. return {
  44121. // for backward compatibility on non-VAO support browser
  44122. geometry: null,
  44123. program: null,
  44124. wireframe: false,
  44125. newAttributes: newAttributes,
  44126. enabledAttributes: enabledAttributes,
  44127. attributeDivisors: attributeDivisors,
  44128. object: vao,
  44129. attributes: {},
  44130. index: null
  44131. };
  44132. }
  44133. function needsUpdate( object, geometry, program, index ) {
  44134. const cachedAttributes = currentState.attributes;
  44135. const geometryAttributes = geometry.attributes;
  44136. let attributesNum = 0;
  44137. const programAttributes = program.getAttributes();
  44138. for ( const name in programAttributes ) {
  44139. const programAttribute = programAttributes[ name ];
  44140. if ( programAttribute.location >= 0 ) {
  44141. const cachedAttribute = cachedAttributes[ name ];
  44142. let geometryAttribute = geometryAttributes[ name ];
  44143. if ( geometryAttribute === undefined ) {
  44144. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44145. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44146. }
  44147. if ( cachedAttribute === undefined ) return true;
  44148. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  44149. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  44150. attributesNum ++;
  44151. }
  44152. }
  44153. if ( currentState.attributesNum !== attributesNum ) return true;
  44154. if ( currentState.index !== index ) return true;
  44155. return false;
  44156. }
  44157. function saveCache( object, geometry, program, index ) {
  44158. const cache = {};
  44159. const attributes = geometry.attributes;
  44160. let attributesNum = 0;
  44161. const programAttributes = program.getAttributes();
  44162. for ( const name in programAttributes ) {
  44163. const programAttribute = programAttributes[ name ];
  44164. if ( programAttribute.location >= 0 ) {
  44165. let attribute = attributes[ name ];
  44166. if ( attribute === undefined ) {
  44167. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  44168. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  44169. }
  44170. const data = {};
  44171. data.attribute = attribute;
  44172. if ( attribute && attribute.data ) {
  44173. data.data = attribute.data;
  44174. }
  44175. cache[ name ] = data;
  44176. attributesNum ++;
  44177. }
  44178. }
  44179. currentState.attributes = cache;
  44180. currentState.attributesNum = attributesNum;
  44181. currentState.index = index;
  44182. }
  44183. function initAttributes() {
  44184. const newAttributes = currentState.newAttributes;
  44185. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  44186. newAttributes[ i ] = 0;
  44187. }
  44188. }
  44189. function enableAttribute( attribute ) {
  44190. enableAttributeAndDivisor( attribute, 0 );
  44191. }
  44192. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  44193. const newAttributes = currentState.newAttributes;
  44194. const enabledAttributes = currentState.enabledAttributes;
  44195. const attributeDivisors = currentState.attributeDivisors;
  44196. newAttributes[ attribute ] = 1;
  44197. if ( enabledAttributes[ attribute ] === 0 ) {
  44198. gl.enableVertexAttribArray( attribute );
  44199. enabledAttributes[ attribute ] = 1;
  44200. }
  44201. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  44202. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  44203. attributeDivisors[ attribute ] = meshPerAttribute;
  44204. }
  44205. }
  44206. function disableUnusedAttributes() {
  44207. const newAttributes = currentState.newAttributes;
  44208. const enabledAttributes = currentState.enabledAttributes;
  44209. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  44210. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  44211. gl.disableVertexAttribArray( i );
  44212. enabledAttributes[ i ] = 0;
  44213. }
  44214. }
  44215. }
  44216. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  44217. if ( integer === true ) {
  44218. gl.vertexAttribIPointer( index, size, type, stride, offset );
  44219. } else {
  44220. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  44221. }
  44222. }
  44223. function setupVertexAttributes( object, material, program, geometry ) {
  44224. initAttributes();
  44225. const geometryAttributes = geometry.attributes;
  44226. const programAttributes = program.getAttributes();
  44227. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44228. for ( const name in programAttributes ) {
  44229. const programAttribute = programAttributes[ name ];
  44230. if ( programAttribute.location >= 0 ) {
  44231. let geometryAttribute = geometryAttributes[ name ];
  44232. if ( geometryAttribute === undefined ) {
  44233. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44234. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44235. }
  44236. if ( geometryAttribute !== undefined ) {
  44237. const normalized = geometryAttribute.normalized;
  44238. const size = geometryAttribute.itemSize;
  44239. const attribute = attributes.get( geometryAttribute );
  44240. // TODO Attribute may not be available on context restore
  44241. if ( attribute === undefined ) continue;
  44242. const buffer = attribute.buffer;
  44243. const type = attribute.type;
  44244. const bytesPerElement = attribute.bytesPerElement;
  44245. // check for integer attributes
  44246. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44247. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44248. const data = geometryAttribute.data;
  44249. const stride = data.stride;
  44250. const offset = geometryAttribute.offset;
  44251. if ( data.isInstancedInterleavedBuffer ) {
  44252. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44253. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44254. }
  44255. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44256. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44257. }
  44258. } else {
  44259. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44260. enableAttribute( programAttribute.location + i );
  44261. }
  44262. }
  44263. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44264. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44265. vertexAttribPointer(
  44266. programAttribute.location + i,
  44267. size / programAttribute.locationSize,
  44268. type,
  44269. normalized,
  44270. stride * bytesPerElement,
  44271. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44272. integer
  44273. );
  44274. }
  44275. } else {
  44276. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44277. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44278. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44279. }
  44280. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44281. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44282. }
  44283. } else {
  44284. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44285. enableAttribute( programAttribute.location + i );
  44286. }
  44287. }
  44288. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44289. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44290. vertexAttribPointer(
  44291. programAttribute.location + i,
  44292. size / programAttribute.locationSize,
  44293. type,
  44294. normalized,
  44295. size * bytesPerElement,
  44296. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44297. integer
  44298. );
  44299. }
  44300. }
  44301. } else if ( materialDefaultAttributeValues !== undefined ) {
  44302. const value = materialDefaultAttributeValues[ name ];
  44303. if ( value !== undefined ) {
  44304. switch ( value.length ) {
  44305. case 2:
  44306. gl.vertexAttrib2fv( programAttribute.location, value );
  44307. break;
  44308. case 3:
  44309. gl.vertexAttrib3fv( programAttribute.location, value );
  44310. break;
  44311. case 4:
  44312. gl.vertexAttrib4fv( programAttribute.location, value );
  44313. break;
  44314. default:
  44315. gl.vertexAttrib1fv( programAttribute.location, value );
  44316. }
  44317. }
  44318. }
  44319. }
  44320. }
  44321. disableUnusedAttributes();
  44322. }
  44323. function dispose() {
  44324. reset();
  44325. for ( const geometryId in bindingStates ) {
  44326. const objectMap = bindingStates[ geometryId ];
  44327. for ( const objectId in objectMap ) {
  44328. const programMap = objectMap[ objectId ];
  44329. for ( const programId in programMap ) {
  44330. const stateMap = programMap[ programId ];
  44331. for ( const wireframe in stateMap ) {
  44332. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44333. delete stateMap[ wireframe ];
  44334. }
  44335. delete programMap[ programId ];
  44336. }
  44337. }
  44338. delete bindingStates[ geometryId ];
  44339. }
  44340. }
  44341. function releaseStatesOfGeometry( geometry ) {
  44342. if ( bindingStates[ geometry.id ] === undefined ) return;
  44343. const objectMap = bindingStates[ geometry.id ];
  44344. for ( const objectId in objectMap ) {
  44345. const programMap = objectMap[ objectId ];
  44346. for ( const programId in programMap ) {
  44347. const stateMap = programMap[ programId ];
  44348. for ( const wireframe in stateMap ) {
  44349. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44350. delete stateMap[ wireframe ];
  44351. }
  44352. delete programMap[ programId ];
  44353. }
  44354. }
  44355. delete bindingStates[ geometry.id ];
  44356. }
  44357. function releaseStatesOfProgram( program ) {
  44358. for ( const geometryId in bindingStates ) {
  44359. const objectMap = bindingStates[ geometryId ];
  44360. for ( const objectId in objectMap ) {
  44361. const programMap = objectMap[ objectId ];
  44362. if ( programMap[ program.id ] === undefined ) continue;
  44363. const stateMap = programMap[ program.id ];
  44364. for ( const wireframe in stateMap ) {
  44365. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44366. delete stateMap[ wireframe ];
  44367. }
  44368. delete programMap[ program.id ];
  44369. }
  44370. }
  44371. }
  44372. function releaseStatesOfObject( object ) {
  44373. for ( const geometryId in bindingStates ) {
  44374. const objectMap = bindingStates[ geometryId ];
  44375. const objectId = ( object.isInstancedMesh === true ) ? object.id : 0;
  44376. const programMap = objectMap[ objectId ];
  44377. if ( programMap === undefined ) continue;
  44378. for ( const programId in programMap ) {
  44379. const stateMap = programMap[ programId ];
  44380. for ( const wireframe in stateMap ) {
  44381. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44382. delete stateMap[ wireframe ];
  44383. }
  44384. delete programMap[ programId ];
  44385. }
  44386. delete objectMap[ objectId ];
  44387. if ( Object.keys( objectMap ).length === 0 ) {
  44388. delete bindingStates[ geometryId ];
  44389. }
  44390. }
  44391. }
  44392. function reset() {
  44393. resetDefaultState();
  44394. forceUpdate = true;
  44395. if ( currentState === defaultState ) return;
  44396. currentState = defaultState;
  44397. bindVertexArrayObject( currentState.object );
  44398. }
  44399. // for backward-compatibility
  44400. function resetDefaultState() {
  44401. defaultState.geometry = null;
  44402. defaultState.program = null;
  44403. defaultState.wireframe = false;
  44404. }
  44405. return {
  44406. setup: setup,
  44407. reset: reset,
  44408. resetDefaultState: resetDefaultState,
  44409. dispose: dispose,
  44410. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44411. releaseStatesOfObject: releaseStatesOfObject,
  44412. releaseStatesOfProgram: releaseStatesOfProgram,
  44413. initAttributes: initAttributes,
  44414. enableAttribute: enableAttribute,
  44415. disableUnusedAttributes: disableUnusedAttributes
  44416. };
  44417. }
  44418. function WebGLBufferRenderer( gl, extensions, info ) {
  44419. let mode;
  44420. function setMode( value ) {
  44421. mode = value;
  44422. }
  44423. function render( start, count ) {
  44424. gl.drawArrays( mode, start, count );
  44425. info.update( count, mode, 1 );
  44426. }
  44427. function renderInstances( start, count, primcount ) {
  44428. if ( primcount === 0 ) return;
  44429. gl.drawArraysInstanced( mode, start, count, primcount );
  44430. info.update( count, mode, primcount );
  44431. }
  44432. function renderMultiDraw( starts, counts, drawCount ) {
  44433. if ( drawCount === 0 ) return;
  44434. const extension = extensions.get( 'WEBGL_multi_draw' );
  44435. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44436. let elementCount = 0;
  44437. for ( let i = 0; i < drawCount; i ++ ) {
  44438. elementCount += counts[ i ];
  44439. }
  44440. info.update( elementCount, mode, 1 );
  44441. }
  44442. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44443. if ( drawCount === 0 ) return;
  44444. const extension = extensions.get( 'WEBGL_multi_draw' );
  44445. if ( extension === null ) {
  44446. for ( let i = 0; i < starts.length; i ++ ) {
  44447. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44448. }
  44449. } else {
  44450. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44451. let elementCount = 0;
  44452. for ( let i = 0; i < drawCount; i ++ ) {
  44453. elementCount += counts[ i ] * primcount[ i ];
  44454. }
  44455. info.update( elementCount, mode, 1 );
  44456. }
  44457. }
  44458. //
  44459. this.setMode = setMode;
  44460. this.render = render;
  44461. this.renderInstances = renderInstances;
  44462. this.renderMultiDraw = renderMultiDraw;
  44463. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44464. }
  44465. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44466. let maxAnisotropy;
  44467. function getMaxAnisotropy() {
  44468. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44469. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44470. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44471. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44472. } else {
  44473. maxAnisotropy = 0;
  44474. }
  44475. return maxAnisotropy;
  44476. }
  44477. function textureFormatReadable( textureFormat ) {
  44478. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44479. return false;
  44480. }
  44481. return true;
  44482. }
  44483. function textureTypeReadable( textureType ) {
  44484. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44485. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44486. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44487. return false;
  44488. }
  44489. return true;
  44490. }
  44491. function getMaxPrecision( precision ) {
  44492. if ( precision === 'highp' ) {
  44493. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44494. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44495. return 'highp';
  44496. }
  44497. precision = 'mediump';
  44498. }
  44499. if ( precision === 'mediump' ) {
  44500. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44501. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44502. return 'mediump';
  44503. }
  44504. }
  44505. return 'lowp';
  44506. }
  44507. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44508. const maxPrecision = getMaxPrecision( precision );
  44509. if ( maxPrecision !== precision ) {
  44510. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44511. precision = maxPrecision;
  44512. }
  44513. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44514. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44515. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44516. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44517. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44518. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44519. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44520. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44521. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44522. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44523. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44524. const samples = gl.getParameter( gl.SAMPLES );
  44525. return {
  44526. isWebGL2: true, // keeping this for backwards compatibility
  44527. getMaxAnisotropy: getMaxAnisotropy,
  44528. getMaxPrecision: getMaxPrecision,
  44529. textureFormatReadable: textureFormatReadable,
  44530. textureTypeReadable: textureTypeReadable,
  44531. precision: precision,
  44532. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44533. reversedDepthBuffer: reversedDepthBuffer,
  44534. maxTextures: maxTextures,
  44535. maxVertexTextures: maxVertexTextures,
  44536. maxTextureSize: maxTextureSize,
  44537. maxCubemapSize: maxCubemapSize,
  44538. maxAttributes: maxAttributes,
  44539. maxVertexUniforms: maxVertexUniforms,
  44540. maxVaryings: maxVaryings,
  44541. maxFragmentUniforms: maxFragmentUniforms,
  44542. maxSamples: maxSamples,
  44543. samples: samples
  44544. };
  44545. }
  44546. function WebGLClipping( properties ) {
  44547. const scope = this;
  44548. let globalState = null,
  44549. numGlobalPlanes = 0,
  44550. localClippingEnabled = false,
  44551. renderingShadows = false;
  44552. const plane = new Plane(),
  44553. viewNormalMatrix = new Matrix3(),
  44554. uniform = { value: null, needsUpdate: false };
  44555. this.uniform = uniform;
  44556. this.numPlanes = 0;
  44557. this.numIntersection = 0;
  44558. this.init = function ( planes, enableLocalClipping ) {
  44559. const enabled =
  44560. planes.length !== 0 ||
  44561. enableLocalClipping ||
  44562. // enable state of previous frame - the clipping code has to
  44563. // run another frame in order to reset the state:
  44564. numGlobalPlanes !== 0 ||
  44565. localClippingEnabled;
  44566. localClippingEnabled = enableLocalClipping;
  44567. numGlobalPlanes = planes.length;
  44568. return enabled;
  44569. };
  44570. this.beginShadows = function () {
  44571. renderingShadows = true;
  44572. projectPlanes( null );
  44573. };
  44574. this.endShadows = function () {
  44575. renderingShadows = false;
  44576. };
  44577. this.setGlobalState = function ( planes, camera ) {
  44578. globalState = projectPlanes( planes, camera, 0 );
  44579. };
  44580. this.setState = function ( material, camera, useCache ) {
  44581. const planes = material.clippingPlanes,
  44582. clipIntersection = material.clipIntersection,
  44583. clipShadows = material.clipShadows;
  44584. const materialProperties = properties.get( material );
  44585. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44586. // there's no local clipping
  44587. if ( renderingShadows ) {
  44588. // there's no global clipping
  44589. projectPlanes( null );
  44590. } else {
  44591. resetGlobalState();
  44592. }
  44593. } else {
  44594. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44595. lGlobal = nGlobal * 4;
  44596. let dstArray = materialProperties.clippingState || null;
  44597. uniform.value = dstArray; // ensure unique state
  44598. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44599. for ( let i = 0; i !== lGlobal; ++ i ) {
  44600. dstArray[ i ] = globalState[ i ];
  44601. }
  44602. materialProperties.clippingState = dstArray;
  44603. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44604. this.numPlanes += nGlobal;
  44605. }
  44606. };
  44607. function resetGlobalState() {
  44608. if ( uniform.value !== globalState ) {
  44609. uniform.value = globalState;
  44610. uniform.needsUpdate = numGlobalPlanes > 0;
  44611. }
  44612. scope.numPlanes = numGlobalPlanes;
  44613. scope.numIntersection = 0;
  44614. }
  44615. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44616. const nPlanes = planes !== null ? planes.length : 0;
  44617. let dstArray = null;
  44618. if ( nPlanes !== 0 ) {
  44619. dstArray = uniform.value;
  44620. if ( skipTransform !== true || dstArray === null ) {
  44621. const flatSize = dstOffset + nPlanes * 4,
  44622. viewMatrix = camera.matrixWorldInverse;
  44623. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44624. if ( dstArray === null || dstArray.length < flatSize ) {
  44625. dstArray = new Float32Array( flatSize );
  44626. }
  44627. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44628. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44629. plane.normal.toArray( dstArray, i4 );
  44630. dstArray[ i4 + 3 ] = plane.constant;
  44631. }
  44632. }
  44633. uniform.value = dstArray;
  44634. uniform.needsUpdate = true;
  44635. }
  44636. scope.numPlanes = nPlanes;
  44637. scope.numIntersection = 0;
  44638. return dstArray;
  44639. }
  44640. }
  44641. function WebGLCubeMaps( renderer ) {
  44642. let cubemaps = new WeakMap();
  44643. function mapTextureMapping( texture, mapping ) {
  44644. if ( mapping === EquirectangularReflectionMapping ) {
  44645. texture.mapping = CubeReflectionMapping;
  44646. } else if ( mapping === EquirectangularRefractionMapping ) {
  44647. texture.mapping = CubeRefractionMapping;
  44648. }
  44649. return texture;
  44650. }
  44651. function get( texture ) {
  44652. if ( texture && texture.isTexture ) {
  44653. const mapping = texture.mapping;
  44654. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44655. if ( cubemaps.has( texture ) ) {
  44656. const cubemap = cubemaps.get( texture ).texture;
  44657. return mapTextureMapping( cubemap, texture.mapping );
  44658. } else {
  44659. const image = texture.image;
  44660. if ( image && image.height > 0 ) {
  44661. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44662. renderTarget.fromEquirectangularTexture( renderer, texture );
  44663. cubemaps.set( texture, renderTarget );
  44664. texture.addEventListener( 'dispose', onTextureDispose );
  44665. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44666. } else {
  44667. // image not yet ready. try the conversion next frame
  44668. return null;
  44669. }
  44670. }
  44671. }
  44672. }
  44673. return texture;
  44674. }
  44675. function onTextureDispose( event ) {
  44676. const texture = event.target;
  44677. texture.removeEventListener( 'dispose', onTextureDispose );
  44678. const cubemap = cubemaps.get( texture );
  44679. if ( cubemap !== undefined ) {
  44680. cubemaps.delete( texture );
  44681. cubemap.dispose();
  44682. }
  44683. }
  44684. function dispose() {
  44685. cubemaps = new WeakMap();
  44686. }
  44687. return {
  44688. get: get,
  44689. dispose: dispose
  44690. };
  44691. }
  44692. const LOD_MIN = 4;
  44693. // The standard deviations (radians) associated with the extra mips.
  44694. // Used for scene blur in fromScene() method.
  44695. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44696. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44697. // samples and exit early, but not recompile the shader.
  44698. // Used for scene blur in fromScene() method.
  44699. const MAX_SAMPLES = 20;
  44700. // GGX VNDF importance sampling configuration
  44701. const GGX_SAMPLES = 256;
  44702. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44703. const _clearColor = /*@__PURE__*/ new Color();
  44704. let _oldTarget = null;
  44705. let _oldActiveCubeFace = 0;
  44706. let _oldActiveMipmapLevel = 0;
  44707. let _oldXrEnabled = false;
  44708. const _origin = /*@__PURE__*/ new Vector3();
  44709. /**
  44710. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44711. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44712. * blur to be quickly accessed based on material roughness. It is packed into a
  44713. * special CubeUV format that allows us to perform custom interpolation so that
  44714. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44715. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44716. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44717. * higher roughness levels. In this way we maintain resolution to smoothly
  44718. * interpolate diffuse lighting while limiting sampling computation.
  44719. *
  44720. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44721. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44722. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44723. * used in material rendering for physically-based image-based lighting.
  44724. */
  44725. class PMREMGenerator {
  44726. /**
  44727. * Constructs a new PMREM generator.
  44728. *
  44729. * @param {WebGLRenderer} renderer - The renderer.
  44730. */
  44731. constructor( renderer ) {
  44732. this._renderer = renderer;
  44733. this._pingPongRenderTarget = null;
  44734. this._lodMax = 0;
  44735. this._cubeSize = 0;
  44736. this._sizeLods = [];
  44737. this._sigmas = [];
  44738. this._lodMeshes = [];
  44739. this._backgroundBox = null;
  44740. this._cubemapMaterial = null;
  44741. this._equirectMaterial = null;
  44742. this._blurMaterial = null;
  44743. this._ggxMaterial = null;
  44744. }
  44745. /**
  44746. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44747. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44748. * in radians to be applied to the scene before PMREM generation. Optional near
  44749. * and far planes ensure the scene is rendered in its entirety.
  44750. *
  44751. * @param {Scene} scene - The scene to be captured.
  44752. * @param {number} [sigma=0] - The blur radius in radians.
  44753. * @param {number} [near=0.1] - The near plane distance.
  44754. * @param {number} [far=100] - The far plane distance.
  44755. * @param {Object} [options={}] - The configuration options.
  44756. * @param {number} [options.size=256] - The texture size of the PMREM.
  44757. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44758. * @return {WebGLRenderTarget} The resulting PMREM.
  44759. */
  44760. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44761. const {
  44762. size = 256,
  44763. position = _origin,
  44764. } = options;
  44765. _oldTarget = this._renderer.getRenderTarget();
  44766. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44767. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44768. _oldXrEnabled = this._renderer.xr.enabled;
  44769. this._renderer.xr.enabled = false;
  44770. this._setSize( size );
  44771. const cubeUVRenderTarget = this._allocateTargets();
  44772. cubeUVRenderTarget.depthBuffer = true;
  44773. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44774. if ( sigma > 0 ) {
  44775. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44776. }
  44777. this._applyPMREM( cubeUVRenderTarget );
  44778. this._cleanup( cubeUVRenderTarget );
  44779. return cubeUVRenderTarget;
  44780. }
  44781. /**
  44782. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44783. * or HDR. The ideal input image size is 1k (1024 x 512),
  44784. * as this matches best with the 256 x 256 cubemap output.
  44785. *
  44786. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44787. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44788. * @return {WebGLRenderTarget} The resulting PMREM.
  44789. */
  44790. fromEquirectangular( equirectangular, renderTarget = null ) {
  44791. return this._fromTexture( equirectangular, renderTarget );
  44792. }
  44793. /**
  44794. * Generates a PMREM from an cubemap texture, which can be either LDR
  44795. * or HDR. The ideal input cube size is 256 x 256,
  44796. * as this matches best with the 256 x 256 cubemap output.
  44797. *
  44798. * @param {Texture} cubemap - The cubemap texture to be converted.
  44799. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44800. * @return {WebGLRenderTarget} The resulting PMREM.
  44801. */
  44802. fromCubemap( cubemap, renderTarget = null ) {
  44803. return this._fromTexture( cubemap, renderTarget );
  44804. }
  44805. /**
  44806. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44807. * your texture's network fetch for increased concurrency.
  44808. */
  44809. compileCubemapShader() {
  44810. if ( this._cubemapMaterial === null ) {
  44811. this._cubemapMaterial = _getCubemapMaterial();
  44812. this._compileMaterial( this._cubemapMaterial );
  44813. }
  44814. }
  44815. /**
  44816. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44817. * your texture's network fetch for increased concurrency.
  44818. */
  44819. compileEquirectangularShader() {
  44820. if ( this._equirectMaterial === null ) {
  44821. this._equirectMaterial = _getEquirectMaterial();
  44822. this._compileMaterial( this._equirectMaterial );
  44823. }
  44824. }
  44825. /**
  44826. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44827. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44828. * one of them will cause any others to also become unusable.
  44829. */
  44830. dispose() {
  44831. this._dispose();
  44832. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44833. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44834. if ( this._backgroundBox !== null ) {
  44835. this._backgroundBox.geometry.dispose();
  44836. this._backgroundBox.material.dispose();
  44837. }
  44838. }
  44839. // private interface
  44840. _setSize( cubeSize ) {
  44841. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44842. this._cubeSize = Math.pow( 2, this._lodMax );
  44843. }
  44844. _dispose() {
  44845. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44846. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44847. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44848. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44849. this._lodMeshes[ i ].geometry.dispose();
  44850. }
  44851. }
  44852. _cleanup( outputTarget ) {
  44853. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44854. this._renderer.xr.enabled = _oldXrEnabled;
  44855. outputTarget.scissorTest = false;
  44856. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44857. }
  44858. _fromTexture( texture, renderTarget ) {
  44859. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44860. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44861. } else { // Equirectangular
  44862. this._setSize( texture.image.width / 4 );
  44863. }
  44864. _oldTarget = this._renderer.getRenderTarget();
  44865. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44866. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44867. _oldXrEnabled = this._renderer.xr.enabled;
  44868. this._renderer.xr.enabled = false;
  44869. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44870. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44871. this._applyPMREM( cubeUVRenderTarget );
  44872. this._cleanup( cubeUVRenderTarget );
  44873. return cubeUVRenderTarget;
  44874. }
  44875. _allocateTargets() {
  44876. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44877. const height = 4 * this._cubeSize;
  44878. const params = {
  44879. magFilter: LinearFilter,
  44880. minFilter: LinearFilter,
  44881. generateMipmaps: false,
  44882. type: HalfFloatType,
  44883. format: RGBAFormat,
  44884. colorSpace: LinearSRGBColorSpace,
  44885. depthBuffer: false
  44886. };
  44887. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44888. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44889. if ( this._pingPongRenderTarget !== null ) {
  44890. this._dispose();
  44891. }
  44892. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44893. const { _lodMax } = this;
  44894. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44895. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44896. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44897. }
  44898. return cubeUVRenderTarget;
  44899. }
  44900. _compileMaterial( material ) {
  44901. const mesh = new Mesh( new BufferGeometry(), material );
  44902. this._renderer.compile( mesh, _flatCamera );
  44903. }
  44904. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44905. const fov = 90;
  44906. const aspect = 1;
  44907. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44908. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44909. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44910. const renderer = this._renderer;
  44911. const originalAutoClear = renderer.autoClear;
  44912. const toneMapping = renderer.toneMapping;
  44913. renderer.getClearColor( _clearColor );
  44914. renderer.toneMapping = NoToneMapping;
  44915. renderer.autoClear = false;
  44916. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44917. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44918. if ( reversedDepthBuffer ) {
  44919. renderer.setRenderTarget( cubeUVRenderTarget );
  44920. renderer.clearDepth();
  44921. renderer.setRenderTarget( null );
  44922. }
  44923. if ( this._backgroundBox === null ) {
  44924. this._backgroundBox = new Mesh(
  44925. new BoxGeometry(),
  44926. new MeshBasicMaterial( {
  44927. name: 'PMREM.Background',
  44928. side: BackSide,
  44929. depthWrite: false,
  44930. depthTest: false,
  44931. } )
  44932. );
  44933. }
  44934. const backgroundBox = this._backgroundBox;
  44935. const backgroundMaterial = backgroundBox.material;
  44936. let useSolidColor = false;
  44937. const background = scene.background;
  44938. if ( background ) {
  44939. if ( background.isColor ) {
  44940. backgroundMaterial.color.copy( background );
  44941. scene.background = null;
  44942. useSolidColor = true;
  44943. }
  44944. } else {
  44945. backgroundMaterial.color.copy( _clearColor );
  44946. useSolidColor = true;
  44947. }
  44948. for ( let i = 0; i < 6; i ++ ) {
  44949. const col = i % 3;
  44950. if ( col === 0 ) {
  44951. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44952. cubeCamera.position.set( position.x, position.y, position.z );
  44953. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44954. } else if ( col === 1 ) {
  44955. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44956. cubeCamera.position.set( position.x, position.y, position.z );
  44957. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44958. } else {
  44959. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44960. cubeCamera.position.set( position.x, position.y, position.z );
  44961. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44962. }
  44963. const size = this._cubeSize;
  44964. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44965. renderer.setRenderTarget( cubeUVRenderTarget );
  44966. if ( useSolidColor ) {
  44967. renderer.render( backgroundBox, cubeCamera );
  44968. }
  44969. renderer.render( scene, cubeCamera );
  44970. }
  44971. renderer.toneMapping = toneMapping;
  44972. renderer.autoClear = originalAutoClear;
  44973. scene.background = background;
  44974. }
  44975. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44976. const renderer = this._renderer;
  44977. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44978. if ( isCubeTexture ) {
  44979. if ( this._cubemapMaterial === null ) {
  44980. this._cubemapMaterial = _getCubemapMaterial();
  44981. }
  44982. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44983. } else {
  44984. if ( this._equirectMaterial === null ) {
  44985. this._equirectMaterial = _getEquirectMaterial();
  44986. }
  44987. }
  44988. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44989. const mesh = this._lodMeshes[ 0 ];
  44990. mesh.material = material;
  44991. const uniforms = material.uniforms;
  44992. uniforms[ 'envMap' ].value = texture;
  44993. const size = this._cubeSize;
  44994. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44995. renderer.setRenderTarget( cubeUVRenderTarget );
  44996. renderer.render( mesh, _flatCamera );
  44997. }
  44998. _applyPMREM( cubeUVRenderTarget ) {
  44999. const renderer = this._renderer;
  45000. const autoClear = renderer.autoClear;
  45001. renderer.autoClear = false;
  45002. const n = this._lodMeshes.length;
  45003. // Use GGX VNDF importance sampling
  45004. for ( let i = 1; i < n; i ++ ) {
  45005. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  45006. }
  45007. renderer.autoClear = autoClear;
  45008. }
  45009. /**
  45010. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  45011. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  45012. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  45013. * applies incremental roughness filtering to avoid over-blurring.
  45014. *
  45015. * @private
  45016. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45017. * @param {number} lodIn - Source LOD level to read from
  45018. * @param {number} lodOut - Target LOD level to write to
  45019. */
  45020. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  45021. const renderer = this._renderer;
  45022. const pingPongRenderTarget = this._pingPongRenderTarget;
  45023. const ggxMaterial = this._ggxMaterial;
  45024. const ggxMesh = this._lodMeshes[ lodOut ];
  45025. ggxMesh.material = ggxMaterial;
  45026. const ggxUniforms = ggxMaterial.uniforms;
  45027. // Calculate incremental roughness between LOD levels
  45028. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  45029. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  45030. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  45031. // Apply blur strength mapping for better quality across the roughness range
  45032. const blurStrength = 0.0 + targetRoughness * 1.25;
  45033. const adjustedRoughness = incrementalRoughness * blurStrength;
  45034. // Calculate viewport position based on output LOD level
  45035. const { _lodMax } = this;
  45036. const outputSize = this._sizeLods[ lodOut ];
  45037. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45038. const y = 4 * ( this._cubeSize - outputSize );
  45039. // Read from previous LOD with incremental roughness
  45040. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  45041. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  45042. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  45043. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45044. renderer.setRenderTarget( pingPongRenderTarget );
  45045. renderer.render( ggxMesh, _flatCamera );
  45046. // Copy from pingPong back to cubeUV (simple direct copy)
  45047. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  45048. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  45049. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  45050. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  45051. renderer.setRenderTarget( cubeUVRenderTarget );
  45052. renderer.render( ggxMesh, _flatCamera );
  45053. }
  45054. /**
  45055. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  45056. * vertically and horizontally, but this breaks down on a cube. Here we apply
  45057. * the blur latitudinally (around the poles), and then longitudinally (towards
  45058. * the poles) to approximate the orthogonally-separable blur. It is least
  45059. * accurate at the poles, but still does a decent job.
  45060. *
  45061. * Used for initial scene blur in fromScene() method when sigma > 0.
  45062. *
  45063. * @private
  45064. * @param {WebGLRenderTarget} cubeUVRenderTarget
  45065. * @param {number} lodIn
  45066. * @param {number} lodOut
  45067. * @param {number} sigma
  45068. * @param {Vector3} [poleAxis]
  45069. */
  45070. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  45071. const pingPongRenderTarget = this._pingPongRenderTarget;
  45072. this._halfBlur(
  45073. cubeUVRenderTarget,
  45074. pingPongRenderTarget,
  45075. lodIn,
  45076. lodOut,
  45077. sigma,
  45078. 'latitudinal',
  45079. poleAxis );
  45080. this._halfBlur(
  45081. pingPongRenderTarget,
  45082. cubeUVRenderTarget,
  45083. lodOut,
  45084. lodOut,
  45085. sigma,
  45086. 'longitudinal',
  45087. poleAxis );
  45088. }
  45089. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  45090. const renderer = this._renderer;
  45091. const blurMaterial = this._blurMaterial;
  45092. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  45093. error(
  45094. 'blur direction must be either latitudinal or longitudinal!' );
  45095. }
  45096. // Number of standard deviations at which to cut off the discrete approximation.
  45097. const STANDARD_DEVIATIONS = 3;
  45098. const blurMesh = this._lodMeshes[ lodOut ];
  45099. blurMesh.material = blurMaterial;
  45100. const blurUniforms = blurMaterial.uniforms;
  45101. const pixels = this._sizeLods[ lodIn ] - 1;
  45102. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  45103. const sigmaPixels = sigmaRadians / radiansPerPixel;
  45104. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  45105. if ( samples > MAX_SAMPLES ) {
  45106. warn( `sigmaRadians, ${
  45107. sigmaRadians}, is too large and will clip, as it requested ${
  45108. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  45109. }
  45110. const weights = [];
  45111. let sum = 0;
  45112. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  45113. const x = i / sigmaPixels;
  45114. const weight = Math.exp( - x * x / 2 );
  45115. weights.push( weight );
  45116. if ( i === 0 ) {
  45117. sum += weight;
  45118. } else if ( i < samples ) {
  45119. sum += 2 * weight;
  45120. }
  45121. }
  45122. for ( let i = 0; i < weights.length; i ++ ) {
  45123. weights[ i ] = weights[ i ] / sum;
  45124. }
  45125. blurUniforms[ 'envMap' ].value = targetIn.texture;
  45126. blurUniforms[ 'samples' ].value = samples;
  45127. blurUniforms[ 'weights' ].value = weights;
  45128. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  45129. if ( poleAxis ) {
  45130. blurUniforms[ 'poleAxis' ].value = poleAxis;
  45131. }
  45132. const { _lodMax } = this;
  45133. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  45134. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  45135. const outputSize = this._sizeLods[ lodOut ];
  45136. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  45137. const y = 4 * ( this._cubeSize - outputSize );
  45138. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  45139. renderer.setRenderTarget( targetOut );
  45140. renderer.render( blurMesh, _flatCamera );
  45141. }
  45142. }
  45143. function _createPlanes( lodMax ) {
  45144. const sizeLods = [];
  45145. const sigmas = [];
  45146. const lodMeshes = [];
  45147. let lod = lodMax;
  45148. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  45149. for ( let i = 0; i < totalLods; i ++ ) {
  45150. const sizeLod = Math.pow( 2, lod );
  45151. sizeLods.push( sizeLod );
  45152. let sigma = 1.0 / sizeLod;
  45153. if ( i > lodMax - LOD_MIN ) {
  45154. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  45155. } else if ( i === 0 ) {
  45156. sigma = 0;
  45157. }
  45158. sigmas.push( sigma );
  45159. const texelSize = 1.0 / ( sizeLod - 2 );
  45160. const min = - texelSize;
  45161. const max = 1 + texelSize;
  45162. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  45163. const cubeFaces = 6;
  45164. const vertices = 6;
  45165. const positionSize = 3;
  45166. const uvSize = 2;
  45167. const faceIndexSize = 1;
  45168. const position = new Float32Array( positionSize * vertices * cubeFaces );
  45169. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  45170. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  45171. for ( let face = 0; face < cubeFaces; face ++ ) {
  45172. const x = ( face % 3 ) * 2 / 3 - 1;
  45173. const y = face > 2 ? 0 : -1;
  45174. const coordinates = [
  45175. x, y, 0,
  45176. x + 2 / 3, y, 0,
  45177. x + 2 / 3, y + 1, 0,
  45178. x, y, 0,
  45179. x + 2 / 3, y + 1, 0,
  45180. x, y + 1, 0
  45181. ];
  45182. position.set( coordinates, positionSize * vertices * face );
  45183. uv.set( uv1, uvSize * vertices * face );
  45184. const fill = [ face, face, face, face, face, face ];
  45185. faceIndex.set( fill, faceIndexSize * vertices * face );
  45186. }
  45187. const planes = new BufferGeometry();
  45188. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  45189. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  45190. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  45191. lodMeshes.push( new Mesh( planes, null ) );
  45192. if ( lod > LOD_MIN ) {
  45193. lod --;
  45194. }
  45195. }
  45196. return { lodMeshes, sizeLods, sigmas };
  45197. }
  45198. function _createRenderTarget( width, height, params ) {
  45199. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  45200. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  45201. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  45202. cubeUVRenderTarget.scissorTest = true;
  45203. return cubeUVRenderTarget;
  45204. }
  45205. function _setViewport( target, x, y, width, height ) {
  45206. target.viewport.set( x, y, width, height );
  45207. target.scissor.set( x, y, width, height );
  45208. }
  45209. function _getGGXShader( lodMax, width, height ) {
  45210. const shaderMaterial = new ShaderMaterial( {
  45211. name: 'PMREMGGXConvolution',
  45212. defines: {
  45213. 'GGX_SAMPLES': GGX_SAMPLES,
  45214. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45215. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45216. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45217. },
  45218. uniforms: {
  45219. 'envMap': { value: null },
  45220. 'roughness': { value: 0.0 },
  45221. 'mipInt': { value: 0 }
  45222. },
  45223. vertexShader: _getCommonVertexShader(),
  45224. fragmentShader: /* glsl */`
  45225. precision highp float;
  45226. precision highp int;
  45227. varying vec3 vOutputDirection;
  45228. uniform sampler2D envMap;
  45229. uniform float roughness;
  45230. uniform float mipInt;
  45231. #define ENVMAP_TYPE_CUBE_UV
  45232. #include <cube_uv_reflection_fragment>
  45233. #define PI 3.14159265359
  45234. // Van der Corput radical inverse
  45235. float radicalInverse_VdC(uint bits) {
  45236. bits = (bits << 16u) | (bits >> 16u);
  45237. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  45238. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  45239. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  45240. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  45241. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  45242. }
  45243. // Hammersley sequence
  45244. vec2 hammersley(uint i, uint N) {
  45245. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  45246. }
  45247. // GGX VNDF importance sampling (Eric Heitz 2018)
  45248. // "Sampling the GGX Distribution of Visible Normals"
  45249. // https://jcgt.org/published/0007/04/01/
  45250. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  45251. float alpha = roughness * roughness;
  45252. // Section 4.1: Orthonormal basis
  45253. vec3 T1 = vec3(1.0, 0.0, 0.0);
  45254. vec3 T2 = cross(V, T1);
  45255. // Section 4.2: Parameterization of projected area
  45256. float r = sqrt(Xi.x);
  45257. float phi = 2.0 * PI * Xi.y;
  45258. float t1 = r * cos(phi);
  45259. float t2 = r * sin(phi);
  45260. float s = 0.5 * (1.0 + V.z);
  45261. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45262. // Section 4.3: Reprojection onto hemisphere
  45263. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V;
  45264. // Section 3.4: Transform back to ellipsoid configuration
  45265. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45266. }
  45267. void main() {
  45268. vec3 N = normalize(vOutputDirection);
  45269. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45270. vec3 prefilteredColor = vec3(0.0);
  45271. float totalWeight = 0.0;
  45272. // For very low roughness, just sample the environment directly
  45273. if (roughness < 0.001) {
  45274. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45275. return;
  45276. }
  45277. // Tangent space basis for VNDF sampling
  45278. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45279. vec3 tangent = normalize(cross(up, N));
  45280. vec3 bitangent = cross(N, tangent);
  45281. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45282. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45283. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45284. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45285. // Transform H back to world space
  45286. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45287. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45288. float NdotL = max(dot(N, L), 0.0);
  45289. if(NdotL > 0.0) {
  45290. // Sample environment at fixed mip level
  45291. // VNDF importance sampling handles the distribution filtering
  45292. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45293. // Weight by NdotL for the split-sum approximation
  45294. // VNDF PDF naturally accounts for the visible microfacet distribution
  45295. prefilteredColor += sampleColor * NdotL;
  45296. totalWeight += NdotL;
  45297. }
  45298. }
  45299. if (totalWeight > 0.0) {
  45300. prefilteredColor = prefilteredColor / totalWeight;
  45301. }
  45302. gl_FragColor = vec4(prefilteredColor, 1.0);
  45303. }
  45304. `,
  45305. blending: NoBlending,
  45306. depthTest: false,
  45307. depthWrite: false
  45308. } );
  45309. return shaderMaterial;
  45310. }
  45311. function _getBlurShader( lodMax, width, height ) {
  45312. const weights = new Float32Array( MAX_SAMPLES );
  45313. const poleAxis = new Vector3( 0, 1, 0 );
  45314. const shaderMaterial = new ShaderMaterial( {
  45315. name: 'SphericalGaussianBlur',
  45316. defines: {
  45317. 'n': MAX_SAMPLES,
  45318. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45319. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45320. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45321. },
  45322. uniforms: {
  45323. 'envMap': { value: null },
  45324. 'samples': { value: 1 },
  45325. 'weights': { value: weights },
  45326. 'latitudinal': { value: false },
  45327. 'dTheta': { value: 0 },
  45328. 'mipInt': { value: 0 },
  45329. 'poleAxis': { value: poleAxis }
  45330. },
  45331. vertexShader: _getCommonVertexShader(),
  45332. fragmentShader: /* glsl */`
  45333. precision mediump float;
  45334. precision mediump int;
  45335. varying vec3 vOutputDirection;
  45336. uniform sampler2D envMap;
  45337. uniform int samples;
  45338. uniform float weights[ n ];
  45339. uniform bool latitudinal;
  45340. uniform float dTheta;
  45341. uniform float mipInt;
  45342. uniform vec3 poleAxis;
  45343. #define ENVMAP_TYPE_CUBE_UV
  45344. #include <cube_uv_reflection_fragment>
  45345. vec3 getSample( float theta, vec3 axis ) {
  45346. float cosTheta = cos( theta );
  45347. // Rodrigues' axis-angle rotation
  45348. vec3 sampleDirection = vOutputDirection * cosTheta
  45349. + cross( axis, vOutputDirection ) * sin( theta )
  45350. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45351. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45352. }
  45353. void main() {
  45354. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45355. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45356. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45357. }
  45358. axis = normalize( axis );
  45359. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45360. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45361. for ( int i = 1; i < n; i++ ) {
  45362. if ( i >= samples ) {
  45363. break;
  45364. }
  45365. float theta = dTheta * float( i );
  45366. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45367. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45368. }
  45369. }
  45370. `,
  45371. blending: NoBlending,
  45372. depthTest: false,
  45373. depthWrite: false
  45374. } );
  45375. return shaderMaterial;
  45376. }
  45377. function _getEquirectMaterial() {
  45378. return new ShaderMaterial( {
  45379. name: 'EquirectangularToCubeUV',
  45380. uniforms: {
  45381. 'envMap': { value: null }
  45382. },
  45383. vertexShader: _getCommonVertexShader(),
  45384. fragmentShader: /* glsl */`
  45385. precision mediump float;
  45386. precision mediump int;
  45387. varying vec3 vOutputDirection;
  45388. uniform sampler2D envMap;
  45389. #include <common>
  45390. void main() {
  45391. vec3 outputDirection = normalize( vOutputDirection );
  45392. vec2 uv = equirectUv( outputDirection );
  45393. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45394. }
  45395. `,
  45396. blending: NoBlending,
  45397. depthTest: false,
  45398. depthWrite: false
  45399. } );
  45400. }
  45401. function _getCubemapMaterial() {
  45402. return new ShaderMaterial( {
  45403. name: 'CubemapToCubeUV',
  45404. uniforms: {
  45405. 'envMap': { value: null },
  45406. 'flipEnvMap': { value: -1 }
  45407. },
  45408. vertexShader: _getCommonVertexShader(),
  45409. fragmentShader: /* glsl */`
  45410. precision mediump float;
  45411. precision mediump int;
  45412. uniform float flipEnvMap;
  45413. varying vec3 vOutputDirection;
  45414. uniform samplerCube envMap;
  45415. void main() {
  45416. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45417. }
  45418. `,
  45419. blending: NoBlending,
  45420. depthTest: false,
  45421. depthWrite: false
  45422. } );
  45423. }
  45424. function _getCommonVertexShader() {
  45425. return /* glsl */`
  45426. precision mediump float;
  45427. precision mediump int;
  45428. attribute float faceIndex;
  45429. varying vec3 vOutputDirection;
  45430. // RH coordinate system; PMREM face-indexing convention
  45431. vec3 getDirection( vec2 uv, float face ) {
  45432. uv = 2.0 * uv - 1.0;
  45433. vec3 direction = vec3( uv, 1.0 );
  45434. if ( face == 0.0 ) {
  45435. direction = direction.zyx; // ( 1, v, u ) pos x
  45436. } else if ( face == 1.0 ) {
  45437. direction = direction.xzy;
  45438. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45439. } else if ( face == 2.0 ) {
  45440. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45441. } else if ( face == 3.0 ) {
  45442. direction = direction.zyx;
  45443. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45444. } else if ( face == 4.0 ) {
  45445. direction = direction.xzy;
  45446. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45447. } else if ( face == 5.0 ) {
  45448. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45449. }
  45450. return direction;
  45451. }
  45452. void main() {
  45453. vOutputDirection = getDirection( uv, faceIndex );
  45454. gl_Position = vec4( position, 1.0 );
  45455. }
  45456. `;
  45457. }
  45458. function WebGLCubeUVMaps( renderer ) {
  45459. let cubeUVmaps = new WeakMap();
  45460. let pmremGenerator = null;
  45461. function get( texture ) {
  45462. if ( texture && texture.isTexture ) {
  45463. const mapping = texture.mapping;
  45464. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45465. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45466. // equirect/cube map to cubeUV conversion
  45467. if ( isEquirectMap || isCubeMap ) {
  45468. let renderTarget = cubeUVmaps.get( texture );
  45469. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45470. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45471. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45472. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45473. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45474. cubeUVmaps.set( texture, renderTarget );
  45475. return renderTarget.texture;
  45476. } else {
  45477. if ( renderTarget !== undefined ) {
  45478. return renderTarget.texture;
  45479. } else {
  45480. const image = texture.image;
  45481. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45482. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45483. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45484. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45485. cubeUVmaps.set( texture, renderTarget );
  45486. texture.addEventListener( 'dispose', onTextureDispose );
  45487. return renderTarget.texture;
  45488. } else {
  45489. // image not yet ready. try the conversion next frame
  45490. return null;
  45491. }
  45492. }
  45493. }
  45494. }
  45495. }
  45496. return texture;
  45497. }
  45498. function isCubeTextureComplete( image ) {
  45499. let count = 0;
  45500. const length = 6;
  45501. for ( let i = 0; i < length; i ++ ) {
  45502. if ( image[ i ] !== undefined ) count ++;
  45503. }
  45504. return count === length;
  45505. }
  45506. function onTextureDispose( event ) {
  45507. const texture = event.target;
  45508. texture.removeEventListener( 'dispose', onTextureDispose );
  45509. const cubemapUV = cubeUVmaps.get( texture );
  45510. if ( cubemapUV !== undefined ) {
  45511. cubeUVmaps.delete( texture );
  45512. cubemapUV.dispose();
  45513. }
  45514. }
  45515. function dispose() {
  45516. cubeUVmaps = new WeakMap();
  45517. if ( pmremGenerator !== null ) {
  45518. pmremGenerator.dispose();
  45519. pmremGenerator = null;
  45520. }
  45521. }
  45522. return {
  45523. get: get,
  45524. dispose: dispose
  45525. };
  45526. }
  45527. function WebGLExtensions( gl ) {
  45528. const extensions = {};
  45529. function getExtension( name ) {
  45530. if ( extensions[ name ] !== undefined ) {
  45531. return extensions[ name ];
  45532. }
  45533. const extension = gl.getExtension( name );
  45534. extensions[ name ] = extension;
  45535. return extension;
  45536. }
  45537. return {
  45538. has: function ( name ) {
  45539. return getExtension( name ) !== null;
  45540. },
  45541. init: function () {
  45542. getExtension( 'EXT_color_buffer_float' );
  45543. getExtension( 'WEBGL_clip_cull_distance' );
  45544. getExtension( 'OES_texture_float_linear' );
  45545. getExtension( 'EXT_color_buffer_half_float' );
  45546. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45547. getExtension( 'WEBGL_render_shared_exponent' );
  45548. },
  45549. get: function ( name ) {
  45550. const extension = getExtension( name );
  45551. if ( extension === null ) {
  45552. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45553. }
  45554. return extension;
  45555. }
  45556. };
  45557. }
  45558. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45559. const geometries = {};
  45560. const wireframeAttributes = new WeakMap();
  45561. function onGeometryDispose( event ) {
  45562. const geometry = event.target;
  45563. if ( geometry.index !== null ) {
  45564. attributes.remove( geometry.index );
  45565. }
  45566. for ( const name in geometry.attributes ) {
  45567. attributes.remove( geometry.attributes[ name ] );
  45568. }
  45569. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45570. delete geometries[ geometry.id ];
  45571. const attribute = wireframeAttributes.get( geometry );
  45572. if ( attribute ) {
  45573. attributes.remove( attribute );
  45574. wireframeAttributes.delete( geometry );
  45575. }
  45576. bindingStates.releaseStatesOfGeometry( geometry );
  45577. if ( geometry.isInstancedBufferGeometry === true ) {
  45578. delete geometry._maxInstanceCount;
  45579. }
  45580. //
  45581. info.memory.geometries --;
  45582. }
  45583. function get( object, geometry ) {
  45584. if ( geometries[ geometry.id ] === true ) return geometry;
  45585. geometry.addEventListener( 'dispose', onGeometryDispose );
  45586. geometries[ geometry.id ] = true;
  45587. info.memory.geometries ++;
  45588. return geometry;
  45589. }
  45590. function update( geometry ) {
  45591. const geometryAttributes = geometry.attributes;
  45592. // Updating index buffer in VAO now. See WebGLBindingStates.
  45593. for ( const name in geometryAttributes ) {
  45594. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45595. }
  45596. }
  45597. function updateWireframeAttribute( geometry ) {
  45598. const indices = [];
  45599. const geometryIndex = geometry.index;
  45600. const geometryPosition = geometry.attributes.position;
  45601. let version = 0;
  45602. if ( geometryIndex !== null ) {
  45603. const array = geometryIndex.array;
  45604. version = geometryIndex.version;
  45605. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45606. const a = array[ i + 0 ];
  45607. const b = array[ i + 1 ];
  45608. const c = array[ i + 2 ];
  45609. indices.push( a, b, b, c, c, a );
  45610. }
  45611. } else if ( geometryPosition !== undefined ) {
  45612. const array = geometryPosition.array;
  45613. version = geometryPosition.version;
  45614. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45615. const a = i + 0;
  45616. const b = i + 1;
  45617. const c = i + 2;
  45618. indices.push( a, b, b, c, c, a );
  45619. }
  45620. } else {
  45621. return;
  45622. }
  45623. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45624. attribute.version = version;
  45625. // Updating index buffer in VAO now. See WebGLBindingStates
  45626. //
  45627. const previousAttribute = wireframeAttributes.get( geometry );
  45628. if ( previousAttribute ) attributes.remove( previousAttribute );
  45629. //
  45630. wireframeAttributes.set( geometry, attribute );
  45631. }
  45632. function getWireframeAttribute( geometry ) {
  45633. const currentAttribute = wireframeAttributes.get( geometry );
  45634. if ( currentAttribute ) {
  45635. const geometryIndex = geometry.index;
  45636. if ( geometryIndex !== null ) {
  45637. // if the attribute is obsolete, create a new one
  45638. if ( currentAttribute.version < geometryIndex.version ) {
  45639. updateWireframeAttribute( geometry );
  45640. }
  45641. }
  45642. } else {
  45643. updateWireframeAttribute( geometry );
  45644. }
  45645. return wireframeAttributes.get( geometry );
  45646. }
  45647. return {
  45648. get: get,
  45649. update: update,
  45650. getWireframeAttribute: getWireframeAttribute
  45651. };
  45652. }
  45653. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45654. let mode;
  45655. function setMode( value ) {
  45656. mode = value;
  45657. }
  45658. let type, bytesPerElement;
  45659. function setIndex( value ) {
  45660. type = value.type;
  45661. bytesPerElement = value.bytesPerElement;
  45662. }
  45663. function render( start, count ) {
  45664. gl.drawElements( mode, count, type, start * bytesPerElement );
  45665. info.update( count, mode, 1 );
  45666. }
  45667. function renderInstances( start, count, primcount ) {
  45668. if ( primcount === 0 ) return;
  45669. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45670. info.update( count, mode, primcount );
  45671. }
  45672. function renderMultiDraw( starts, counts, drawCount ) {
  45673. if ( drawCount === 0 ) return;
  45674. const extension = extensions.get( 'WEBGL_multi_draw' );
  45675. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45676. let elementCount = 0;
  45677. for ( let i = 0; i < drawCount; i ++ ) {
  45678. elementCount += counts[ i ];
  45679. }
  45680. info.update( elementCount, mode, 1 );
  45681. }
  45682. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45683. if ( drawCount === 0 ) return;
  45684. const extension = extensions.get( 'WEBGL_multi_draw' );
  45685. if ( extension === null ) {
  45686. for ( let i = 0; i < starts.length; i ++ ) {
  45687. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45688. }
  45689. } else {
  45690. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45691. let elementCount = 0;
  45692. for ( let i = 0; i < drawCount; i ++ ) {
  45693. elementCount += counts[ i ] * primcount[ i ];
  45694. }
  45695. info.update( elementCount, mode, 1 );
  45696. }
  45697. }
  45698. //
  45699. this.setMode = setMode;
  45700. this.setIndex = setIndex;
  45701. this.render = render;
  45702. this.renderInstances = renderInstances;
  45703. this.renderMultiDraw = renderMultiDraw;
  45704. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45705. }
  45706. function WebGLInfo( gl ) {
  45707. const memory = {
  45708. geometries: 0,
  45709. textures: 0
  45710. };
  45711. const render = {
  45712. frame: 0,
  45713. calls: 0,
  45714. triangles: 0,
  45715. points: 0,
  45716. lines: 0
  45717. };
  45718. function update( count, mode, instanceCount ) {
  45719. render.calls ++;
  45720. switch ( mode ) {
  45721. case gl.TRIANGLES:
  45722. render.triangles += instanceCount * ( count / 3 );
  45723. break;
  45724. case gl.LINES:
  45725. render.lines += instanceCount * ( count / 2 );
  45726. break;
  45727. case gl.LINE_STRIP:
  45728. render.lines += instanceCount * ( count - 1 );
  45729. break;
  45730. case gl.LINE_LOOP:
  45731. render.lines += instanceCount * count;
  45732. break;
  45733. case gl.POINTS:
  45734. render.points += instanceCount * count;
  45735. break;
  45736. default:
  45737. error( 'WebGLInfo: Unknown draw mode:', mode );
  45738. break;
  45739. }
  45740. }
  45741. function reset() {
  45742. render.calls = 0;
  45743. render.triangles = 0;
  45744. render.points = 0;
  45745. render.lines = 0;
  45746. }
  45747. return {
  45748. memory: memory,
  45749. render: render,
  45750. programs: null,
  45751. autoReset: true,
  45752. reset: reset,
  45753. update: update
  45754. };
  45755. }
  45756. function WebGLMorphtargets( gl, capabilities, textures ) {
  45757. const morphTextures = new WeakMap();
  45758. const morph = new Vector4();
  45759. function update( object, geometry, program ) {
  45760. const objectInfluences = object.morphTargetInfluences;
  45761. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45762. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45763. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45764. let entry = morphTextures.get( geometry );
  45765. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45766. if ( entry !== undefined ) entry.texture.dispose();
  45767. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45768. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45769. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45770. const morphTargets = geometry.morphAttributes.position || [];
  45771. const morphNormals = geometry.morphAttributes.normal || [];
  45772. const morphColors = geometry.morphAttributes.color || [];
  45773. let vertexDataCount = 0;
  45774. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45775. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45776. if ( hasMorphColors === true ) vertexDataCount = 3;
  45777. let width = geometry.attributes.position.count * vertexDataCount;
  45778. let height = 1;
  45779. if ( width > capabilities.maxTextureSize ) {
  45780. height = Math.ceil( width / capabilities.maxTextureSize );
  45781. width = capabilities.maxTextureSize;
  45782. }
  45783. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45784. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45785. texture.type = FloatType;
  45786. texture.needsUpdate = true;
  45787. // fill buffer
  45788. const vertexDataStride = vertexDataCount * 4;
  45789. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45790. const morphTarget = morphTargets[ i ];
  45791. const morphNormal = morphNormals[ i ];
  45792. const morphColor = morphColors[ i ];
  45793. const offset = width * height * 4 * i;
  45794. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45795. const stride = j * vertexDataStride;
  45796. if ( hasMorphPosition === true ) {
  45797. morph.fromBufferAttribute( morphTarget, j );
  45798. buffer[ offset + stride + 0 ] = morph.x;
  45799. buffer[ offset + stride + 1 ] = morph.y;
  45800. buffer[ offset + stride + 2 ] = morph.z;
  45801. buffer[ offset + stride + 3 ] = 0;
  45802. }
  45803. if ( hasMorphNormals === true ) {
  45804. morph.fromBufferAttribute( morphNormal, j );
  45805. buffer[ offset + stride + 4 ] = morph.x;
  45806. buffer[ offset + stride + 5 ] = morph.y;
  45807. buffer[ offset + stride + 6 ] = morph.z;
  45808. buffer[ offset + stride + 7 ] = 0;
  45809. }
  45810. if ( hasMorphColors === true ) {
  45811. morph.fromBufferAttribute( morphColor, j );
  45812. buffer[ offset + stride + 8 ] = morph.x;
  45813. buffer[ offset + stride + 9 ] = morph.y;
  45814. buffer[ offset + stride + 10 ] = morph.z;
  45815. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45816. }
  45817. }
  45818. }
  45819. entry = {
  45820. count: morphTargetsCount,
  45821. texture: texture,
  45822. size: new Vector2( width, height )
  45823. };
  45824. morphTextures.set( geometry, entry );
  45825. function disposeTexture() {
  45826. texture.dispose();
  45827. morphTextures.delete( geometry );
  45828. geometry.removeEventListener( 'dispose', disposeTexture );
  45829. }
  45830. geometry.addEventListener( 'dispose', disposeTexture );
  45831. }
  45832. //
  45833. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45834. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45835. } else {
  45836. let morphInfluencesSum = 0;
  45837. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45838. morphInfluencesSum += objectInfluences[ i ];
  45839. }
  45840. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45841. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45842. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45843. }
  45844. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45845. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45846. }
  45847. return {
  45848. update: update
  45849. };
  45850. }
  45851. function WebGLObjects( gl, geometries, attributes, bindingStates, info ) {
  45852. let updateMap = new WeakMap();
  45853. function update( object ) {
  45854. const frame = info.render.frame;
  45855. const geometry = object.geometry;
  45856. const buffergeometry = geometries.get( object, geometry );
  45857. // Update once per frame
  45858. if ( updateMap.get( buffergeometry ) !== frame ) {
  45859. geometries.update( buffergeometry );
  45860. updateMap.set( buffergeometry, frame );
  45861. }
  45862. if ( object.isInstancedMesh ) {
  45863. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45864. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45865. }
  45866. if ( updateMap.get( object ) !== frame ) {
  45867. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45868. if ( object.instanceColor !== null ) {
  45869. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45870. }
  45871. updateMap.set( object, frame );
  45872. }
  45873. }
  45874. if ( object.isSkinnedMesh ) {
  45875. const skeleton = object.skeleton;
  45876. if ( updateMap.get( skeleton ) !== frame ) {
  45877. skeleton.update();
  45878. updateMap.set( skeleton, frame );
  45879. }
  45880. }
  45881. return buffergeometry;
  45882. }
  45883. function dispose() {
  45884. updateMap = new WeakMap();
  45885. }
  45886. function onInstancedMeshDispose( event ) {
  45887. const instancedMesh = event.target;
  45888. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45889. bindingStates.releaseStatesOfObject( instancedMesh );
  45890. attributes.remove( instancedMesh.instanceMatrix );
  45891. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45892. }
  45893. return {
  45894. update: update,
  45895. dispose: dispose
  45896. };
  45897. }
  45898. const toneMappingMap = {
  45899. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  45900. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  45901. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  45902. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  45903. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  45904. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  45905. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  45906. };
  45907. function WebGLOutput( type, width, height, depth, stencil ) {
  45908. // render targets for scene and post-processing
  45909. const targetA = new WebGLRenderTarget( width, height, {
  45910. type: type,
  45911. depthBuffer: depth,
  45912. stencilBuffer: stencil
  45913. } );
  45914. const targetB = new WebGLRenderTarget( width, height, {
  45915. type: HalfFloatType,
  45916. depthBuffer: false,
  45917. stencilBuffer: false
  45918. } );
  45919. // create fullscreen triangle geometry
  45920. const geometry = new BufferGeometry();
  45921. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  45922. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  45923. // create output material with tone mapping support
  45924. const material = new RawShaderMaterial( {
  45925. uniforms: {
  45926. tDiffuse: { value: null }
  45927. },
  45928. vertexShader: /* glsl */`
  45929. precision highp float;
  45930. uniform mat4 modelViewMatrix;
  45931. uniform mat4 projectionMatrix;
  45932. attribute vec3 position;
  45933. attribute vec2 uv;
  45934. varying vec2 vUv;
  45935. void main() {
  45936. vUv = uv;
  45937. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  45938. }`,
  45939. fragmentShader: /* glsl */`
  45940. precision highp float;
  45941. uniform sampler2D tDiffuse;
  45942. varying vec2 vUv;
  45943. #include <tonemapping_pars_fragment>
  45944. #include <colorspace_pars_fragment>
  45945. void main() {
  45946. gl_FragColor = texture2D( tDiffuse, vUv );
  45947. #ifdef LINEAR_TONE_MAPPING
  45948. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  45949. #elif defined( REINHARD_TONE_MAPPING )
  45950. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  45951. #elif defined( CINEON_TONE_MAPPING )
  45952. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  45953. #elif defined( ACES_FILMIC_TONE_MAPPING )
  45954. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  45955. #elif defined( AGX_TONE_MAPPING )
  45956. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  45957. #elif defined( NEUTRAL_TONE_MAPPING )
  45958. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  45959. #elif defined( CUSTOM_TONE_MAPPING )
  45960. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  45961. #endif
  45962. #ifdef SRGB_TRANSFER
  45963. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  45964. #endif
  45965. }`,
  45966. depthTest: false,
  45967. depthWrite: false
  45968. } );
  45969. const mesh = new Mesh( geometry, material );
  45970. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  45971. let _outputColorSpace = null;
  45972. let _outputToneMapping = null;
  45973. let _isCompositing = false;
  45974. let _savedToneMapping;
  45975. let _savedRenderTarget = null;
  45976. let _effects = [];
  45977. let _hasRenderPass = false;
  45978. this.setSize = function ( width, height ) {
  45979. targetA.setSize( width, height );
  45980. targetB.setSize( width, height );
  45981. for ( let i = 0; i < _effects.length; i ++ ) {
  45982. const effect = _effects[ i ];
  45983. if ( effect.setSize ) effect.setSize( width, height );
  45984. }
  45985. };
  45986. this.setEffects = function ( effects ) {
  45987. _effects = effects;
  45988. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  45989. const width = targetA.width;
  45990. const height = targetA.height;
  45991. for ( let i = 0; i < _effects.length; i ++ ) {
  45992. const effect = _effects[ i ];
  45993. if ( effect.setSize ) effect.setSize( width, height );
  45994. }
  45995. };
  45996. this.begin = function ( renderer, renderTarget ) {
  45997. // Don't begin during compositing phase (post-processing effects call render())
  45998. if ( _isCompositing ) return false;
  45999. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  46000. _savedRenderTarget = renderTarget;
  46001. // resize internal buffers to match render target (e.g. XR resolution)
  46002. if ( renderTarget !== null ) {
  46003. const width = renderTarget.width;
  46004. const height = renderTarget.height;
  46005. if ( targetA.width !== width || targetA.height !== height ) {
  46006. this.setSize( width, height );
  46007. }
  46008. }
  46009. // if first effect is a RenderPass, it will set its own render target
  46010. if ( _hasRenderPass === false ) {
  46011. renderer.setRenderTarget( targetA );
  46012. }
  46013. // disable tone mapping during render - it will be applied in end()
  46014. _savedToneMapping = renderer.toneMapping;
  46015. renderer.toneMapping = NoToneMapping;
  46016. return true;
  46017. };
  46018. this.hasRenderPass = function () {
  46019. return _hasRenderPass;
  46020. };
  46021. this.end = function ( renderer, deltaTime ) {
  46022. // restore tone mapping
  46023. renderer.toneMapping = _savedToneMapping;
  46024. _isCompositing = true;
  46025. // run post-processing effects
  46026. let readBuffer = targetA;
  46027. let writeBuffer = targetB;
  46028. for ( let i = 0; i < _effects.length; i ++ ) {
  46029. const effect = _effects[ i ];
  46030. if ( effect.enabled === false ) continue;
  46031. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  46032. if ( effect.needsSwap !== false ) {
  46033. const temp = readBuffer;
  46034. readBuffer = writeBuffer;
  46035. writeBuffer = temp;
  46036. }
  46037. }
  46038. // update output material defines if settings changed
  46039. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  46040. _outputColorSpace = renderer.outputColorSpace;
  46041. _outputToneMapping = renderer.toneMapping;
  46042. material.defines = {};
  46043. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  46044. const toneMapping = toneMappingMap[ _outputToneMapping ];
  46045. if ( toneMapping ) material.defines[ toneMapping ] = '';
  46046. material.needsUpdate = true;
  46047. }
  46048. // final output to canvas (or XR render target)
  46049. material.uniforms.tDiffuse.value = readBuffer.texture;
  46050. renderer.setRenderTarget( _savedRenderTarget );
  46051. renderer.render( mesh, camera );
  46052. _savedRenderTarget = null;
  46053. _isCompositing = false;
  46054. };
  46055. this.isCompositing = function () {
  46056. return _isCompositing;
  46057. };
  46058. this.dispose = function () {
  46059. targetA.dispose();
  46060. targetB.dispose();
  46061. geometry.dispose();
  46062. material.dispose();
  46063. };
  46064. }
  46065. /**
  46066. * Uniforms of a program.
  46067. * Those form a tree structure with a special top-level container for the root,
  46068. * which you get by calling 'new WebGLUniforms( gl, program )'.
  46069. *
  46070. *
  46071. * Properties of inner nodes including the top-level container:
  46072. *
  46073. * .seq - array of nested uniforms
  46074. * .map - nested uniforms by name
  46075. *
  46076. *
  46077. * Methods of all nodes except the top-level container:
  46078. *
  46079. * .setValue( gl, value, [textures] )
  46080. *
  46081. * uploads a uniform value(s)
  46082. * the 'textures' parameter is needed for sampler uniforms
  46083. *
  46084. *
  46085. * Static methods of the top-level container (textures factorizations):
  46086. *
  46087. * .upload( gl, seq, values, textures )
  46088. *
  46089. * sets uniforms in 'seq' to 'values[id].value'
  46090. *
  46091. * .seqWithValue( seq, values ) : filteredSeq
  46092. *
  46093. * filters 'seq' entries with corresponding entry in values
  46094. *
  46095. *
  46096. * Methods of the top-level container (textures factorizations):
  46097. *
  46098. * .setValue( gl, name, value, textures )
  46099. *
  46100. * sets uniform with name 'name' to 'value'
  46101. *
  46102. * .setOptional( gl, obj, prop )
  46103. *
  46104. * like .set for an optional property of the object
  46105. *
  46106. */
  46107. const emptyTexture = /*@__PURE__*/ new Texture();
  46108. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  46109. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  46110. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  46111. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  46112. // --- Utilities ---
  46113. // Array Caches (provide typed arrays for temporary by size)
  46114. const arrayCacheF32 = [];
  46115. const arrayCacheI32 = [];
  46116. // Float32Array caches used for uploading Matrix uniforms
  46117. const mat4array = new Float32Array( 16 );
  46118. const mat3array = new Float32Array( 9 );
  46119. const mat2array = new Float32Array( 4 );
  46120. // Flattening for arrays of vectors and matrices
  46121. function flatten( array, nBlocks, blockSize ) {
  46122. const firstElem = array[ 0 ];
  46123. if ( firstElem <= 0 || firstElem > 0 ) return array;
  46124. // unoptimized: ! isNaN( firstElem )
  46125. // see http://jacksondunstan.com/articles/983
  46126. const n = nBlocks * blockSize;
  46127. let r = arrayCacheF32[ n ];
  46128. if ( r === undefined ) {
  46129. r = new Float32Array( n );
  46130. arrayCacheF32[ n ] = r;
  46131. }
  46132. if ( nBlocks !== 0 ) {
  46133. firstElem.toArray( r, 0 );
  46134. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  46135. offset += blockSize;
  46136. array[ i ].toArray( r, offset );
  46137. }
  46138. }
  46139. return r;
  46140. }
  46141. function arraysEqual( a, b ) {
  46142. if ( a.length !== b.length ) return false;
  46143. for ( let i = 0, l = a.length; i < l; i ++ ) {
  46144. if ( a[ i ] !== b[ i ] ) return false;
  46145. }
  46146. return true;
  46147. }
  46148. function copyArray( a, b ) {
  46149. for ( let i = 0, l = b.length; i < l; i ++ ) {
  46150. a[ i ] = b[ i ];
  46151. }
  46152. }
  46153. // Texture unit allocation
  46154. function allocTexUnits( textures, n ) {
  46155. let r = arrayCacheI32[ n ];
  46156. if ( r === undefined ) {
  46157. r = new Int32Array( n );
  46158. arrayCacheI32[ n ] = r;
  46159. }
  46160. for ( let i = 0; i !== n; ++ i ) {
  46161. r[ i ] = textures.allocateTextureUnit();
  46162. }
  46163. return r;
  46164. }
  46165. // --- Setters ---
  46166. // Note: Defining these methods externally, because they come in a bunch
  46167. // and this way their names minify.
  46168. // Single scalar
  46169. function setValueV1f( gl, v ) {
  46170. const cache = this.cache;
  46171. if ( cache[ 0 ] === v ) return;
  46172. gl.uniform1f( this.addr, v );
  46173. cache[ 0 ] = v;
  46174. }
  46175. // Single float vector (from flat array or THREE.VectorN)
  46176. function setValueV2f( gl, v ) {
  46177. const cache = this.cache;
  46178. if ( v.x !== undefined ) {
  46179. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46180. gl.uniform2f( this.addr, v.x, v.y );
  46181. cache[ 0 ] = v.x;
  46182. cache[ 1 ] = v.y;
  46183. }
  46184. } else {
  46185. if ( arraysEqual( cache, v ) ) return;
  46186. gl.uniform2fv( this.addr, v );
  46187. copyArray( cache, v );
  46188. }
  46189. }
  46190. function setValueV3f( gl, v ) {
  46191. const cache = this.cache;
  46192. if ( v.x !== undefined ) {
  46193. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46194. gl.uniform3f( this.addr, v.x, v.y, v.z );
  46195. cache[ 0 ] = v.x;
  46196. cache[ 1 ] = v.y;
  46197. cache[ 2 ] = v.z;
  46198. }
  46199. } else if ( v.r !== undefined ) {
  46200. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  46201. gl.uniform3f( this.addr, v.r, v.g, v.b );
  46202. cache[ 0 ] = v.r;
  46203. cache[ 1 ] = v.g;
  46204. cache[ 2 ] = v.b;
  46205. }
  46206. } else {
  46207. if ( arraysEqual( cache, v ) ) return;
  46208. gl.uniform3fv( this.addr, v );
  46209. copyArray( cache, v );
  46210. }
  46211. }
  46212. function setValueV4f( gl, v ) {
  46213. const cache = this.cache;
  46214. if ( v.x !== undefined ) {
  46215. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46216. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  46217. cache[ 0 ] = v.x;
  46218. cache[ 1 ] = v.y;
  46219. cache[ 2 ] = v.z;
  46220. cache[ 3 ] = v.w;
  46221. }
  46222. } else {
  46223. if ( arraysEqual( cache, v ) ) return;
  46224. gl.uniform4fv( this.addr, v );
  46225. copyArray( cache, v );
  46226. }
  46227. }
  46228. // Single matrix (from flat array or THREE.MatrixN)
  46229. function setValueM2( gl, v ) {
  46230. const cache = this.cache;
  46231. const elements = v.elements;
  46232. if ( elements === undefined ) {
  46233. if ( arraysEqual( cache, v ) ) return;
  46234. gl.uniformMatrix2fv( this.addr, false, v );
  46235. copyArray( cache, v );
  46236. } else {
  46237. if ( arraysEqual( cache, elements ) ) return;
  46238. mat2array.set( elements );
  46239. gl.uniformMatrix2fv( this.addr, false, mat2array );
  46240. copyArray( cache, elements );
  46241. }
  46242. }
  46243. function setValueM3( gl, v ) {
  46244. const cache = this.cache;
  46245. const elements = v.elements;
  46246. if ( elements === undefined ) {
  46247. if ( arraysEqual( cache, v ) ) return;
  46248. gl.uniformMatrix3fv( this.addr, false, v );
  46249. copyArray( cache, v );
  46250. } else {
  46251. if ( arraysEqual( cache, elements ) ) return;
  46252. mat3array.set( elements );
  46253. gl.uniformMatrix3fv( this.addr, false, mat3array );
  46254. copyArray( cache, elements );
  46255. }
  46256. }
  46257. function setValueM4( gl, v ) {
  46258. const cache = this.cache;
  46259. const elements = v.elements;
  46260. if ( elements === undefined ) {
  46261. if ( arraysEqual( cache, v ) ) return;
  46262. gl.uniformMatrix4fv( this.addr, false, v );
  46263. copyArray( cache, v );
  46264. } else {
  46265. if ( arraysEqual( cache, elements ) ) return;
  46266. mat4array.set( elements );
  46267. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46268. copyArray( cache, elements );
  46269. }
  46270. }
  46271. // Single integer / boolean
  46272. function setValueV1i( gl, v ) {
  46273. const cache = this.cache;
  46274. if ( cache[ 0 ] === v ) return;
  46275. gl.uniform1i( this.addr, v );
  46276. cache[ 0 ] = v;
  46277. }
  46278. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46279. function setValueV2i( gl, v ) {
  46280. const cache = this.cache;
  46281. if ( v.x !== undefined ) {
  46282. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46283. gl.uniform2i( this.addr, v.x, v.y );
  46284. cache[ 0 ] = v.x;
  46285. cache[ 1 ] = v.y;
  46286. }
  46287. } else {
  46288. if ( arraysEqual( cache, v ) ) return;
  46289. gl.uniform2iv( this.addr, v );
  46290. copyArray( cache, v );
  46291. }
  46292. }
  46293. function setValueV3i( gl, v ) {
  46294. const cache = this.cache;
  46295. if ( v.x !== undefined ) {
  46296. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46297. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46298. cache[ 0 ] = v.x;
  46299. cache[ 1 ] = v.y;
  46300. cache[ 2 ] = v.z;
  46301. }
  46302. } else {
  46303. if ( arraysEqual( cache, v ) ) return;
  46304. gl.uniform3iv( this.addr, v );
  46305. copyArray( cache, v );
  46306. }
  46307. }
  46308. function setValueV4i( gl, v ) {
  46309. const cache = this.cache;
  46310. if ( v.x !== undefined ) {
  46311. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46312. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46313. cache[ 0 ] = v.x;
  46314. cache[ 1 ] = v.y;
  46315. cache[ 2 ] = v.z;
  46316. cache[ 3 ] = v.w;
  46317. }
  46318. } else {
  46319. if ( arraysEqual( cache, v ) ) return;
  46320. gl.uniform4iv( this.addr, v );
  46321. copyArray( cache, v );
  46322. }
  46323. }
  46324. // Single unsigned integer
  46325. function setValueV1ui( gl, v ) {
  46326. const cache = this.cache;
  46327. if ( cache[ 0 ] === v ) return;
  46328. gl.uniform1ui( this.addr, v );
  46329. cache[ 0 ] = v;
  46330. }
  46331. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46332. function setValueV2ui( gl, v ) {
  46333. const cache = this.cache;
  46334. if ( v.x !== undefined ) {
  46335. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46336. gl.uniform2ui( this.addr, v.x, v.y );
  46337. cache[ 0 ] = v.x;
  46338. cache[ 1 ] = v.y;
  46339. }
  46340. } else {
  46341. if ( arraysEqual( cache, v ) ) return;
  46342. gl.uniform2uiv( this.addr, v );
  46343. copyArray( cache, v );
  46344. }
  46345. }
  46346. function setValueV3ui( gl, v ) {
  46347. const cache = this.cache;
  46348. if ( v.x !== undefined ) {
  46349. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46350. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46351. cache[ 0 ] = v.x;
  46352. cache[ 1 ] = v.y;
  46353. cache[ 2 ] = v.z;
  46354. }
  46355. } else {
  46356. if ( arraysEqual( cache, v ) ) return;
  46357. gl.uniform3uiv( this.addr, v );
  46358. copyArray( cache, v );
  46359. }
  46360. }
  46361. function setValueV4ui( gl, v ) {
  46362. const cache = this.cache;
  46363. if ( v.x !== undefined ) {
  46364. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46365. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46366. cache[ 0 ] = v.x;
  46367. cache[ 1 ] = v.y;
  46368. cache[ 2 ] = v.z;
  46369. cache[ 3 ] = v.w;
  46370. }
  46371. } else {
  46372. if ( arraysEqual( cache, v ) ) return;
  46373. gl.uniform4uiv( this.addr, v );
  46374. copyArray( cache, v );
  46375. }
  46376. }
  46377. // Single texture (2D / Cube)
  46378. function setValueT1( gl, v, textures ) {
  46379. const cache = this.cache;
  46380. const unit = textures.allocateTextureUnit();
  46381. if ( cache[ 0 ] !== unit ) {
  46382. gl.uniform1i( this.addr, unit );
  46383. cache[ 0 ] = unit;
  46384. }
  46385. let emptyTexture2D;
  46386. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46387. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46388. emptyTexture2D = emptyShadowTexture;
  46389. } else {
  46390. emptyTexture2D = emptyTexture;
  46391. }
  46392. textures.setTexture2D( v || emptyTexture2D, unit );
  46393. }
  46394. function setValueT3D1( gl, v, textures ) {
  46395. const cache = this.cache;
  46396. const unit = textures.allocateTextureUnit();
  46397. if ( cache[ 0 ] !== unit ) {
  46398. gl.uniform1i( this.addr, unit );
  46399. cache[ 0 ] = unit;
  46400. }
  46401. textures.setTexture3D( v || empty3dTexture, unit );
  46402. }
  46403. function setValueT6( gl, v, textures ) {
  46404. const cache = this.cache;
  46405. const unit = textures.allocateTextureUnit();
  46406. if ( cache[ 0 ] !== unit ) {
  46407. gl.uniform1i( this.addr, unit );
  46408. cache[ 0 ] = unit;
  46409. }
  46410. textures.setTextureCube( v || emptyCubeTexture, unit );
  46411. }
  46412. function setValueT2DArray1( gl, v, textures ) {
  46413. const cache = this.cache;
  46414. const unit = textures.allocateTextureUnit();
  46415. if ( cache[ 0 ] !== unit ) {
  46416. gl.uniform1i( this.addr, unit );
  46417. cache[ 0 ] = unit;
  46418. }
  46419. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46420. }
  46421. // Helper to pick the right setter for the singular case
  46422. function getSingularSetter( type ) {
  46423. switch ( type ) {
  46424. case 0x1406: return setValueV1f; // FLOAT
  46425. case 0x8b50: return setValueV2f; // _VEC2
  46426. case 0x8b51: return setValueV3f; // _VEC3
  46427. case 0x8b52: return setValueV4f; // _VEC4
  46428. case 0x8b5a: return setValueM2; // _MAT2
  46429. case 0x8b5b: return setValueM3; // _MAT3
  46430. case 0x8b5c: return setValueM4; // _MAT4
  46431. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46432. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46433. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46434. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46435. case 0x1405: return setValueV1ui; // UINT
  46436. case 0x8dc6: return setValueV2ui; // _VEC2
  46437. case 0x8dc7: return setValueV3ui; // _VEC3
  46438. case 0x8dc8: return setValueV4ui; // _VEC4
  46439. case 0x8b5e: // SAMPLER_2D
  46440. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46441. case 0x8dca: // INT_SAMPLER_2D
  46442. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46443. case 0x8b62: // SAMPLER_2D_SHADOW
  46444. return setValueT1;
  46445. case 0x8b5f: // SAMPLER_3D
  46446. case 0x8dcb: // INT_SAMPLER_3D
  46447. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46448. return setValueT3D1;
  46449. case 0x8b60: // SAMPLER_CUBE
  46450. case 0x8dcc: // INT_SAMPLER_CUBE
  46451. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46452. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46453. return setValueT6;
  46454. case 0x8dc1: // SAMPLER_2D_ARRAY
  46455. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46456. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46457. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46458. return setValueT2DArray1;
  46459. }
  46460. }
  46461. // Array of scalars
  46462. function setValueV1fArray( gl, v ) {
  46463. gl.uniform1fv( this.addr, v );
  46464. }
  46465. // Array of vectors (from flat array or array of THREE.VectorN)
  46466. function setValueV2fArray( gl, v ) {
  46467. const data = flatten( v, this.size, 2 );
  46468. gl.uniform2fv( this.addr, data );
  46469. }
  46470. function setValueV3fArray( gl, v ) {
  46471. const data = flatten( v, this.size, 3 );
  46472. gl.uniform3fv( this.addr, data );
  46473. }
  46474. function setValueV4fArray( gl, v ) {
  46475. const data = flatten( v, this.size, 4 );
  46476. gl.uniform4fv( this.addr, data );
  46477. }
  46478. // Array of matrices (from flat array or array of THREE.MatrixN)
  46479. function setValueM2Array( gl, v ) {
  46480. const data = flatten( v, this.size, 4 );
  46481. gl.uniformMatrix2fv( this.addr, false, data );
  46482. }
  46483. function setValueM3Array( gl, v ) {
  46484. const data = flatten( v, this.size, 9 );
  46485. gl.uniformMatrix3fv( this.addr, false, data );
  46486. }
  46487. function setValueM4Array( gl, v ) {
  46488. const data = flatten( v, this.size, 16 );
  46489. gl.uniformMatrix4fv( this.addr, false, data );
  46490. }
  46491. // Array of integer / boolean
  46492. function setValueV1iArray( gl, v ) {
  46493. gl.uniform1iv( this.addr, v );
  46494. }
  46495. // Array of integer / boolean vectors (from flat array)
  46496. function setValueV2iArray( gl, v ) {
  46497. gl.uniform2iv( this.addr, v );
  46498. }
  46499. function setValueV3iArray( gl, v ) {
  46500. gl.uniform3iv( this.addr, v );
  46501. }
  46502. function setValueV4iArray( gl, v ) {
  46503. gl.uniform4iv( this.addr, v );
  46504. }
  46505. // Array of unsigned integer
  46506. function setValueV1uiArray( gl, v ) {
  46507. gl.uniform1uiv( this.addr, v );
  46508. }
  46509. // Array of unsigned integer vectors (from flat array)
  46510. function setValueV2uiArray( gl, v ) {
  46511. gl.uniform2uiv( this.addr, v );
  46512. }
  46513. function setValueV3uiArray( gl, v ) {
  46514. gl.uniform3uiv( this.addr, v );
  46515. }
  46516. function setValueV4uiArray( gl, v ) {
  46517. gl.uniform4uiv( this.addr, v );
  46518. }
  46519. // Array of textures (2D / 3D / Cube / 2DArray)
  46520. function setValueT1Array( gl, v, textures ) {
  46521. const cache = this.cache;
  46522. const n = v.length;
  46523. const units = allocTexUnits( textures, n );
  46524. if ( ! arraysEqual( cache, units ) ) {
  46525. gl.uniform1iv( this.addr, units );
  46526. copyArray( cache, units );
  46527. }
  46528. let emptyTexture2D;
  46529. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46530. emptyTexture2D = emptyShadowTexture;
  46531. } else {
  46532. emptyTexture2D = emptyTexture;
  46533. }
  46534. for ( let i = 0; i !== n; ++ i ) {
  46535. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46536. }
  46537. }
  46538. function setValueT3DArray( gl, v, textures ) {
  46539. const cache = this.cache;
  46540. const n = v.length;
  46541. const units = allocTexUnits( textures, n );
  46542. if ( ! arraysEqual( cache, units ) ) {
  46543. gl.uniform1iv( this.addr, units );
  46544. copyArray( cache, units );
  46545. }
  46546. for ( let i = 0; i !== n; ++ i ) {
  46547. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46548. }
  46549. }
  46550. function setValueT6Array( gl, v, textures ) {
  46551. const cache = this.cache;
  46552. const n = v.length;
  46553. const units = allocTexUnits( textures, n );
  46554. if ( ! arraysEqual( cache, units ) ) {
  46555. gl.uniform1iv( this.addr, units );
  46556. copyArray( cache, units );
  46557. }
  46558. for ( let i = 0; i !== n; ++ i ) {
  46559. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46560. }
  46561. }
  46562. function setValueT2DArrayArray( gl, v, textures ) {
  46563. const cache = this.cache;
  46564. const n = v.length;
  46565. const units = allocTexUnits( textures, n );
  46566. if ( ! arraysEqual( cache, units ) ) {
  46567. gl.uniform1iv( this.addr, units );
  46568. copyArray( cache, units );
  46569. }
  46570. for ( let i = 0; i !== n; ++ i ) {
  46571. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46572. }
  46573. }
  46574. // Helper to pick the right setter for a pure (bottom-level) array
  46575. function getPureArraySetter( type ) {
  46576. switch ( type ) {
  46577. case 0x1406: return setValueV1fArray; // FLOAT
  46578. case 0x8b50: return setValueV2fArray; // _VEC2
  46579. case 0x8b51: return setValueV3fArray; // _VEC3
  46580. case 0x8b52: return setValueV4fArray; // _VEC4
  46581. case 0x8b5a: return setValueM2Array; // _MAT2
  46582. case 0x8b5b: return setValueM3Array; // _MAT3
  46583. case 0x8b5c: return setValueM4Array; // _MAT4
  46584. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46585. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46586. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46587. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46588. case 0x1405: return setValueV1uiArray; // UINT
  46589. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46590. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46591. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46592. case 0x8b5e: // SAMPLER_2D
  46593. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46594. case 0x8dca: // INT_SAMPLER_2D
  46595. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46596. case 0x8b62: // SAMPLER_2D_SHADOW
  46597. return setValueT1Array;
  46598. case 0x8b5f: // SAMPLER_3D
  46599. case 0x8dcb: // INT_SAMPLER_3D
  46600. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46601. return setValueT3DArray;
  46602. case 0x8b60: // SAMPLER_CUBE
  46603. case 0x8dcc: // INT_SAMPLER_CUBE
  46604. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46605. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46606. return setValueT6Array;
  46607. case 0x8dc1: // SAMPLER_2D_ARRAY
  46608. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46609. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46610. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46611. return setValueT2DArrayArray;
  46612. }
  46613. }
  46614. // --- Uniform Classes ---
  46615. class SingleUniform {
  46616. constructor( id, activeInfo, addr ) {
  46617. this.id = id;
  46618. this.addr = addr;
  46619. this.cache = [];
  46620. this.type = activeInfo.type;
  46621. this.setValue = getSingularSetter( activeInfo.type );
  46622. // this.path = activeInfo.name; // DEBUG
  46623. }
  46624. }
  46625. class PureArrayUniform {
  46626. constructor( id, activeInfo, addr ) {
  46627. this.id = id;
  46628. this.addr = addr;
  46629. this.cache = [];
  46630. this.type = activeInfo.type;
  46631. this.size = activeInfo.size;
  46632. this.setValue = getPureArraySetter( activeInfo.type );
  46633. // this.path = activeInfo.name; // DEBUG
  46634. }
  46635. }
  46636. class StructuredUniform {
  46637. constructor( id ) {
  46638. this.id = id;
  46639. this.seq = [];
  46640. this.map = {};
  46641. }
  46642. setValue( gl, value, textures ) {
  46643. const seq = this.seq;
  46644. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46645. const u = seq[ i ];
  46646. u.setValue( gl, value[ u.id ], textures );
  46647. }
  46648. }
  46649. }
  46650. // --- Top-level ---
  46651. // Parser - builds up the property tree from the path strings
  46652. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46653. // extracts
  46654. // - the identifier (member name or array index)
  46655. // - followed by an optional right bracket (found when array index)
  46656. // - followed by an optional left bracket or dot (type of subscript)
  46657. //
  46658. // Note: These portions can be read in a non-overlapping fashion and
  46659. // allow straightforward parsing of the hierarchy that WebGL encodes
  46660. // in the uniform names.
  46661. function addUniform( container, uniformObject ) {
  46662. container.seq.push( uniformObject );
  46663. container.map[ uniformObject.id ] = uniformObject;
  46664. }
  46665. function parseUniform( activeInfo, addr, container ) {
  46666. const path = activeInfo.name,
  46667. pathLength = path.length;
  46668. // reset RegExp object, because of the early exit of a previous run
  46669. RePathPart.lastIndex = 0;
  46670. while ( true ) {
  46671. const match = RePathPart.exec( path ),
  46672. matchEnd = RePathPart.lastIndex;
  46673. let id = match[ 1 ];
  46674. const idIsIndex = match[ 2 ] === ']',
  46675. subscript = match[ 3 ];
  46676. if ( idIsIndex ) id = id | 0; // convert to integer
  46677. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46678. // bare name or "pure" bottom-level array "[0]" suffix
  46679. addUniform( container, subscript === undefined ?
  46680. new SingleUniform( id, activeInfo, addr ) :
  46681. new PureArrayUniform( id, activeInfo, addr ) );
  46682. break;
  46683. } else {
  46684. // step into inner node / create it in case it doesn't exist
  46685. const map = container.map;
  46686. let next = map[ id ];
  46687. if ( next === undefined ) {
  46688. next = new StructuredUniform( id );
  46689. addUniform( container, next );
  46690. }
  46691. container = next;
  46692. }
  46693. }
  46694. }
  46695. // Root Container
  46696. class WebGLUniforms {
  46697. constructor( gl, program ) {
  46698. this.seq = [];
  46699. this.map = {};
  46700. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46701. for ( let i = 0; i < n; ++ i ) {
  46702. const info = gl.getActiveUniform( program, i ),
  46703. addr = gl.getUniformLocation( program, info.name );
  46704. parseUniform( info, addr, this );
  46705. }
  46706. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46707. const shadowSamplers = [];
  46708. const otherUniforms = [];
  46709. for ( const u of this.seq ) {
  46710. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46711. shadowSamplers.push( u );
  46712. } else {
  46713. otherUniforms.push( u );
  46714. }
  46715. }
  46716. if ( shadowSamplers.length > 0 ) {
  46717. this.seq = shadowSamplers.concat( otherUniforms );
  46718. }
  46719. }
  46720. setValue( gl, name, value, textures ) {
  46721. const u = this.map[ name ];
  46722. if ( u !== undefined ) u.setValue( gl, value, textures );
  46723. }
  46724. setOptional( gl, object, name ) {
  46725. const v = object[ name ];
  46726. if ( v !== undefined ) this.setValue( gl, name, v );
  46727. }
  46728. static upload( gl, seq, values, textures ) {
  46729. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46730. const u = seq[ i ],
  46731. v = values[ u.id ];
  46732. if ( v.needsUpdate !== false ) {
  46733. // note: always updating when .needsUpdate is undefined
  46734. u.setValue( gl, v.value, textures );
  46735. }
  46736. }
  46737. }
  46738. static seqWithValue( seq, values ) {
  46739. const r = [];
  46740. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46741. const u = seq[ i ];
  46742. if ( u.id in values ) r.push( u );
  46743. }
  46744. return r;
  46745. }
  46746. }
  46747. function WebGLShader( gl, type, string ) {
  46748. const shader = gl.createShader( type );
  46749. gl.shaderSource( shader, string );
  46750. gl.compileShader( shader );
  46751. return shader;
  46752. }
  46753. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46754. const COMPLETION_STATUS_KHR = 0x91B1;
  46755. let programIdCount = 0;
  46756. function handleSource( string, errorLine ) {
  46757. const lines = string.split( '\n' );
  46758. const lines2 = [];
  46759. const from = Math.max( errorLine - 6, 0 );
  46760. const to = Math.min( errorLine + 6, lines.length );
  46761. for ( let i = from; i < to; i ++ ) {
  46762. const line = i + 1;
  46763. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46764. }
  46765. return lines2.join( '\n' );
  46766. }
  46767. const _m0 = /*@__PURE__*/ new Matrix3();
  46768. function getEncodingComponents( colorSpace ) {
  46769. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46770. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46771. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46772. case LinearTransfer:
  46773. return [ encodingMatrix, 'LinearTransferOETF' ];
  46774. case SRGBTransfer:
  46775. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46776. default:
  46777. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46778. return [ encodingMatrix, 'LinearTransferOETF' ];
  46779. }
  46780. }
  46781. function getShaderErrors( gl, shader, type ) {
  46782. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46783. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46784. const errors = shaderInfoLog.trim();
  46785. if ( status && errors === '' ) return '';
  46786. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46787. if ( errorMatches ) {
  46788. // --enable-privileged-webgl-extension
  46789. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46790. const errorLine = parseInt( errorMatches[ 1 ] );
  46791. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46792. } else {
  46793. return errors;
  46794. }
  46795. }
  46796. function getTexelEncodingFunction( functionName, colorSpace ) {
  46797. const components = getEncodingComponents( colorSpace );
  46798. return [
  46799. `vec4 ${functionName}( vec4 value ) {`,
  46800. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46801. '}',
  46802. ].join( '\n' );
  46803. }
  46804. const toneMappingFunctions = {
  46805. [ LinearToneMapping ]: 'Linear',
  46806. [ ReinhardToneMapping ]: 'Reinhard',
  46807. [ CineonToneMapping ]: 'Cineon',
  46808. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  46809. [ AgXToneMapping ]: 'AgX',
  46810. [ NeutralToneMapping ]: 'Neutral',
  46811. [ CustomToneMapping ]: 'Custom'
  46812. };
  46813. function getToneMappingFunction( functionName, toneMapping ) {
  46814. const toneMappingName = toneMappingFunctions[ toneMapping ];
  46815. if ( toneMappingName === undefined ) {
  46816. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46817. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  46818. }
  46819. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46820. }
  46821. const _v0 = /*@__PURE__*/ new Vector3();
  46822. function getLuminanceFunction() {
  46823. ColorManagement.getLuminanceCoefficients( _v0 );
  46824. const r = _v0.x.toFixed( 4 );
  46825. const g = _v0.y.toFixed( 4 );
  46826. const b = _v0.z.toFixed( 4 );
  46827. return [
  46828. 'float luminance( const in vec3 rgb ) {',
  46829. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46830. ' return dot( weights, rgb );',
  46831. '}'
  46832. ].join( '\n' );
  46833. }
  46834. function generateVertexExtensions( parameters ) {
  46835. const chunks = [
  46836. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46837. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46838. ];
  46839. return chunks.filter( filterEmptyLine ).join( '\n' );
  46840. }
  46841. function generateDefines( defines ) {
  46842. const chunks = [];
  46843. for ( const name in defines ) {
  46844. const value = defines[ name ];
  46845. if ( value === false ) continue;
  46846. chunks.push( '#define ' + name + ' ' + value );
  46847. }
  46848. return chunks.join( '\n' );
  46849. }
  46850. function fetchAttributeLocations( gl, program ) {
  46851. const attributes = {};
  46852. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46853. for ( let i = 0; i < n; i ++ ) {
  46854. const info = gl.getActiveAttrib( program, i );
  46855. const name = info.name;
  46856. let locationSize = 1;
  46857. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46858. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46859. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46860. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46861. attributes[ name ] = {
  46862. type: info.type,
  46863. location: gl.getAttribLocation( program, name ),
  46864. locationSize: locationSize
  46865. };
  46866. }
  46867. return attributes;
  46868. }
  46869. function filterEmptyLine( string ) {
  46870. return string !== '';
  46871. }
  46872. function replaceLightNums( string, parameters ) {
  46873. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46874. return string
  46875. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46876. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46877. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46878. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46879. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46880. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46881. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46882. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46883. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46884. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46885. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46886. }
  46887. function replaceClippingPlaneNums( string, parameters ) {
  46888. return string
  46889. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46890. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46891. }
  46892. // Resolve Includes
  46893. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46894. function resolveIncludes( string ) {
  46895. return string.replace( includePattern, includeReplacer );
  46896. }
  46897. const shaderChunkMap = new Map();
  46898. function includeReplacer( match, include ) {
  46899. let string = ShaderChunk[ include ];
  46900. if ( string === undefined ) {
  46901. const newInclude = shaderChunkMap.get( include );
  46902. if ( newInclude !== undefined ) {
  46903. string = ShaderChunk[ newInclude ];
  46904. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46905. } else {
  46906. throw new Error( 'Can not resolve #include <' + include + '>' );
  46907. }
  46908. }
  46909. return resolveIncludes( string );
  46910. }
  46911. // Unroll Loops
  46912. 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;
  46913. function unrollLoops( string ) {
  46914. return string.replace( unrollLoopPattern, loopReplacer );
  46915. }
  46916. function loopReplacer( match, start, end, snippet ) {
  46917. let string = '';
  46918. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46919. string += snippet
  46920. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46921. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46922. }
  46923. return string;
  46924. }
  46925. //
  46926. function generatePrecision( parameters ) {
  46927. let precisionstring = `precision ${parameters.precision} float;
  46928. precision ${parameters.precision} int;
  46929. precision ${parameters.precision} sampler2D;
  46930. precision ${parameters.precision} samplerCube;
  46931. precision ${parameters.precision} sampler3D;
  46932. precision ${parameters.precision} sampler2DArray;
  46933. precision ${parameters.precision} sampler2DShadow;
  46934. precision ${parameters.precision} samplerCubeShadow;
  46935. precision ${parameters.precision} sampler2DArrayShadow;
  46936. precision ${parameters.precision} isampler2D;
  46937. precision ${parameters.precision} isampler3D;
  46938. precision ${parameters.precision} isamplerCube;
  46939. precision ${parameters.precision} isampler2DArray;
  46940. precision ${parameters.precision} usampler2D;
  46941. precision ${parameters.precision} usampler3D;
  46942. precision ${parameters.precision} usamplerCube;
  46943. precision ${parameters.precision} usampler2DArray;
  46944. `;
  46945. if ( parameters.precision === 'highp' ) {
  46946. precisionstring += '\n#define HIGH_PRECISION';
  46947. } else if ( parameters.precision === 'mediump' ) {
  46948. precisionstring += '\n#define MEDIUM_PRECISION';
  46949. } else if ( parameters.precision === 'lowp' ) {
  46950. precisionstring += '\n#define LOW_PRECISION';
  46951. }
  46952. return precisionstring;
  46953. }
  46954. const shadowMapTypeDefines = {
  46955. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  46956. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  46957. };
  46958. function generateShadowMapTypeDefine( parameters ) {
  46959. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  46960. }
  46961. const envMapTypeDefines = {
  46962. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  46963. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  46964. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  46965. };
  46966. function generateEnvMapTypeDefine( parameters ) {
  46967. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  46968. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  46969. }
  46970. const envMapModeDefines = {
  46971. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  46972. };
  46973. function generateEnvMapModeDefine( parameters ) {
  46974. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  46975. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  46976. }
  46977. const envMapBlendingDefines = {
  46978. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  46979. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  46980. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  46981. };
  46982. function generateEnvMapBlendingDefine( parameters ) {
  46983. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  46984. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  46985. }
  46986. function generateCubeUVSize( parameters ) {
  46987. const imageHeight = parameters.envMapCubeUVHeight;
  46988. if ( imageHeight === null ) return null;
  46989. const maxMip = Math.log2( imageHeight ) - 2;
  46990. const texelHeight = 1.0 / imageHeight;
  46991. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46992. return { texelWidth, texelHeight, maxMip };
  46993. }
  46994. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46995. // TODO Send this event to Three.js DevTools
  46996. // log( 'WebGLProgram', cacheKey );
  46997. const gl = renderer.getContext();
  46998. const defines = parameters.defines;
  46999. let vertexShader = parameters.vertexShader;
  47000. let fragmentShader = parameters.fragmentShader;
  47001. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  47002. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  47003. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  47004. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  47005. const envMapCubeUVSize = generateCubeUVSize( parameters );
  47006. const customVertexExtensions = generateVertexExtensions( parameters );
  47007. const customDefines = generateDefines( defines );
  47008. const program = gl.createProgram();
  47009. let prefixVertex, prefixFragment;
  47010. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  47011. if ( parameters.isRawShaderMaterial ) {
  47012. prefixVertex = [
  47013. '#define SHADER_TYPE ' + parameters.shaderType,
  47014. '#define SHADER_NAME ' + parameters.shaderName,
  47015. customDefines
  47016. ].filter( filterEmptyLine ).join( '\n' );
  47017. if ( prefixVertex.length > 0 ) {
  47018. prefixVertex += '\n';
  47019. }
  47020. prefixFragment = [
  47021. '#define SHADER_TYPE ' + parameters.shaderType,
  47022. '#define SHADER_NAME ' + parameters.shaderName,
  47023. customDefines
  47024. ].filter( filterEmptyLine ).join( '\n' );
  47025. if ( prefixFragment.length > 0 ) {
  47026. prefixFragment += '\n';
  47027. }
  47028. } else {
  47029. prefixVertex = [
  47030. generatePrecision( parameters ),
  47031. '#define SHADER_TYPE ' + parameters.shaderType,
  47032. '#define SHADER_NAME ' + parameters.shaderName,
  47033. customDefines,
  47034. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  47035. parameters.batching ? '#define USE_BATCHING' : '',
  47036. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  47037. parameters.instancing ? '#define USE_INSTANCING' : '',
  47038. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  47039. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  47040. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47041. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47042. parameters.map ? '#define USE_MAP' : '',
  47043. parameters.envMap ? '#define USE_ENVMAP' : '',
  47044. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47045. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47046. parameters.aoMap ? '#define USE_AOMAP' : '',
  47047. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47048. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47049. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47050. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47051. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  47052. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47053. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47054. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47055. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47056. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47057. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47058. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47059. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47060. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47061. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47062. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47063. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47064. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47065. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47066. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47067. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47068. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47069. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47070. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47071. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47072. //
  47073. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  47074. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  47075. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  47076. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  47077. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  47078. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  47079. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  47080. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  47081. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  47082. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  47083. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  47084. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  47085. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  47086. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  47087. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  47088. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  47089. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  47090. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  47091. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  47092. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  47093. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  47094. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  47095. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  47096. //
  47097. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47098. parameters.vertexColors ? '#define USE_COLOR' : '',
  47099. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47100. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47101. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47102. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47103. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47104. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47105. parameters.skinning ? '#define USE_SKINNING' : '',
  47106. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  47107. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  47108. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  47109. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  47110. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  47111. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47112. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47113. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47114. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47115. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  47116. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47117. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47118. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47119. 'uniform mat4 modelMatrix;',
  47120. 'uniform mat4 modelViewMatrix;',
  47121. 'uniform mat4 projectionMatrix;',
  47122. 'uniform mat4 viewMatrix;',
  47123. 'uniform mat3 normalMatrix;',
  47124. 'uniform vec3 cameraPosition;',
  47125. 'uniform bool isOrthographic;',
  47126. '#ifdef USE_INSTANCING',
  47127. ' attribute mat4 instanceMatrix;',
  47128. '#endif',
  47129. '#ifdef USE_INSTANCING_COLOR',
  47130. ' attribute vec3 instanceColor;',
  47131. '#endif',
  47132. '#ifdef USE_INSTANCING_MORPH',
  47133. ' uniform sampler2D morphTexture;',
  47134. '#endif',
  47135. 'attribute vec3 position;',
  47136. 'attribute vec3 normal;',
  47137. 'attribute vec2 uv;',
  47138. '#ifdef USE_UV1',
  47139. ' attribute vec2 uv1;',
  47140. '#endif',
  47141. '#ifdef USE_UV2',
  47142. ' attribute vec2 uv2;',
  47143. '#endif',
  47144. '#ifdef USE_UV3',
  47145. ' attribute vec2 uv3;',
  47146. '#endif',
  47147. '#ifdef USE_TANGENT',
  47148. ' attribute vec4 tangent;',
  47149. '#endif',
  47150. '#if defined( USE_COLOR_ALPHA )',
  47151. ' attribute vec4 color;',
  47152. '#elif defined( USE_COLOR )',
  47153. ' attribute vec3 color;',
  47154. '#endif',
  47155. '#ifdef USE_SKINNING',
  47156. ' attribute vec4 skinIndex;',
  47157. ' attribute vec4 skinWeight;',
  47158. '#endif',
  47159. '\n'
  47160. ].filter( filterEmptyLine ).join( '\n' );
  47161. prefixFragment = [
  47162. generatePrecision( parameters ),
  47163. '#define SHADER_TYPE ' + parameters.shaderType,
  47164. '#define SHADER_NAME ' + parameters.shaderName,
  47165. customDefines,
  47166. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  47167. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  47168. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  47169. parameters.map ? '#define USE_MAP' : '',
  47170. parameters.matcap ? '#define USE_MATCAP' : '',
  47171. parameters.envMap ? '#define USE_ENVMAP' : '',
  47172. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  47173. parameters.envMap ? '#define ' + envMapModeDefine : '',
  47174. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  47175. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  47176. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  47177. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  47178. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  47179. parameters.aoMap ? '#define USE_AOMAP' : '',
  47180. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  47181. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  47182. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  47183. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  47184. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  47185. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  47186. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  47187. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  47188. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  47189. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  47190. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  47191. parameters.dispersion ? '#define USE_DISPERSION' : '',
  47192. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  47193. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  47194. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  47195. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  47196. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  47197. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  47198. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  47199. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  47200. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  47201. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  47202. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  47203. parameters.sheen ? '#define USE_SHEEN' : '',
  47204. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  47205. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  47206. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  47207. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  47208. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  47209. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  47210. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  47211. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  47212. parameters.vertexUv1s ? '#define USE_UV1' : '',
  47213. parameters.vertexUv2s ? '#define USE_UV2' : '',
  47214. parameters.vertexUv3s ? '#define USE_UV3' : '',
  47215. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  47216. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  47217. parameters.flatShading ? '#define FLAT_SHADED' : '',
  47218. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  47219. parameters.flipSided ? '#define FLIP_SIDED' : '',
  47220. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  47221. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  47222. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  47223. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  47224. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  47225. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  47226. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  47227. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  47228. 'uniform mat4 viewMatrix;',
  47229. 'uniform vec3 cameraPosition;',
  47230. 'uniform bool isOrthographic;',
  47231. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  47232. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  47233. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  47234. parameters.dithering ? '#define DITHERING' : '',
  47235. parameters.opaque ? '#define OPAQUE' : '',
  47236. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  47237. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  47238. getLuminanceFunction(),
  47239. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  47240. '\n'
  47241. ].filter( filterEmptyLine ).join( '\n' );
  47242. }
  47243. vertexShader = resolveIncludes( vertexShader );
  47244. vertexShader = replaceLightNums( vertexShader, parameters );
  47245. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  47246. fragmentShader = resolveIncludes( fragmentShader );
  47247. fragmentShader = replaceLightNums( fragmentShader, parameters );
  47248. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  47249. vertexShader = unrollLoops( vertexShader );
  47250. fragmentShader = unrollLoops( fragmentShader );
  47251. if ( parameters.isRawShaderMaterial !== true ) {
  47252. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  47253. versionString = '#version 300 es\n';
  47254. prefixVertex = [
  47255. customVertexExtensions,
  47256. '#define attribute in',
  47257. '#define varying out',
  47258. '#define texture2D texture'
  47259. ].join( '\n' ) + '\n' + prefixVertex;
  47260. prefixFragment = [
  47261. '#define varying in',
  47262. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47263. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47264. '#define gl_FragDepthEXT gl_FragDepth',
  47265. '#define texture2D texture',
  47266. '#define textureCube texture',
  47267. '#define texture2DProj textureProj',
  47268. '#define texture2DLodEXT textureLod',
  47269. '#define texture2DProjLodEXT textureProjLod',
  47270. '#define textureCubeLodEXT textureLod',
  47271. '#define texture2DGradEXT textureGrad',
  47272. '#define texture2DProjGradEXT textureProjGrad',
  47273. '#define textureCubeGradEXT textureGrad'
  47274. ].join( '\n' ) + '\n' + prefixFragment;
  47275. }
  47276. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47277. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47278. // log( '*VERTEX*', vertexGlsl );
  47279. // log( '*FRAGMENT*', fragmentGlsl );
  47280. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47281. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47282. gl.attachShader( program, glVertexShader );
  47283. gl.attachShader( program, glFragmentShader );
  47284. // Force a particular attribute to index 0.
  47285. if ( parameters.index0AttributeName !== undefined ) {
  47286. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47287. } else if ( parameters.morphTargets === true ) {
  47288. // programs with morphTargets displace position out of attribute 0
  47289. gl.bindAttribLocation( program, 0, 'position' );
  47290. }
  47291. gl.linkProgram( program );
  47292. function onFirstUse( self ) {
  47293. // check for link errors
  47294. if ( renderer.debug.checkShaderErrors ) {
  47295. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47296. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47297. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47298. const programLog = programInfoLog.trim();
  47299. const vertexLog = vertexShaderInfoLog.trim();
  47300. const fragmentLog = fragmentShaderInfoLog.trim();
  47301. let runnable = true;
  47302. let haveDiagnostics = true;
  47303. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47304. runnable = false;
  47305. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47306. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47307. } else {
  47308. // default error reporting
  47309. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47310. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47311. error(
  47312. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47313. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47314. 'Material Name: ' + self.name + '\n' +
  47315. 'Material Type: ' + self.type + '\n\n' +
  47316. 'Program Info Log: ' + programLog + '\n' +
  47317. vertexErrors + '\n' +
  47318. fragmentErrors
  47319. );
  47320. }
  47321. } else if ( programLog !== '' ) {
  47322. warn( 'WebGLProgram: Program Info Log:', programLog );
  47323. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47324. haveDiagnostics = false;
  47325. }
  47326. if ( haveDiagnostics ) {
  47327. self.diagnostics = {
  47328. runnable: runnable,
  47329. programLog: programLog,
  47330. vertexShader: {
  47331. log: vertexLog,
  47332. prefix: prefixVertex
  47333. },
  47334. fragmentShader: {
  47335. log: fragmentLog,
  47336. prefix: prefixFragment
  47337. }
  47338. };
  47339. }
  47340. }
  47341. // Clean up
  47342. // Crashes in iOS9 and iOS10. #18402
  47343. // gl.detachShader( program, glVertexShader );
  47344. // gl.detachShader( program, glFragmentShader );
  47345. gl.deleteShader( glVertexShader );
  47346. gl.deleteShader( glFragmentShader );
  47347. cachedUniforms = new WebGLUniforms( gl, program );
  47348. cachedAttributes = fetchAttributeLocations( gl, program );
  47349. }
  47350. // set up caching for uniform locations
  47351. let cachedUniforms;
  47352. this.getUniforms = function () {
  47353. if ( cachedUniforms === undefined ) {
  47354. // Populates cachedUniforms and cachedAttributes
  47355. onFirstUse( this );
  47356. }
  47357. return cachedUniforms;
  47358. };
  47359. // set up caching for attribute locations
  47360. let cachedAttributes;
  47361. this.getAttributes = function () {
  47362. if ( cachedAttributes === undefined ) {
  47363. // Populates cachedAttributes and cachedUniforms
  47364. onFirstUse( this );
  47365. }
  47366. return cachedAttributes;
  47367. };
  47368. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47369. // flag the program as ready immediately. It may cause a stall when it's first used.
  47370. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47371. this.isReady = function () {
  47372. if ( programReady === false ) {
  47373. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47374. }
  47375. return programReady;
  47376. };
  47377. // free resource
  47378. this.destroy = function () {
  47379. bindingStates.releaseStatesOfProgram( this );
  47380. gl.deleteProgram( program );
  47381. this.program = undefined;
  47382. };
  47383. //
  47384. this.type = parameters.shaderType;
  47385. this.name = parameters.shaderName;
  47386. this.id = programIdCount ++;
  47387. this.cacheKey = cacheKey;
  47388. this.usedTimes = 1;
  47389. this.program = program;
  47390. this.vertexShader = glVertexShader;
  47391. this.fragmentShader = glFragmentShader;
  47392. return this;
  47393. }
  47394. let _id = 0;
  47395. class WebGLShaderCache {
  47396. constructor() {
  47397. this.shaderCache = new Map();
  47398. this.materialCache = new Map();
  47399. }
  47400. update( material ) {
  47401. const vertexShader = material.vertexShader;
  47402. const fragmentShader = material.fragmentShader;
  47403. const vertexShaderStage = this._getShaderStage( vertexShader );
  47404. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47405. const materialShaders = this._getShaderCacheForMaterial( material );
  47406. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47407. materialShaders.add( vertexShaderStage );
  47408. vertexShaderStage.usedTimes ++;
  47409. }
  47410. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47411. materialShaders.add( fragmentShaderStage );
  47412. fragmentShaderStage.usedTimes ++;
  47413. }
  47414. return this;
  47415. }
  47416. remove( material ) {
  47417. const materialShaders = this.materialCache.get( material );
  47418. for ( const shaderStage of materialShaders ) {
  47419. shaderStage.usedTimes --;
  47420. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47421. }
  47422. this.materialCache.delete( material );
  47423. return this;
  47424. }
  47425. getVertexShaderID( material ) {
  47426. return this._getShaderStage( material.vertexShader ).id;
  47427. }
  47428. getFragmentShaderID( material ) {
  47429. return this._getShaderStage( material.fragmentShader ).id;
  47430. }
  47431. dispose() {
  47432. this.shaderCache.clear();
  47433. this.materialCache.clear();
  47434. }
  47435. _getShaderCacheForMaterial( material ) {
  47436. const cache = this.materialCache;
  47437. let set = cache.get( material );
  47438. if ( set === undefined ) {
  47439. set = new Set();
  47440. cache.set( material, set );
  47441. }
  47442. return set;
  47443. }
  47444. _getShaderStage( code ) {
  47445. const cache = this.shaderCache;
  47446. let stage = cache.get( code );
  47447. if ( stage === undefined ) {
  47448. stage = new WebGLShaderStage( code );
  47449. cache.set( code, stage );
  47450. }
  47451. return stage;
  47452. }
  47453. }
  47454. class WebGLShaderStage {
  47455. constructor( code ) {
  47456. this.id = _id ++;
  47457. this.code = code;
  47458. this.usedTimes = 0;
  47459. }
  47460. }
  47461. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  47462. const _programLayers = new Layers();
  47463. const _customShaders = new WebGLShaderCache();
  47464. const _activeChannels = new Set();
  47465. const programs = [];
  47466. const programsMap = new Map();
  47467. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47468. let precision = capabilities.precision;
  47469. const shaderIDs = {
  47470. MeshDepthMaterial: 'depth',
  47471. MeshDistanceMaterial: 'distance',
  47472. MeshNormalMaterial: 'normal',
  47473. MeshBasicMaterial: 'basic',
  47474. MeshLambertMaterial: 'lambert',
  47475. MeshPhongMaterial: 'phong',
  47476. MeshToonMaterial: 'toon',
  47477. MeshStandardMaterial: 'physical',
  47478. MeshPhysicalMaterial: 'physical',
  47479. MeshMatcapMaterial: 'matcap',
  47480. LineBasicMaterial: 'basic',
  47481. LineDashedMaterial: 'dashed',
  47482. PointsMaterial: 'points',
  47483. ShadowMaterial: 'shadow',
  47484. SpriteMaterial: 'sprite'
  47485. };
  47486. function getChannel( value ) {
  47487. _activeChannels.add( value );
  47488. if ( value === 0 ) return 'uv';
  47489. return `uv${ value }`;
  47490. }
  47491. function getParameters( material, lights, shadows, scene, object ) {
  47492. const fog = scene.fog;
  47493. const geometry = object.geometry;
  47494. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  47495. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  47496. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47497. const shaderID = shaderIDs[ material.type ];
  47498. // heuristics to create shader parameters according to lights in the scene
  47499. // (not to blow over maxLights budget)
  47500. if ( material.precision !== null ) {
  47501. precision = capabilities.getMaxPrecision( material.precision );
  47502. if ( precision !== material.precision ) {
  47503. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47504. }
  47505. }
  47506. //
  47507. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47508. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47509. let morphTextureStride = 0;
  47510. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47511. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47512. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47513. //
  47514. let vertexShader, fragmentShader;
  47515. let customVertexShaderID, customFragmentShaderID;
  47516. if ( shaderID ) {
  47517. const shader = ShaderLib[ shaderID ];
  47518. vertexShader = shader.vertexShader;
  47519. fragmentShader = shader.fragmentShader;
  47520. } else {
  47521. vertexShader = material.vertexShader;
  47522. fragmentShader = material.fragmentShader;
  47523. _customShaders.update( material );
  47524. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47525. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47526. }
  47527. const currentRenderTarget = renderer.getRenderTarget();
  47528. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47529. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47530. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47531. const HAS_MAP = !! material.map;
  47532. const HAS_MATCAP = !! material.matcap;
  47533. const HAS_ENVMAP = !! envMap;
  47534. const HAS_AOMAP = !! material.aoMap;
  47535. const HAS_LIGHTMAP = !! material.lightMap;
  47536. const HAS_BUMPMAP = !! material.bumpMap;
  47537. const HAS_NORMALMAP = !! material.normalMap;
  47538. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47539. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47540. const HAS_METALNESSMAP = !! material.metalnessMap;
  47541. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47542. const HAS_ANISOTROPY = material.anisotropy > 0;
  47543. const HAS_CLEARCOAT = material.clearcoat > 0;
  47544. const HAS_DISPERSION = material.dispersion > 0;
  47545. const HAS_IRIDESCENCE = material.iridescence > 0;
  47546. const HAS_SHEEN = material.sheen > 0;
  47547. const HAS_TRANSMISSION = material.transmission > 0;
  47548. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47549. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47550. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47551. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47552. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47553. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47554. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47555. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47556. const HAS_SPECULARMAP = !! material.specularMap;
  47557. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47558. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47559. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47560. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47561. const HAS_GRADIENTMAP = !! material.gradientMap;
  47562. const HAS_ALPHAMAP = !! material.alphaMap;
  47563. const HAS_ALPHATEST = material.alphaTest > 0;
  47564. const HAS_ALPHAHASH = !! material.alphaHash;
  47565. const HAS_EXTENSIONS = !! material.extensions;
  47566. let toneMapping = NoToneMapping;
  47567. if ( material.toneMapped ) {
  47568. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47569. toneMapping = renderer.toneMapping;
  47570. }
  47571. }
  47572. const parameters = {
  47573. shaderID: shaderID,
  47574. shaderType: material.type,
  47575. shaderName: material.name,
  47576. vertexShader: vertexShader,
  47577. fragmentShader: fragmentShader,
  47578. defines: material.defines,
  47579. customVertexShaderID: customVertexShaderID,
  47580. customFragmentShaderID: customFragmentShaderID,
  47581. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47582. glslVersion: material.glslVersion,
  47583. precision: precision,
  47584. batching: IS_BATCHEDMESH,
  47585. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47586. instancing: IS_INSTANCEDMESH,
  47587. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47588. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47589. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47590. alphaToCoverage: !! material.alphaToCoverage,
  47591. map: HAS_MAP,
  47592. matcap: HAS_MATCAP,
  47593. envMap: HAS_ENVMAP,
  47594. envMapMode: HAS_ENVMAP && envMap.mapping,
  47595. envMapCubeUVHeight: envMapCubeUVHeight,
  47596. aoMap: HAS_AOMAP,
  47597. lightMap: HAS_LIGHTMAP,
  47598. bumpMap: HAS_BUMPMAP,
  47599. normalMap: HAS_NORMALMAP,
  47600. displacementMap: HAS_DISPLACEMENTMAP,
  47601. emissiveMap: HAS_EMISSIVEMAP,
  47602. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47603. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47604. metalnessMap: HAS_METALNESSMAP,
  47605. roughnessMap: HAS_ROUGHNESSMAP,
  47606. anisotropy: HAS_ANISOTROPY,
  47607. anisotropyMap: HAS_ANISOTROPYMAP,
  47608. clearcoat: HAS_CLEARCOAT,
  47609. clearcoatMap: HAS_CLEARCOATMAP,
  47610. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47611. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47612. dispersion: HAS_DISPERSION,
  47613. iridescence: HAS_IRIDESCENCE,
  47614. iridescenceMap: HAS_IRIDESCENCEMAP,
  47615. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47616. sheen: HAS_SHEEN,
  47617. sheenColorMap: HAS_SHEEN_COLORMAP,
  47618. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47619. specularMap: HAS_SPECULARMAP,
  47620. specularColorMap: HAS_SPECULAR_COLORMAP,
  47621. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47622. transmission: HAS_TRANSMISSION,
  47623. transmissionMap: HAS_TRANSMISSIONMAP,
  47624. thicknessMap: HAS_THICKNESSMAP,
  47625. gradientMap: HAS_GRADIENTMAP,
  47626. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47627. alphaMap: HAS_ALPHAMAP,
  47628. alphaTest: HAS_ALPHATEST,
  47629. alphaHash: HAS_ALPHAHASH,
  47630. combine: material.combine,
  47631. //
  47632. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47633. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47634. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47635. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47636. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47637. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47638. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47639. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47640. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47641. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47642. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47643. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47644. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47645. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47646. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47647. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47648. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47649. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47650. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47651. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47652. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47653. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47654. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47655. //
  47656. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47657. vertexColors: material.vertexColors,
  47658. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47659. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47660. fog: !! fog,
  47661. useFog: material.fog === true,
  47662. fogExp2: ( !! fog && fog.isFogExp2 ),
  47663. flatShading: ( material.flatShading === true && material.wireframe === false ),
  47664. sizeAttenuation: material.sizeAttenuation === true,
  47665. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47666. reversedDepthBuffer: reversedDepthBuffer,
  47667. skinning: object.isSkinnedMesh === true,
  47668. morphTargets: geometry.morphAttributes.position !== undefined,
  47669. morphNormals: geometry.morphAttributes.normal !== undefined,
  47670. morphColors: geometry.morphAttributes.color !== undefined,
  47671. morphTargetsCount: morphTargetsCount,
  47672. morphTextureStride: morphTextureStride,
  47673. numDirLights: lights.directional.length,
  47674. numPointLights: lights.point.length,
  47675. numSpotLights: lights.spot.length,
  47676. numSpotLightMaps: lights.spotLightMap.length,
  47677. numRectAreaLights: lights.rectArea.length,
  47678. numHemiLights: lights.hemi.length,
  47679. numDirLightShadows: lights.directionalShadowMap.length,
  47680. numPointLightShadows: lights.pointShadowMap.length,
  47681. numSpotLightShadows: lights.spotShadowMap.length,
  47682. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47683. numLightProbes: lights.numLightProbes,
  47684. numClippingPlanes: clipping.numPlanes,
  47685. numClipIntersection: clipping.numIntersection,
  47686. dithering: material.dithering,
  47687. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47688. shadowMapType: renderer.shadowMap.type,
  47689. toneMapping: toneMapping,
  47690. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47691. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47692. premultipliedAlpha: material.premultipliedAlpha,
  47693. doubleSided: material.side === DoubleSide,
  47694. flipSided: material.side === BackSide,
  47695. useDepthPacking: material.depthPacking >= 0,
  47696. depthPacking: material.depthPacking || 0,
  47697. index0AttributeName: material.index0AttributeName,
  47698. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47699. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47700. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47701. customProgramCacheKey: material.customProgramCacheKey()
  47702. };
  47703. // the usage of getChannel() determines the active texture channels for this shader
  47704. parameters.vertexUv1s = _activeChannels.has( 1 );
  47705. parameters.vertexUv2s = _activeChannels.has( 2 );
  47706. parameters.vertexUv3s = _activeChannels.has( 3 );
  47707. _activeChannels.clear();
  47708. return parameters;
  47709. }
  47710. function getProgramCacheKey( parameters ) {
  47711. const array = [];
  47712. if ( parameters.shaderID ) {
  47713. array.push( parameters.shaderID );
  47714. } else {
  47715. array.push( parameters.customVertexShaderID );
  47716. array.push( parameters.customFragmentShaderID );
  47717. }
  47718. if ( parameters.defines !== undefined ) {
  47719. for ( const name in parameters.defines ) {
  47720. array.push( name );
  47721. array.push( parameters.defines[ name ] );
  47722. }
  47723. }
  47724. if ( parameters.isRawShaderMaterial === false ) {
  47725. getProgramCacheKeyParameters( array, parameters );
  47726. getProgramCacheKeyBooleans( array, parameters );
  47727. array.push( renderer.outputColorSpace );
  47728. }
  47729. array.push( parameters.customProgramCacheKey );
  47730. return array.join();
  47731. }
  47732. function getProgramCacheKeyParameters( array, parameters ) {
  47733. array.push( parameters.precision );
  47734. array.push( parameters.outputColorSpace );
  47735. array.push( parameters.envMapMode );
  47736. array.push( parameters.envMapCubeUVHeight );
  47737. array.push( parameters.mapUv );
  47738. array.push( parameters.alphaMapUv );
  47739. array.push( parameters.lightMapUv );
  47740. array.push( parameters.aoMapUv );
  47741. array.push( parameters.bumpMapUv );
  47742. array.push( parameters.normalMapUv );
  47743. array.push( parameters.displacementMapUv );
  47744. array.push( parameters.emissiveMapUv );
  47745. array.push( parameters.metalnessMapUv );
  47746. array.push( parameters.roughnessMapUv );
  47747. array.push( parameters.anisotropyMapUv );
  47748. array.push( parameters.clearcoatMapUv );
  47749. array.push( parameters.clearcoatNormalMapUv );
  47750. array.push( parameters.clearcoatRoughnessMapUv );
  47751. array.push( parameters.iridescenceMapUv );
  47752. array.push( parameters.iridescenceThicknessMapUv );
  47753. array.push( parameters.sheenColorMapUv );
  47754. array.push( parameters.sheenRoughnessMapUv );
  47755. array.push( parameters.specularMapUv );
  47756. array.push( parameters.specularColorMapUv );
  47757. array.push( parameters.specularIntensityMapUv );
  47758. array.push( parameters.transmissionMapUv );
  47759. array.push( parameters.thicknessMapUv );
  47760. array.push( parameters.combine );
  47761. array.push( parameters.fogExp2 );
  47762. array.push( parameters.sizeAttenuation );
  47763. array.push( parameters.morphTargetsCount );
  47764. array.push( parameters.morphAttributeCount );
  47765. array.push( parameters.numDirLights );
  47766. array.push( parameters.numPointLights );
  47767. array.push( parameters.numSpotLights );
  47768. array.push( parameters.numSpotLightMaps );
  47769. array.push( parameters.numHemiLights );
  47770. array.push( parameters.numRectAreaLights );
  47771. array.push( parameters.numDirLightShadows );
  47772. array.push( parameters.numPointLightShadows );
  47773. array.push( parameters.numSpotLightShadows );
  47774. array.push( parameters.numSpotLightShadowsWithMaps );
  47775. array.push( parameters.numLightProbes );
  47776. array.push( parameters.shadowMapType );
  47777. array.push( parameters.toneMapping );
  47778. array.push( parameters.numClippingPlanes );
  47779. array.push( parameters.numClipIntersection );
  47780. array.push( parameters.depthPacking );
  47781. }
  47782. function getProgramCacheKeyBooleans( array, parameters ) {
  47783. _programLayers.disableAll();
  47784. if ( parameters.instancing )
  47785. _programLayers.enable( 0 );
  47786. if ( parameters.instancingColor )
  47787. _programLayers.enable( 1 );
  47788. if ( parameters.instancingMorph )
  47789. _programLayers.enable( 2 );
  47790. if ( parameters.matcap )
  47791. _programLayers.enable( 3 );
  47792. if ( parameters.envMap )
  47793. _programLayers.enable( 4 );
  47794. if ( parameters.normalMapObjectSpace )
  47795. _programLayers.enable( 5 );
  47796. if ( parameters.normalMapTangentSpace )
  47797. _programLayers.enable( 6 );
  47798. if ( parameters.clearcoat )
  47799. _programLayers.enable( 7 );
  47800. if ( parameters.iridescence )
  47801. _programLayers.enable( 8 );
  47802. if ( parameters.alphaTest )
  47803. _programLayers.enable( 9 );
  47804. if ( parameters.vertexColors )
  47805. _programLayers.enable( 10 );
  47806. if ( parameters.vertexAlphas )
  47807. _programLayers.enable( 11 );
  47808. if ( parameters.vertexUv1s )
  47809. _programLayers.enable( 12 );
  47810. if ( parameters.vertexUv2s )
  47811. _programLayers.enable( 13 );
  47812. if ( parameters.vertexUv3s )
  47813. _programLayers.enable( 14 );
  47814. if ( parameters.vertexTangents )
  47815. _programLayers.enable( 15 );
  47816. if ( parameters.anisotropy )
  47817. _programLayers.enable( 16 );
  47818. if ( parameters.alphaHash )
  47819. _programLayers.enable( 17 );
  47820. if ( parameters.batching )
  47821. _programLayers.enable( 18 );
  47822. if ( parameters.dispersion )
  47823. _programLayers.enable( 19 );
  47824. if ( parameters.batchingColor )
  47825. _programLayers.enable( 20 );
  47826. if ( parameters.gradientMap )
  47827. _programLayers.enable( 21 );
  47828. array.push( _programLayers.mask );
  47829. _programLayers.disableAll();
  47830. if ( parameters.fog )
  47831. _programLayers.enable( 0 );
  47832. if ( parameters.useFog )
  47833. _programLayers.enable( 1 );
  47834. if ( parameters.flatShading )
  47835. _programLayers.enable( 2 );
  47836. if ( parameters.logarithmicDepthBuffer )
  47837. _programLayers.enable( 3 );
  47838. if ( parameters.reversedDepthBuffer )
  47839. _programLayers.enable( 4 );
  47840. if ( parameters.skinning )
  47841. _programLayers.enable( 5 );
  47842. if ( parameters.morphTargets )
  47843. _programLayers.enable( 6 );
  47844. if ( parameters.morphNormals )
  47845. _programLayers.enable( 7 );
  47846. if ( parameters.morphColors )
  47847. _programLayers.enable( 8 );
  47848. if ( parameters.premultipliedAlpha )
  47849. _programLayers.enable( 9 );
  47850. if ( parameters.shadowMapEnabled )
  47851. _programLayers.enable( 10 );
  47852. if ( parameters.doubleSided )
  47853. _programLayers.enable( 11 );
  47854. if ( parameters.flipSided )
  47855. _programLayers.enable( 12 );
  47856. if ( parameters.useDepthPacking )
  47857. _programLayers.enable( 13 );
  47858. if ( parameters.dithering )
  47859. _programLayers.enable( 14 );
  47860. if ( parameters.transmission )
  47861. _programLayers.enable( 15 );
  47862. if ( parameters.sheen )
  47863. _programLayers.enable( 16 );
  47864. if ( parameters.opaque )
  47865. _programLayers.enable( 17 );
  47866. if ( parameters.pointsUvs )
  47867. _programLayers.enable( 18 );
  47868. if ( parameters.decodeVideoTexture )
  47869. _programLayers.enable( 19 );
  47870. if ( parameters.decodeVideoTextureEmissive )
  47871. _programLayers.enable( 20 );
  47872. if ( parameters.alphaToCoverage )
  47873. _programLayers.enable( 21 );
  47874. array.push( _programLayers.mask );
  47875. }
  47876. function getUniforms( material ) {
  47877. const shaderID = shaderIDs[ material.type ];
  47878. let uniforms;
  47879. if ( shaderID ) {
  47880. const shader = ShaderLib[ shaderID ];
  47881. uniforms = UniformsUtils.clone( shader.uniforms );
  47882. } else {
  47883. uniforms = material.uniforms;
  47884. }
  47885. return uniforms;
  47886. }
  47887. function acquireProgram( parameters, cacheKey ) {
  47888. let program = programsMap.get( cacheKey );
  47889. if ( program !== undefined ) {
  47890. ++ program.usedTimes;
  47891. } else {
  47892. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47893. programs.push( program );
  47894. programsMap.set( cacheKey, program );
  47895. }
  47896. return program;
  47897. }
  47898. function releaseProgram( program ) {
  47899. if ( -- program.usedTimes === 0 ) {
  47900. // Remove from unordered set
  47901. const i = programs.indexOf( program );
  47902. programs[ i ] = programs[ programs.length - 1 ];
  47903. programs.pop();
  47904. // Remove from map
  47905. programsMap.delete( program.cacheKey );
  47906. // Free WebGL resources
  47907. program.destroy();
  47908. }
  47909. }
  47910. function releaseShaderCache( material ) {
  47911. _customShaders.remove( material );
  47912. }
  47913. function dispose() {
  47914. _customShaders.dispose();
  47915. }
  47916. return {
  47917. getParameters: getParameters,
  47918. getProgramCacheKey: getProgramCacheKey,
  47919. getUniforms: getUniforms,
  47920. acquireProgram: acquireProgram,
  47921. releaseProgram: releaseProgram,
  47922. releaseShaderCache: releaseShaderCache,
  47923. // Exposed for resource monitoring & error feedback via renderer.info:
  47924. programs: programs,
  47925. dispose: dispose
  47926. };
  47927. }
  47928. function WebGLProperties() {
  47929. let properties = new WeakMap();
  47930. function has( object ) {
  47931. return properties.has( object );
  47932. }
  47933. function get( object ) {
  47934. let map = properties.get( object );
  47935. if ( map === undefined ) {
  47936. map = {};
  47937. properties.set( object, map );
  47938. }
  47939. return map;
  47940. }
  47941. function remove( object ) {
  47942. properties.delete( object );
  47943. }
  47944. function update( object, key, value ) {
  47945. properties.get( object )[ key ] = value;
  47946. }
  47947. function dispose() {
  47948. properties = new WeakMap();
  47949. }
  47950. return {
  47951. has: has,
  47952. get: get,
  47953. remove: remove,
  47954. update: update,
  47955. dispose: dispose
  47956. };
  47957. }
  47958. function painterSortStable( a, b ) {
  47959. if ( a.groupOrder !== b.groupOrder ) {
  47960. return a.groupOrder - b.groupOrder;
  47961. } else if ( a.renderOrder !== b.renderOrder ) {
  47962. return a.renderOrder - b.renderOrder;
  47963. } else if ( a.material.id !== b.material.id ) {
  47964. return a.material.id - b.material.id;
  47965. } else if ( a.materialVariant !== b.materialVariant ) {
  47966. return a.materialVariant - b.materialVariant;
  47967. } else if ( a.z !== b.z ) {
  47968. return a.z - b.z;
  47969. } else {
  47970. return a.id - b.id;
  47971. }
  47972. }
  47973. function reversePainterSortStable( a, b ) {
  47974. if ( a.groupOrder !== b.groupOrder ) {
  47975. return a.groupOrder - b.groupOrder;
  47976. } else if ( a.renderOrder !== b.renderOrder ) {
  47977. return a.renderOrder - b.renderOrder;
  47978. } else if ( a.z !== b.z ) {
  47979. return b.z - a.z;
  47980. } else {
  47981. return a.id - b.id;
  47982. }
  47983. }
  47984. function WebGLRenderList() {
  47985. const renderItems = [];
  47986. let renderItemsIndex = 0;
  47987. const opaque = [];
  47988. const transmissive = [];
  47989. const transparent = [];
  47990. function init() {
  47991. renderItemsIndex = 0;
  47992. opaque.length = 0;
  47993. transmissive.length = 0;
  47994. transparent.length = 0;
  47995. }
  47996. function materialVariant( object ) {
  47997. let variant = 0;
  47998. if ( object.isInstancedMesh ) variant += 2;
  47999. if ( object.isSkinnedMesh ) variant += 1;
  48000. return variant;
  48001. }
  48002. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  48003. let renderItem = renderItems[ renderItemsIndex ];
  48004. if ( renderItem === undefined ) {
  48005. renderItem = {
  48006. id: object.id,
  48007. object: object,
  48008. geometry: geometry,
  48009. material: material,
  48010. materialVariant: materialVariant( object ),
  48011. groupOrder: groupOrder,
  48012. renderOrder: object.renderOrder,
  48013. z: z,
  48014. group: group
  48015. };
  48016. renderItems[ renderItemsIndex ] = renderItem;
  48017. } else {
  48018. renderItem.id = object.id;
  48019. renderItem.object = object;
  48020. renderItem.geometry = geometry;
  48021. renderItem.material = material;
  48022. renderItem.materialVariant = materialVariant( object );
  48023. renderItem.groupOrder = groupOrder;
  48024. renderItem.renderOrder = object.renderOrder;
  48025. renderItem.z = z;
  48026. renderItem.group = group;
  48027. }
  48028. renderItemsIndex ++;
  48029. return renderItem;
  48030. }
  48031. function push( object, geometry, material, groupOrder, z, group ) {
  48032. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48033. if ( material.transmission > 0.0 ) {
  48034. transmissive.push( renderItem );
  48035. } else if ( material.transparent === true ) {
  48036. transparent.push( renderItem );
  48037. } else {
  48038. opaque.push( renderItem );
  48039. }
  48040. }
  48041. function unshift( object, geometry, material, groupOrder, z, group ) {
  48042. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  48043. if ( material.transmission > 0.0 ) {
  48044. transmissive.unshift( renderItem );
  48045. } else if ( material.transparent === true ) {
  48046. transparent.unshift( renderItem );
  48047. } else {
  48048. opaque.unshift( renderItem );
  48049. }
  48050. }
  48051. function sort( customOpaqueSort, customTransparentSort ) {
  48052. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  48053. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  48054. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  48055. }
  48056. function finish() {
  48057. // Clear references from inactive renderItems in the list
  48058. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  48059. const renderItem = renderItems[ i ];
  48060. if ( renderItem.id === null ) break;
  48061. renderItem.id = null;
  48062. renderItem.object = null;
  48063. renderItem.geometry = null;
  48064. renderItem.material = null;
  48065. renderItem.group = null;
  48066. }
  48067. }
  48068. return {
  48069. opaque: opaque,
  48070. transmissive: transmissive,
  48071. transparent: transparent,
  48072. init: init,
  48073. push: push,
  48074. unshift: unshift,
  48075. finish: finish,
  48076. sort: sort
  48077. };
  48078. }
  48079. function WebGLRenderLists() {
  48080. let lists = new WeakMap();
  48081. function get( scene, renderCallDepth ) {
  48082. const listArray = lists.get( scene );
  48083. let list;
  48084. if ( listArray === undefined ) {
  48085. list = new WebGLRenderList();
  48086. lists.set( scene, [ list ] );
  48087. } else {
  48088. if ( renderCallDepth >= listArray.length ) {
  48089. list = new WebGLRenderList();
  48090. listArray.push( list );
  48091. } else {
  48092. list = listArray[ renderCallDepth ];
  48093. }
  48094. }
  48095. return list;
  48096. }
  48097. function dispose() {
  48098. lists = new WeakMap();
  48099. }
  48100. return {
  48101. get: get,
  48102. dispose: dispose
  48103. };
  48104. }
  48105. function UniformsCache() {
  48106. const lights = {};
  48107. return {
  48108. get: function ( light ) {
  48109. if ( lights[ light.id ] !== undefined ) {
  48110. return lights[ light.id ];
  48111. }
  48112. let uniforms;
  48113. switch ( light.type ) {
  48114. case 'DirectionalLight':
  48115. uniforms = {
  48116. direction: new Vector3(),
  48117. color: new Color()
  48118. };
  48119. break;
  48120. case 'SpotLight':
  48121. uniforms = {
  48122. position: new Vector3(),
  48123. direction: new Vector3(),
  48124. color: new Color(),
  48125. distance: 0,
  48126. coneCos: 0,
  48127. penumbraCos: 0,
  48128. decay: 0
  48129. };
  48130. break;
  48131. case 'PointLight':
  48132. uniforms = {
  48133. position: new Vector3(),
  48134. color: new Color(),
  48135. distance: 0,
  48136. decay: 0
  48137. };
  48138. break;
  48139. case 'HemisphereLight':
  48140. uniforms = {
  48141. direction: new Vector3(),
  48142. skyColor: new Color(),
  48143. groundColor: new Color()
  48144. };
  48145. break;
  48146. case 'RectAreaLight':
  48147. uniforms = {
  48148. color: new Color(),
  48149. position: new Vector3(),
  48150. halfWidth: new Vector3(),
  48151. halfHeight: new Vector3()
  48152. };
  48153. break;
  48154. }
  48155. lights[ light.id ] = uniforms;
  48156. return uniforms;
  48157. }
  48158. };
  48159. }
  48160. function ShadowUniformsCache() {
  48161. const lights = {};
  48162. return {
  48163. get: function ( light ) {
  48164. if ( lights[ light.id ] !== undefined ) {
  48165. return lights[ light.id ];
  48166. }
  48167. let uniforms;
  48168. switch ( light.type ) {
  48169. case 'DirectionalLight':
  48170. uniforms = {
  48171. shadowIntensity: 1,
  48172. shadowBias: 0,
  48173. shadowNormalBias: 0,
  48174. shadowRadius: 1,
  48175. shadowMapSize: new Vector2()
  48176. };
  48177. break;
  48178. case 'SpotLight':
  48179. uniforms = {
  48180. shadowIntensity: 1,
  48181. shadowBias: 0,
  48182. shadowNormalBias: 0,
  48183. shadowRadius: 1,
  48184. shadowMapSize: new Vector2()
  48185. };
  48186. break;
  48187. case 'PointLight':
  48188. uniforms = {
  48189. shadowIntensity: 1,
  48190. shadowBias: 0,
  48191. shadowNormalBias: 0,
  48192. shadowRadius: 1,
  48193. shadowMapSize: new Vector2(),
  48194. shadowCameraNear: 1,
  48195. shadowCameraFar: 1000
  48196. };
  48197. break;
  48198. // TODO (abelnation): set RectAreaLight shadow uniforms
  48199. }
  48200. lights[ light.id ] = uniforms;
  48201. return uniforms;
  48202. }
  48203. };
  48204. }
  48205. let nextVersion = 0;
  48206. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  48207. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  48208. }
  48209. function WebGLLights( extensions ) {
  48210. const cache = new UniformsCache();
  48211. const shadowCache = ShadowUniformsCache();
  48212. const state = {
  48213. version: 0,
  48214. hash: {
  48215. directionalLength: -1,
  48216. pointLength: -1,
  48217. spotLength: -1,
  48218. rectAreaLength: -1,
  48219. hemiLength: -1,
  48220. numDirectionalShadows: -1,
  48221. numPointShadows: -1,
  48222. numSpotShadows: -1,
  48223. numSpotMaps: -1,
  48224. numLightProbes: -1
  48225. },
  48226. ambient: [ 0, 0, 0 ],
  48227. probe: [],
  48228. directional: [],
  48229. directionalShadow: [],
  48230. directionalShadowMap: [],
  48231. directionalShadowMatrix: [],
  48232. spot: [],
  48233. spotLightMap: [],
  48234. spotShadow: [],
  48235. spotShadowMap: [],
  48236. spotLightMatrix: [],
  48237. rectArea: [],
  48238. rectAreaLTC1: null,
  48239. rectAreaLTC2: null,
  48240. point: [],
  48241. pointShadow: [],
  48242. pointShadowMap: [],
  48243. pointShadowMatrix: [],
  48244. hemi: [],
  48245. numSpotLightShadowsWithMaps: 0,
  48246. numLightProbes: 0
  48247. };
  48248. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  48249. const vector3 = new Vector3();
  48250. const matrix4 = new Matrix4();
  48251. const matrix42 = new Matrix4();
  48252. function setup( lights ) {
  48253. let r = 0, g = 0, b = 0;
  48254. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  48255. let directionalLength = 0;
  48256. let pointLength = 0;
  48257. let spotLength = 0;
  48258. let rectAreaLength = 0;
  48259. let hemiLength = 0;
  48260. let numDirectionalShadows = 0;
  48261. let numPointShadows = 0;
  48262. let numSpotShadows = 0;
  48263. let numSpotMaps = 0;
  48264. let numSpotShadowsWithMaps = 0;
  48265. let numLightProbes = 0;
  48266. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  48267. lights.sort( shadowCastingAndTexturingLightsFirst );
  48268. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48269. const light = lights[ i ];
  48270. const color = light.color;
  48271. const intensity = light.intensity;
  48272. const distance = light.distance;
  48273. let shadowMap = null;
  48274. if ( light.shadow && light.shadow.map ) {
  48275. if ( light.shadow.map.texture.format === RGFormat ) {
  48276. // VSM uses color texture with blurred mean/std_dev
  48277. shadowMap = light.shadow.map.texture;
  48278. } else {
  48279. // Other types use depth texture
  48280. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48281. }
  48282. }
  48283. if ( light.isAmbientLight ) {
  48284. r += color.r * intensity;
  48285. g += color.g * intensity;
  48286. b += color.b * intensity;
  48287. } else if ( light.isLightProbe ) {
  48288. for ( let j = 0; j < 9; j ++ ) {
  48289. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48290. }
  48291. numLightProbes ++;
  48292. } else if ( light.isDirectionalLight ) {
  48293. const uniforms = cache.get( light );
  48294. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48295. if ( light.castShadow ) {
  48296. const shadow = light.shadow;
  48297. const shadowUniforms = shadowCache.get( light );
  48298. shadowUniforms.shadowIntensity = shadow.intensity;
  48299. shadowUniforms.shadowBias = shadow.bias;
  48300. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48301. shadowUniforms.shadowRadius = shadow.radius;
  48302. shadowUniforms.shadowMapSize = shadow.mapSize;
  48303. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48304. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48305. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48306. numDirectionalShadows ++;
  48307. }
  48308. state.directional[ directionalLength ] = uniforms;
  48309. directionalLength ++;
  48310. } else if ( light.isSpotLight ) {
  48311. const uniforms = cache.get( light );
  48312. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48313. uniforms.color.copy( color ).multiplyScalar( intensity );
  48314. uniforms.distance = distance;
  48315. uniforms.coneCos = Math.cos( light.angle );
  48316. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48317. uniforms.decay = light.decay;
  48318. state.spot[ spotLength ] = uniforms;
  48319. const shadow = light.shadow;
  48320. if ( light.map ) {
  48321. state.spotLightMap[ numSpotMaps ] = light.map;
  48322. numSpotMaps ++;
  48323. // make sure the lightMatrix is up to date
  48324. // TODO : do it if required only
  48325. shadow.updateMatrices( light );
  48326. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48327. }
  48328. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48329. if ( light.castShadow ) {
  48330. const shadowUniforms = shadowCache.get( light );
  48331. shadowUniforms.shadowIntensity = shadow.intensity;
  48332. shadowUniforms.shadowBias = shadow.bias;
  48333. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48334. shadowUniforms.shadowRadius = shadow.radius;
  48335. shadowUniforms.shadowMapSize = shadow.mapSize;
  48336. state.spotShadow[ spotLength ] = shadowUniforms;
  48337. state.spotShadowMap[ spotLength ] = shadowMap;
  48338. numSpotShadows ++;
  48339. }
  48340. spotLength ++;
  48341. } else if ( light.isRectAreaLight ) {
  48342. const uniforms = cache.get( light );
  48343. uniforms.color.copy( color ).multiplyScalar( intensity );
  48344. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48345. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48346. state.rectArea[ rectAreaLength ] = uniforms;
  48347. rectAreaLength ++;
  48348. } else if ( light.isPointLight ) {
  48349. const uniforms = cache.get( light );
  48350. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48351. uniforms.distance = light.distance;
  48352. uniforms.decay = light.decay;
  48353. if ( light.castShadow ) {
  48354. const shadow = light.shadow;
  48355. const shadowUniforms = shadowCache.get( light );
  48356. shadowUniforms.shadowIntensity = shadow.intensity;
  48357. shadowUniforms.shadowBias = shadow.bias;
  48358. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48359. shadowUniforms.shadowRadius = shadow.radius;
  48360. shadowUniforms.shadowMapSize = shadow.mapSize;
  48361. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48362. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48363. state.pointShadow[ pointLength ] = shadowUniforms;
  48364. state.pointShadowMap[ pointLength ] = shadowMap;
  48365. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48366. numPointShadows ++;
  48367. }
  48368. state.point[ pointLength ] = uniforms;
  48369. pointLength ++;
  48370. } else if ( light.isHemisphereLight ) {
  48371. const uniforms = cache.get( light );
  48372. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48373. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48374. state.hemi[ hemiLength ] = uniforms;
  48375. hemiLength ++;
  48376. }
  48377. }
  48378. if ( rectAreaLength > 0 ) {
  48379. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48380. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48381. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48382. } else {
  48383. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48384. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48385. }
  48386. }
  48387. state.ambient[ 0 ] = r;
  48388. state.ambient[ 1 ] = g;
  48389. state.ambient[ 2 ] = b;
  48390. const hash = state.hash;
  48391. if ( hash.directionalLength !== directionalLength ||
  48392. hash.pointLength !== pointLength ||
  48393. hash.spotLength !== spotLength ||
  48394. hash.rectAreaLength !== rectAreaLength ||
  48395. hash.hemiLength !== hemiLength ||
  48396. hash.numDirectionalShadows !== numDirectionalShadows ||
  48397. hash.numPointShadows !== numPointShadows ||
  48398. hash.numSpotShadows !== numSpotShadows ||
  48399. hash.numSpotMaps !== numSpotMaps ||
  48400. hash.numLightProbes !== numLightProbes ) {
  48401. state.directional.length = directionalLength;
  48402. state.spot.length = spotLength;
  48403. state.rectArea.length = rectAreaLength;
  48404. state.point.length = pointLength;
  48405. state.hemi.length = hemiLength;
  48406. state.directionalShadow.length = numDirectionalShadows;
  48407. state.directionalShadowMap.length = numDirectionalShadows;
  48408. state.pointShadow.length = numPointShadows;
  48409. state.pointShadowMap.length = numPointShadows;
  48410. state.spotShadow.length = numSpotShadows;
  48411. state.spotShadowMap.length = numSpotShadows;
  48412. state.directionalShadowMatrix.length = numDirectionalShadows;
  48413. state.pointShadowMatrix.length = numPointShadows;
  48414. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48415. state.spotLightMap.length = numSpotMaps;
  48416. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48417. state.numLightProbes = numLightProbes;
  48418. hash.directionalLength = directionalLength;
  48419. hash.pointLength = pointLength;
  48420. hash.spotLength = spotLength;
  48421. hash.rectAreaLength = rectAreaLength;
  48422. hash.hemiLength = hemiLength;
  48423. hash.numDirectionalShadows = numDirectionalShadows;
  48424. hash.numPointShadows = numPointShadows;
  48425. hash.numSpotShadows = numSpotShadows;
  48426. hash.numSpotMaps = numSpotMaps;
  48427. hash.numLightProbes = numLightProbes;
  48428. state.version = nextVersion ++;
  48429. }
  48430. }
  48431. function setupView( lights, camera ) {
  48432. let directionalLength = 0;
  48433. let pointLength = 0;
  48434. let spotLength = 0;
  48435. let rectAreaLength = 0;
  48436. let hemiLength = 0;
  48437. const viewMatrix = camera.matrixWorldInverse;
  48438. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48439. const light = lights[ i ];
  48440. if ( light.isDirectionalLight ) {
  48441. const uniforms = state.directional[ directionalLength ];
  48442. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48443. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48444. uniforms.direction.sub( vector3 );
  48445. uniforms.direction.transformDirection( viewMatrix );
  48446. directionalLength ++;
  48447. } else if ( light.isSpotLight ) {
  48448. const uniforms = state.spot[ spotLength ];
  48449. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48450. uniforms.position.applyMatrix4( viewMatrix );
  48451. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48452. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48453. uniforms.direction.sub( vector3 );
  48454. uniforms.direction.transformDirection( viewMatrix );
  48455. spotLength ++;
  48456. } else if ( light.isRectAreaLight ) {
  48457. const uniforms = state.rectArea[ rectAreaLength ];
  48458. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48459. uniforms.position.applyMatrix4( viewMatrix );
  48460. // extract local rotation of light to derive width/height half vectors
  48461. matrix42.identity();
  48462. matrix4.copy( light.matrixWorld );
  48463. matrix4.premultiply( viewMatrix );
  48464. matrix42.extractRotation( matrix4 );
  48465. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48466. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48467. uniforms.halfWidth.applyMatrix4( matrix42 );
  48468. uniforms.halfHeight.applyMatrix4( matrix42 );
  48469. rectAreaLength ++;
  48470. } else if ( light.isPointLight ) {
  48471. const uniforms = state.point[ pointLength ];
  48472. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48473. uniforms.position.applyMatrix4( viewMatrix );
  48474. pointLength ++;
  48475. } else if ( light.isHemisphereLight ) {
  48476. const uniforms = state.hemi[ hemiLength ];
  48477. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48478. uniforms.direction.transformDirection( viewMatrix );
  48479. hemiLength ++;
  48480. }
  48481. }
  48482. }
  48483. return {
  48484. setup: setup,
  48485. setupView: setupView,
  48486. state: state
  48487. };
  48488. }
  48489. function WebGLRenderState( extensions ) {
  48490. const lights = new WebGLLights( extensions );
  48491. const lightsArray = [];
  48492. const shadowsArray = [];
  48493. function init( camera ) {
  48494. state.camera = camera;
  48495. lightsArray.length = 0;
  48496. shadowsArray.length = 0;
  48497. }
  48498. function pushLight( light ) {
  48499. lightsArray.push( light );
  48500. }
  48501. function pushShadow( shadowLight ) {
  48502. shadowsArray.push( shadowLight );
  48503. }
  48504. function setupLights() {
  48505. lights.setup( lightsArray );
  48506. }
  48507. function setupLightsView( camera ) {
  48508. lights.setupView( lightsArray, camera );
  48509. }
  48510. const state = {
  48511. lightsArray: lightsArray,
  48512. shadowsArray: shadowsArray,
  48513. camera: null,
  48514. lights: lights,
  48515. transmissionRenderTarget: {}
  48516. };
  48517. return {
  48518. init: init,
  48519. state: state,
  48520. setupLights: setupLights,
  48521. setupLightsView: setupLightsView,
  48522. pushLight: pushLight,
  48523. pushShadow: pushShadow
  48524. };
  48525. }
  48526. function WebGLRenderStates( extensions ) {
  48527. let renderStates = new WeakMap();
  48528. function get( scene, renderCallDepth = 0 ) {
  48529. const renderStateArray = renderStates.get( scene );
  48530. let renderState;
  48531. if ( renderStateArray === undefined ) {
  48532. renderState = new WebGLRenderState( extensions );
  48533. renderStates.set( scene, [ renderState ] );
  48534. } else {
  48535. if ( renderCallDepth >= renderStateArray.length ) {
  48536. renderState = new WebGLRenderState( extensions );
  48537. renderStateArray.push( renderState );
  48538. } else {
  48539. renderState = renderStateArray[ renderCallDepth ];
  48540. }
  48541. }
  48542. return renderState;
  48543. }
  48544. function dispose() {
  48545. renderStates = new WeakMap();
  48546. }
  48547. return {
  48548. get: get,
  48549. dispose: dispose
  48550. };
  48551. }
  48552. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48553. 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\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tdepth = 1.0 - depth;\n\t\t\t#endif\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  48554. const _cubeDirections = [
  48555. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48556. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48557. ];
  48558. const _cubeUps = [
  48559. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48560. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48561. ];
  48562. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48563. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48564. const _lookTarget = /*@__PURE__*/ new Vector3();
  48565. function WebGLShadowMap( renderer, objects, capabilities ) {
  48566. let _frustum = new Frustum();
  48567. const _shadowMapSize = new Vector2(),
  48568. _viewportSize = new Vector2(),
  48569. _viewport = new Vector4(),
  48570. _depthMaterial = new MeshDepthMaterial(),
  48571. _distanceMaterial = new MeshDistanceMaterial(),
  48572. _materialCache = {},
  48573. _maxTextureSize = capabilities.maxTextureSize;
  48574. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48575. const shadowMaterialVertical = new ShaderMaterial( {
  48576. defines: {
  48577. VSM_SAMPLES: 8
  48578. },
  48579. uniforms: {
  48580. shadow_pass: { value: null },
  48581. resolution: { value: new Vector2() },
  48582. radius: { value: 4.0 }
  48583. },
  48584. vertexShader: vertex,
  48585. fragmentShader: fragment
  48586. } );
  48587. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48588. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48589. const fullScreenTri = new BufferGeometry();
  48590. fullScreenTri.setAttribute(
  48591. 'position',
  48592. new BufferAttribute(
  48593. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48594. 3
  48595. )
  48596. );
  48597. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48598. const scope = this;
  48599. this.enabled = false;
  48600. this.autoUpdate = true;
  48601. this.needsUpdate = false;
  48602. this.type = PCFShadowMap;
  48603. let _previousType = this.type;
  48604. this.render = function ( lights, scene, camera ) {
  48605. if ( scope.enabled === false ) return;
  48606. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48607. if ( lights.length === 0 ) return;
  48608. if ( this.type === PCFSoftShadowMap ) {
  48609. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48610. this.type = PCFShadowMap;
  48611. }
  48612. const currentRenderTarget = renderer.getRenderTarget();
  48613. const activeCubeFace = renderer.getActiveCubeFace();
  48614. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48615. const _state = renderer.state;
  48616. // Set GL state for depth map.
  48617. _state.setBlending( NoBlending );
  48618. if ( _state.buffers.depth.getReversed() === true ) {
  48619. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48620. } else {
  48621. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48622. }
  48623. _state.buffers.depth.setTest( true );
  48624. _state.setScissorTest( false );
  48625. // check for shadow map type changes
  48626. const typeChanged = _previousType !== this.type;
  48627. // When shadow map type changes, materials need recompilation because sampler types change
  48628. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48629. if ( typeChanged ) {
  48630. scene.traverse( function ( object ) {
  48631. if ( object.material ) {
  48632. if ( Array.isArray( object.material ) ) {
  48633. object.material.forEach( mat => mat.needsUpdate = true );
  48634. } else {
  48635. object.material.needsUpdate = true;
  48636. }
  48637. }
  48638. } );
  48639. }
  48640. // render depth map
  48641. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48642. const light = lights[ i ];
  48643. const shadow = light.shadow;
  48644. if ( shadow === undefined ) {
  48645. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48646. continue;
  48647. }
  48648. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48649. _shadowMapSize.copy( shadow.mapSize );
  48650. const shadowFrameExtents = shadow.getFrameExtents();
  48651. _shadowMapSize.multiply( shadowFrameExtents );
  48652. _viewportSize.copy( shadow.mapSize );
  48653. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48654. if ( _shadowMapSize.x > _maxTextureSize ) {
  48655. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48656. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48657. shadow.mapSize.x = _viewportSize.x;
  48658. }
  48659. if ( _shadowMapSize.y > _maxTextureSize ) {
  48660. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48661. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48662. shadow.mapSize.y = _viewportSize.y;
  48663. }
  48664. }
  48665. if ( shadow.map === null || typeChanged === true ) {
  48666. if ( shadow.map !== null ) {
  48667. if ( shadow.map.depthTexture !== null ) {
  48668. shadow.map.depthTexture.dispose();
  48669. shadow.map.depthTexture = null;
  48670. }
  48671. shadow.map.dispose();
  48672. }
  48673. if ( this.type === VSMShadowMap ) {
  48674. if ( light.isPointLight ) {
  48675. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48676. continue;
  48677. }
  48678. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48679. format: RGFormat,
  48680. type: HalfFloatType,
  48681. minFilter: LinearFilter,
  48682. magFilter: LinearFilter,
  48683. generateMipmaps: false
  48684. } );
  48685. shadow.map.texture.name = light.name + '.shadowMap';
  48686. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48687. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48688. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48689. shadow.map.depthTexture.format = DepthFormat;
  48690. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48691. shadow.map.depthTexture.minFilter = NearestFilter;
  48692. shadow.map.depthTexture.magFilter = NearestFilter;
  48693. } else {
  48694. if ( light.isPointLight ) {
  48695. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48696. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48697. } else {
  48698. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48699. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48700. }
  48701. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48702. shadow.map.depthTexture.format = DepthFormat;
  48703. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48704. if ( this.type === PCFShadowMap ) {
  48705. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48706. shadow.map.depthTexture.minFilter = LinearFilter;
  48707. shadow.map.depthTexture.magFilter = LinearFilter;
  48708. } else {
  48709. shadow.map.depthTexture.compareFunction = null;
  48710. shadow.map.depthTexture.minFilter = NearestFilter;
  48711. shadow.map.depthTexture.magFilter = NearestFilter;
  48712. }
  48713. }
  48714. shadow.camera.updateProjectionMatrix();
  48715. }
  48716. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48717. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48718. for ( let face = 0; face < faceCount; face ++ ) {
  48719. // For cube render targets, render to each face separately
  48720. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48721. renderer.setRenderTarget( shadow.map, face );
  48722. renderer.clear();
  48723. } else {
  48724. // For 2D render targets, use viewports
  48725. if ( face === 0 ) {
  48726. renderer.setRenderTarget( shadow.map );
  48727. renderer.clear();
  48728. }
  48729. const viewport = shadow.getViewport( face );
  48730. _viewport.set(
  48731. _viewportSize.x * viewport.x,
  48732. _viewportSize.y * viewport.y,
  48733. _viewportSize.x * viewport.z,
  48734. _viewportSize.y * viewport.w
  48735. );
  48736. _state.viewport( _viewport );
  48737. }
  48738. if ( light.isPointLight ) {
  48739. const camera = shadow.camera;
  48740. const shadowMatrix = shadow.matrix;
  48741. const far = light.distance || camera.far;
  48742. if ( far !== camera.far ) {
  48743. camera.far = far;
  48744. camera.updateProjectionMatrix();
  48745. }
  48746. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48747. camera.position.copy( _lightPositionWorld );
  48748. _lookTarget.copy( camera.position );
  48749. _lookTarget.add( _cubeDirections[ face ] );
  48750. camera.up.copy( _cubeUps[ face ] );
  48751. camera.lookAt( _lookTarget );
  48752. camera.updateMatrixWorld();
  48753. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48754. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48755. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48756. } else {
  48757. shadow.updateMatrices( light );
  48758. }
  48759. _frustum = shadow.getFrustum();
  48760. renderObject( scene, camera, shadow.camera, light, this.type );
  48761. }
  48762. // do blur pass for VSM
  48763. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48764. VSMPass( shadow, camera );
  48765. }
  48766. shadow.needsUpdate = false;
  48767. }
  48768. _previousType = this.type;
  48769. scope.needsUpdate = false;
  48770. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48771. };
  48772. function VSMPass( shadow, camera ) {
  48773. const geometry = objects.update( fullScreenMesh );
  48774. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48775. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48776. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48777. shadowMaterialVertical.needsUpdate = true;
  48778. shadowMaterialHorizontal.needsUpdate = true;
  48779. }
  48780. if ( shadow.mapPass === null ) {
  48781. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48782. format: RGFormat,
  48783. type: HalfFloatType
  48784. } );
  48785. }
  48786. // vertical pass - read from native depth texture
  48787. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  48788. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48789. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48790. renderer.setRenderTarget( shadow.mapPass );
  48791. renderer.clear();
  48792. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48793. // horizontal pass
  48794. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48795. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48796. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48797. renderer.setRenderTarget( shadow.map );
  48798. renderer.clear();
  48799. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48800. }
  48801. function getDepthMaterial( object, material, light, type ) {
  48802. let result = null;
  48803. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48804. if ( customMaterial !== undefined ) {
  48805. result = customMaterial;
  48806. } else {
  48807. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48808. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48809. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48810. ( material.alphaMap && material.alphaTest > 0 ) ||
  48811. ( material.map && material.alphaTest > 0 ) ||
  48812. ( material.alphaToCoverage === true ) ) {
  48813. // in this case we need a unique material instance reflecting the
  48814. // appropriate state
  48815. const keyA = result.uuid, keyB = material.uuid;
  48816. let materialsForVariant = _materialCache[ keyA ];
  48817. if ( materialsForVariant === undefined ) {
  48818. materialsForVariant = {};
  48819. _materialCache[ keyA ] = materialsForVariant;
  48820. }
  48821. let cachedMaterial = materialsForVariant[ keyB ];
  48822. if ( cachedMaterial === undefined ) {
  48823. cachedMaterial = result.clone();
  48824. materialsForVariant[ keyB ] = cachedMaterial;
  48825. material.addEventListener( 'dispose', onMaterialDispose );
  48826. }
  48827. result = cachedMaterial;
  48828. }
  48829. }
  48830. result.visible = material.visible;
  48831. result.wireframe = material.wireframe;
  48832. if ( type === VSMShadowMap ) {
  48833. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48834. } else {
  48835. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48836. }
  48837. result.alphaMap = material.alphaMap;
  48838. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48839. result.map = material.map;
  48840. result.clipShadows = material.clipShadows;
  48841. result.clippingPlanes = material.clippingPlanes;
  48842. result.clipIntersection = material.clipIntersection;
  48843. result.displacementMap = material.displacementMap;
  48844. result.displacementScale = material.displacementScale;
  48845. result.displacementBias = material.displacementBias;
  48846. result.wireframeLinewidth = material.wireframeLinewidth;
  48847. result.linewidth = material.linewidth;
  48848. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48849. const materialProperties = renderer.properties.get( result );
  48850. materialProperties.light = light;
  48851. }
  48852. return result;
  48853. }
  48854. function renderObject( object, camera, shadowCamera, light, type ) {
  48855. if ( object.visible === false ) return;
  48856. const visible = object.layers.test( camera.layers );
  48857. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48858. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48859. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48860. const geometry = objects.update( object );
  48861. const material = object.material;
  48862. if ( Array.isArray( material ) ) {
  48863. const groups = geometry.groups;
  48864. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48865. const group = groups[ k ];
  48866. const groupMaterial = material[ group.materialIndex ];
  48867. if ( groupMaterial && groupMaterial.visible ) {
  48868. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48869. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48870. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48871. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48872. }
  48873. }
  48874. } else if ( material.visible ) {
  48875. const depthMaterial = getDepthMaterial( object, material, light, type );
  48876. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48877. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48878. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48879. }
  48880. }
  48881. }
  48882. const children = object.children;
  48883. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48884. renderObject( children[ i ], camera, shadowCamera, light, type );
  48885. }
  48886. }
  48887. function onMaterialDispose( event ) {
  48888. const material = event.target;
  48889. material.removeEventListener( 'dispose', onMaterialDispose );
  48890. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48891. for ( const id in _materialCache ) {
  48892. const cache = _materialCache[ id ];
  48893. const uuid = event.target.uuid;
  48894. if ( uuid in cache ) {
  48895. const shadowMaterial = cache[ uuid ];
  48896. shadowMaterial.dispose();
  48897. delete cache[ uuid ];
  48898. }
  48899. }
  48900. }
  48901. }
  48902. const reversedFuncs = {
  48903. [ NeverDepth ]: AlwaysDepth,
  48904. [ LessDepth ]: GreaterDepth,
  48905. [ EqualDepth ]: NotEqualDepth,
  48906. [ LessEqualDepth ]: GreaterEqualDepth,
  48907. [ AlwaysDepth ]: NeverDepth,
  48908. [ GreaterDepth ]: LessDepth,
  48909. [ NotEqualDepth ]: EqualDepth,
  48910. [ GreaterEqualDepth ]: LessEqualDepth,
  48911. };
  48912. function WebGLState( gl, extensions ) {
  48913. function ColorBuffer() {
  48914. let locked = false;
  48915. const color = new Vector4();
  48916. let currentColorMask = null;
  48917. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48918. return {
  48919. setMask: function ( colorMask ) {
  48920. if ( currentColorMask !== colorMask && ! locked ) {
  48921. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48922. currentColorMask = colorMask;
  48923. }
  48924. },
  48925. setLocked: function ( lock ) {
  48926. locked = lock;
  48927. },
  48928. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48929. if ( premultipliedAlpha === true ) {
  48930. r *= a; g *= a; b *= a;
  48931. }
  48932. color.set( r, g, b, a );
  48933. if ( currentColorClear.equals( color ) === false ) {
  48934. gl.clearColor( r, g, b, a );
  48935. currentColorClear.copy( color );
  48936. }
  48937. },
  48938. reset: function () {
  48939. locked = false;
  48940. currentColorMask = null;
  48941. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48942. }
  48943. };
  48944. }
  48945. function DepthBuffer() {
  48946. let locked = false;
  48947. let currentReversed = false;
  48948. let currentDepthMask = null;
  48949. let currentDepthFunc = null;
  48950. let currentDepthClear = null;
  48951. return {
  48952. setReversed: function ( reversed ) {
  48953. if ( currentReversed !== reversed ) {
  48954. const ext = extensions.get( 'EXT_clip_control' );
  48955. if ( reversed ) {
  48956. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48957. } else {
  48958. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48959. }
  48960. currentReversed = reversed;
  48961. const oldDepth = currentDepthClear;
  48962. currentDepthClear = null;
  48963. this.setClear( oldDepth );
  48964. }
  48965. },
  48966. getReversed: function () {
  48967. return currentReversed;
  48968. },
  48969. setTest: function ( depthTest ) {
  48970. if ( depthTest ) {
  48971. enable( gl.DEPTH_TEST );
  48972. } else {
  48973. disable( gl.DEPTH_TEST );
  48974. }
  48975. },
  48976. setMask: function ( depthMask ) {
  48977. if ( currentDepthMask !== depthMask && ! locked ) {
  48978. gl.depthMask( depthMask );
  48979. currentDepthMask = depthMask;
  48980. }
  48981. },
  48982. setFunc: function ( depthFunc ) {
  48983. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48984. if ( currentDepthFunc !== depthFunc ) {
  48985. switch ( depthFunc ) {
  48986. case NeverDepth:
  48987. gl.depthFunc( gl.NEVER );
  48988. break;
  48989. case AlwaysDepth:
  48990. gl.depthFunc( gl.ALWAYS );
  48991. break;
  48992. case LessDepth:
  48993. gl.depthFunc( gl.LESS );
  48994. break;
  48995. case LessEqualDepth:
  48996. gl.depthFunc( gl.LEQUAL );
  48997. break;
  48998. case EqualDepth:
  48999. gl.depthFunc( gl.EQUAL );
  49000. break;
  49001. case GreaterEqualDepth:
  49002. gl.depthFunc( gl.GEQUAL );
  49003. break;
  49004. case GreaterDepth:
  49005. gl.depthFunc( gl.GREATER );
  49006. break;
  49007. case NotEqualDepth:
  49008. gl.depthFunc( gl.NOTEQUAL );
  49009. break;
  49010. default:
  49011. gl.depthFunc( gl.LEQUAL );
  49012. }
  49013. currentDepthFunc = depthFunc;
  49014. }
  49015. },
  49016. setLocked: function ( lock ) {
  49017. locked = lock;
  49018. },
  49019. setClear: function ( depth ) {
  49020. if ( currentDepthClear !== depth ) {
  49021. if ( currentReversed ) {
  49022. depth = 1 - depth;
  49023. }
  49024. gl.clearDepth( depth );
  49025. currentDepthClear = depth;
  49026. }
  49027. },
  49028. reset: function () {
  49029. locked = false;
  49030. currentDepthMask = null;
  49031. currentDepthFunc = null;
  49032. currentDepthClear = null;
  49033. currentReversed = false;
  49034. }
  49035. };
  49036. }
  49037. function StencilBuffer() {
  49038. let locked = false;
  49039. let currentStencilMask = null;
  49040. let currentStencilFunc = null;
  49041. let currentStencilRef = null;
  49042. let currentStencilFuncMask = null;
  49043. let currentStencilFail = null;
  49044. let currentStencilZFail = null;
  49045. let currentStencilZPass = null;
  49046. let currentStencilClear = null;
  49047. return {
  49048. setTest: function ( stencilTest ) {
  49049. if ( ! locked ) {
  49050. if ( stencilTest ) {
  49051. enable( gl.STENCIL_TEST );
  49052. } else {
  49053. disable( gl.STENCIL_TEST );
  49054. }
  49055. }
  49056. },
  49057. setMask: function ( stencilMask ) {
  49058. if ( currentStencilMask !== stencilMask && ! locked ) {
  49059. gl.stencilMask( stencilMask );
  49060. currentStencilMask = stencilMask;
  49061. }
  49062. },
  49063. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  49064. if ( currentStencilFunc !== stencilFunc ||
  49065. currentStencilRef !== stencilRef ||
  49066. currentStencilFuncMask !== stencilMask ) {
  49067. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  49068. currentStencilFunc = stencilFunc;
  49069. currentStencilRef = stencilRef;
  49070. currentStencilFuncMask = stencilMask;
  49071. }
  49072. },
  49073. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  49074. if ( currentStencilFail !== stencilFail ||
  49075. currentStencilZFail !== stencilZFail ||
  49076. currentStencilZPass !== stencilZPass ) {
  49077. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  49078. currentStencilFail = stencilFail;
  49079. currentStencilZFail = stencilZFail;
  49080. currentStencilZPass = stencilZPass;
  49081. }
  49082. },
  49083. setLocked: function ( lock ) {
  49084. locked = lock;
  49085. },
  49086. setClear: function ( stencil ) {
  49087. if ( currentStencilClear !== stencil ) {
  49088. gl.clearStencil( stencil );
  49089. currentStencilClear = stencil;
  49090. }
  49091. },
  49092. reset: function () {
  49093. locked = false;
  49094. currentStencilMask = null;
  49095. currentStencilFunc = null;
  49096. currentStencilRef = null;
  49097. currentStencilFuncMask = null;
  49098. currentStencilFail = null;
  49099. currentStencilZFail = null;
  49100. currentStencilZPass = null;
  49101. currentStencilClear = null;
  49102. }
  49103. };
  49104. }
  49105. //
  49106. const colorBuffer = new ColorBuffer();
  49107. const depthBuffer = new DepthBuffer();
  49108. const stencilBuffer = new StencilBuffer();
  49109. const uboBindings = new WeakMap();
  49110. const uboProgramMap = new WeakMap();
  49111. let enabledCapabilities = {};
  49112. let currentBoundFramebuffers = {};
  49113. let currentDrawbuffers = new WeakMap();
  49114. let defaultDrawbuffers = [];
  49115. let currentProgram = null;
  49116. let currentBlendingEnabled = false;
  49117. let currentBlending = null;
  49118. let currentBlendEquation = null;
  49119. let currentBlendSrc = null;
  49120. let currentBlendDst = null;
  49121. let currentBlendEquationAlpha = null;
  49122. let currentBlendSrcAlpha = null;
  49123. let currentBlendDstAlpha = null;
  49124. let currentBlendColor = new Color( 0, 0, 0 );
  49125. let currentBlendAlpha = 0;
  49126. let currentPremultipledAlpha = false;
  49127. let currentFlipSided = null;
  49128. let currentCullFace = null;
  49129. let currentLineWidth = null;
  49130. let currentPolygonOffsetFactor = null;
  49131. let currentPolygonOffsetUnits = null;
  49132. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  49133. let lineWidthAvailable = false;
  49134. let version = 0;
  49135. const glVersion = gl.getParameter( gl.VERSION );
  49136. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  49137. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  49138. lineWidthAvailable = ( version >= 1.0 );
  49139. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  49140. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  49141. lineWidthAvailable = ( version >= 2.0 );
  49142. }
  49143. let currentTextureSlot = null;
  49144. let currentBoundTextures = {};
  49145. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  49146. const viewportParam = gl.getParameter( gl.VIEWPORT );
  49147. const currentScissor = new Vector4().fromArray( scissorParam );
  49148. const currentViewport = new Vector4().fromArray( viewportParam );
  49149. function createTexture( type, target, count, dimensions ) {
  49150. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  49151. const texture = gl.createTexture();
  49152. gl.bindTexture( type, texture );
  49153. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  49154. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  49155. for ( let i = 0; i < count; i ++ ) {
  49156. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  49157. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49158. } else {
  49159. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  49160. }
  49161. }
  49162. return texture;
  49163. }
  49164. const emptyTextures = {};
  49165. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  49166. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  49167. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  49168. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  49169. // init
  49170. colorBuffer.setClear( 0, 0, 0, 1 );
  49171. depthBuffer.setClear( 1 );
  49172. stencilBuffer.setClear( 0 );
  49173. enable( gl.DEPTH_TEST );
  49174. depthBuffer.setFunc( LessEqualDepth );
  49175. setFlipSided( false );
  49176. setCullFace( CullFaceBack );
  49177. enable( gl.CULL_FACE );
  49178. setBlending( NoBlending );
  49179. //
  49180. function enable( id ) {
  49181. if ( enabledCapabilities[ id ] !== true ) {
  49182. gl.enable( id );
  49183. enabledCapabilities[ id ] = true;
  49184. }
  49185. }
  49186. function disable( id ) {
  49187. if ( enabledCapabilities[ id ] !== false ) {
  49188. gl.disable( id );
  49189. enabledCapabilities[ id ] = false;
  49190. }
  49191. }
  49192. function bindFramebuffer( target, framebuffer ) {
  49193. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  49194. gl.bindFramebuffer( target, framebuffer );
  49195. currentBoundFramebuffers[ target ] = framebuffer;
  49196. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  49197. if ( target === gl.DRAW_FRAMEBUFFER ) {
  49198. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  49199. }
  49200. if ( target === gl.FRAMEBUFFER ) {
  49201. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  49202. }
  49203. return true;
  49204. }
  49205. return false;
  49206. }
  49207. function drawBuffers( renderTarget, framebuffer ) {
  49208. let drawBuffers = defaultDrawbuffers;
  49209. let needsUpdate = false;
  49210. if ( renderTarget ) {
  49211. drawBuffers = currentDrawbuffers.get( framebuffer );
  49212. if ( drawBuffers === undefined ) {
  49213. drawBuffers = [];
  49214. currentDrawbuffers.set( framebuffer, drawBuffers );
  49215. }
  49216. const textures = renderTarget.textures;
  49217. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  49218. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49219. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  49220. }
  49221. drawBuffers.length = textures.length;
  49222. needsUpdate = true;
  49223. }
  49224. } else {
  49225. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  49226. drawBuffers[ 0 ] = gl.BACK;
  49227. needsUpdate = true;
  49228. }
  49229. }
  49230. if ( needsUpdate ) {
  49231. gl.drawBuffers( drawBuffers );
  49232. }
  49233. }
  49234. function useProgram( program ) {
  49235. if ( currentProgram !== program ) {
  49236. gl.useProgram( program );
  49237. currentProgram = program;
  49238. return true;
  49239. }
  49240. return false;
  49241. }
  49242. const equationToGL = {
  49243. [ AddEquation ]: gl.FUNC_ADD,
  49244. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  49245. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  49246. };
  49247. equationToGL[ MinEquation ] = gl.MIN;
  49248. equationToGL[ MaxEquation ] = gl.MAX;
  49249. const factorToGL = {
  49250. [ ZeroFactor ]: gl.ZERO,
  49251. [ OneFactor ]: gl.ONE,
  49252. [ SrcColorFactor ]: gl.SRC_COLOR,
  49253. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  49254. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  49255. [ DstColorFactor ]: gl.DST_COLOR,
  49256. [ DstAlphaFactor ]: gl.DST_ALPHA,
  49257. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  49258. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  49259. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  49260. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  49261. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  49262. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  49263. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  49264. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  49265. };
  49266. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  49267. if ( blending === NoBlending ) {
  49268. if ( currentBlendingEnabled === true ) {
  49269. disable( gl.BLEND );
  49270. currentBlendingEnabled = false;
  49271. }
  49272. return;
  49273. }
  49274. if ( currentBlendingEnabled === false ) {
  49275. enable( gl.BLEND );
  49276. currentBlendingEnabled = true;
  49277. }
  49278. if ( blending !== CustomBlending ) {
  49279. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49280. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49281. gl.blendEquation( gl.FUNC_ADD );
  49282. currentBlendEquation = AddEquation;
  49283. currentBlendEquationAlpha = AddEquation;
  49284. }
  49285. if ( premultipliedAlpha ) {
  49286. switch ( blending ) {
  49287. case NormalBlending:
  49288. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49289. break;
  49290. case AdditiveBlending:
  49291. gl.blendFunc( gl.ONE, gl.ONE );
  49292. break;
  49293. case SubtractiveBlending:
  49294. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49295. break;
  49296. case MultiplyBlending:
  49297. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49298. break;
  49299. default:
  49300. error( 'WebGLState: Invalid blending: ', blending );
  49301. break;
  49302. }
  49303. } else {
  49304. switch ( blending ) {
  49305. case NormalBlending:
  49306. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49307. break;
  49308. case AdditiveBlending:
  49309. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49310. break;
  49311. case SubtractiveBlending:
  49312. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49313. break;
  49314. case MultiplyBlending:
  49315. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49316. break;
  49317. default:
  49318. error( 'WebGLState: Invalid blending: ', blending );
  49319. break;
  49320. }
  49321. }
  49322. currentBlendSrc = null;
  49323. currentBlendDst = null;
  49324. currentBlendSrcAlpha = null;
  49325. currentBlendDstAlpha = null;
  49326. currentBlendColor.set( 0, 0, 0 );
  49327. currentBlendAlpha = 0;
  49328. currentBlending = blending;
  49329. currentPremultipledAlpha = premultipliedAlpha;
  49330. }
  49331. return;
  49332. }
  49333. // custom blending
  49334. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49335. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49336. blendDstAlpha = blendDstAlpha || blendDst;
  49337. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49338. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49339. currentBlendEquation = blendEquation;
  49340. currentBlendEquationAlpha = blendEquationAlpha;
  49341. }
  49342. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49343. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49344. currentBlendSrc = blendSrc;
  49345. currentBlendDst = blendDst;
  49346. currentBlendSrcAlpha = blendSrcAlpha;
  49347. currentBlendDstAlpha = blendDstAlpha;
  49348. }
  49349. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49350. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49351. currentBlendColor.copy( blendColor );
  49352. currentBlendAlpha = blendAlpha;
  49353. }
  49354. currentBlending = blending;
  49355. currentPremultipledAlpha = false;
  49356. }
  49357. function setMaterial( material, frontFaceCW ) {
  49358. material.side === DoubleSide
  49359. ? disable( gl.CULL_FACE )
  49360. : enable( gl.CULL_FACE );
  49361. let flipSided = ( material.side === BackSide );
  49362. if ( frontFaceCW ) flipSided = ! flipSided;
  49363. setFlipSided( flipSided );
  49364. ( material.blending === NormalBlending && material.transparent === false )
  49365. ? setBlending( NoBlending )
  49366. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49367. depthBuffer.setFunc( material.depthFunc );
  49368. depthBuffer.setTest( material.depthTest );
  49369. depthBuffer.setMask( material.depthWrite );
  49370. colorBuffer.setMask( material.colorWrite );
  49371. const stencilWrite = material.stencilWrite;
  49372. stencilBuffer.setTest( stencilWrite );
  49373. if ( stencilWrite ) {
  49374. stencilBuffer.setMask( material.stencilWriteMask );
  49375. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49376. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49377. }
  49378. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49379. material.alphaToCoverage === true
  49380. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49381. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49382. }
  49383. //
  49384. function setFlipSided( flipSided ) {
  49385. if ( currentFlipSided !== flipSided ) {
  49386. if ( flipSided ) {
  49387. gl.frontFace( gl.CW );
  49388. } else {
  49389. gl.frontFace( gl.CCW );
  49390. }
  49391. currentFlipSided = flipSided;
  49392. }
  49393. }
  49394. function setCullFace( cullFace ) {
  49395. if ( cullFace !== CullFaceNone ) {
  49396. enable( gl.CULL_FACE );
  49397. if ( cullFace !== currentCullFace ) {
  49398. if ( cullFace === CullFaceBack ) {
  49399. gl.cullFace( gl.BACK );
  49400. } else if ( cullFace === CullFaceFront ) {
  49401. gl.cullFace( gl.FRONT );
  49402. } else {
  49403. gl.cullFace( gl.FRONT_AND_BACK );
  49404. }
  49405. }
  49406. } else {
  49407. disable( gl.CULL_FACE );
  49408. }
  49409. currentCullFace = cullFace;
  49410. }
  49411. function setLineWidth( width ) {
  49412. if ( width !== currentLineWidth ) {
  49413. if ( lineWidthAvailable ) gl.lineWidth( width );
  49414. currentLineWidth = width;
  49415. }
  49416. }
  49417. function setPolygonOffset( polygonOffset, factor, units ) {
  49418. if ( polygonOffset ) {
  49419. enable( gl.POLYGON_OFFSET_FILL );
  49420. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49421. gl.polygonOffset( factor, units );
  49422. currentPolygonOffsetFactor = factor;
  49423. currentPolygonOffsetUnits = units;
  49424. }
  49425. } else {
  49426. disable( gl.POLYGON_OFFSET_FILL );
  49427. }
  49428. }
  49429. function setScissorTest( scissorTest ) {
  49430. if ( scissorTest ) {
  49431. enable( gl.SCISSOR_TEST );
  49432. } else {
  49433. disable( gl.SCISSOR_TEST );
  49434. }
  49435. }
  49436. // texture
  49437. function activeTexture( webglSlot ) {
  49438. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49439. if ( currentTextureSlot !== webglSlot ) {
  49440. gl.activeTexture( webglSlot );
  49441. currentTextureSlot = webglSlot;
  49442. }
  49443. }
  49444. function bindTexture( webglType, webglTexture, webglSlot ) {
  49445. if ( webglSlot === undefined ) {
  49446. if ( currentTextureSlot === null ) {
  49447. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49448. } else {
  49449. webglSlot = currentTextureSlot;
  49450. }
  49451. }
  49452. let boundTexture = currentBoundTextures[ webglSlot ];
  49453. if ( boundTexture === undefined ) {
  49454. boundTexture = { type: undefined, texture: undefined };
  49455. currentBoundTextures[ webglSlot ] = boundTexture;
  49456. }
  49457. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49458. if ( currentTextureSlot !== webglSlot ) {
  49459. gl.activeTexture( webglSlot );
  49460. currentTextureSlot = webglSlot;
  49461. }
  49462. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49463. boundTexture.type = webglType;
  49464. boundTexture.texture = webglTexture;
  49465. }
  49466. }
  49467. function unbindTexture() {
  49468. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49469. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49470. gl.bindTexture( boundTexture.type, null );
  49471. boundTexture.type = undefined;
  49472. boundTexture.texture = undefined;
  49473. }
  49474. }
  49475. function compressedTexImage2D() {
  49476. try {
  49477. gl.compressedTexImage2D( ...arguments );
  49478. } catch ( e ) {
  49479. error( 'WebGLState:', e );
  49480. }
  49481. }
  49482. function compressedTexImage3D() {
  49483. try {
  49484. gl.compressedTexImage3D( ...arguments );
  49485. } catch ( e ) {
  49486. error( 'WebGLState:', e );
  49487. }
  49488. }
  49489. function texSubImage2D() {
  49490. try {
  49491. gl.texSubImage2D( ...arguments );
  49492. } catch ( e ) {
  49493. error( 'WebGLState:', e );
  49494. }
  49495. }
  49496. function texSubImage3D() {
  49497. try {
  49498. gl.texSubImage3D( ...arguments );
  49499. } catch ( e ) {
  49500. error( 'WebGLState:', e );
  49501. }
  49502. }
  49503. function compressedTexSubImage2D() {
  49504. try {
  49505. gl.compressedTexSubImage2D( ...arguments );
  49506. } catch ( e ) {
  49507. error( 'WebGLState:', e );
  49508. }
  49509. }
  49510. function compressedTexSubImage3D() {
  49511. try {
  49512. gl.compressedTexSubImage3D( ...arguments );
  49513. } catch ( e ) {
  49514. error( 'WebGLState:', e );
  49515. }
  49516. }
  49517. function texStorage2D() {
  49518. try {
  49519. gl.texStorage2D( ...arguments );
  49520. } catch ( e ) {
  49521. error( 'WebGLState:', e );
  49522. }
  49523. }
  49524. function texStorage3D() {
  49525. try {
  49526. gl.texStorage3D( ...arguments );
  49527. } catch ( e ) {
  49528. error( 'WebGLState:', e );
  49529. }
  49530. }
  49531. function texImage2D() {
  49532. try {
  49533. gl.texImage2D( ...arguments );
  49534. } catch ( e ) {
  49535. error( 'WebGLState:', e );
  49536. }
  49537. }
  49538. function texImage3D() {
  49539. try {
  49540. gl.texImage3D( ...arguments );
  49541. } catch ( e ) {
  49542. error( 'WebGLState:', e );
  49543. }
  49544. }
  49545. //
  49546. function scissor( scissor ) {
  49547. if ( currentScissor.equals( scissor ) === false ) {
  49548. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49549. currentScissor.copy( scissor );
  49550. }
  49551. }
  49552. function viewport( viewport ) {
  49553. if ( currentViewport.equals( viewport ) === false ) {
  49554. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49555. currentViewport.copy( viewport );
  49556. }
  49557. }
  49558. function updateUBOMapping( uniformsGroup, program ) {
  49559. let mapping = uboProgramMap.get( program );
  49560. if ( mapping === undefined ) {
  49561. mapping = new WeakMap();
  49562. uboProgramMap.set( program, mapping );
  49563. }
  49564. let blockIndex = mapping.get( uniformsGroup );
  49565. if ( blockIndex === undefined ) {
  49566. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49567. mapping.set( uniformsGroup, blockIndex );
  49568. }
  49569. }
  49570. function uniformBlockBinding( uniformsGroup, program ) {
  49571. const mapping = uboProgramMap.get( program );
  49572. const blockIndex = mapping.get( uniformsGroup );
  49573. if ( uboBindings.get( program ) !== blockIndex ) {
  49574. // bind shader specific block index to global block point
  49575. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49576. uboBindings.set( program, blockIndex );
  49577. }
  49578. }
  49579. //
  49580. function reset() {
  49581. // reset state
  49582. gl.disable( gl.BLEND );
  49583. gl.disable( gl.CULL_FACE );
  49584. gl.disable( gl.DEPTH_TEST );
  49585. gl.disable( gl.POLYGON_OFFSET_FILL );
  49586. gl.disable( gl.SCISSOR_TEST );
  49587. gl.disable( gl.STENCIL_TEST );
  49588. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49589. gl.blendEquation( gl.FUNC_ADD );
  49590. gl.blendFunc( gl.ONE, gl.ZERO );
  49591. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49592. gl.blendColor( 0, 0, 0, 0 );
  49593. gl.colorMask( true, true, true, true );
  49594. gl.clearColor( 0, 0, 0, 0 );
  49595. gl.depthMask( true );
  49596. gl.depthFunc( gl.LESS );
  49597. depthBuffer.setReversed( false );
  49598. gl.clearDepth( 1 );
  49599. gl.stencilMask( 0xffffffff );
  49600. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49601. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49602. gl.clearStencil( 0 );
  49603. gl.cullFace( gl.BACK );
  49604. gl.frontFace( gl.CCW );
  49605. gl.polygonOffset( 0, 0 );
  49606. gl.activeTexture( gl.TEXTURE0 );
  49607. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49608. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49609. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49610. gl.useProgram( null );
  49611. gl.lineWidth( 1 );
  49612. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49613. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49614. // reset internals
  49615. enabledCapabilities = {};
  49616. currentTextureSlot = null;
  49617. currentBoundTextures = {};
  49618. currentBoundFramebuffers = {};
  49619. currentDrawbuffers = new WeakMap();
  49620. defaultDrawbuffers = [];
  49621. currentProgram = null;
  49622. currentBlendingEnabled = false;
  49623. currentBlending = null;
  49624. currentBlendEquation = null;
  49625. currentBlendSrc = null;
  49626. currentBlendDst = null;
  49627. currentBlendEquationAlpha = null;
  49628. currentBlendSrcAlpha = null;
  49629. currentBlendDstAlpha = null;
  49630. currentBlendColor = new Color( 0, 0, 0 );
  49631. currentBlendAlpha = 0;
  49632. currentPremultipledAlpha = false;
  49633. currentFlipSided = null;
  49634. currentCullFace = null;
  49635. currentLineWidth = null;
  49636. currentPolygonOffsetFactor = null;
  49637. currentPolygonOffsetUnits = null;
  49638. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49639. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49640. colorBuffer.reset();
  49641. depthBuffer.reset();
  49642. stencilBuffer.reset();
  49643. }
  49644. return {
  49645. buffers: {
  49646. color: colorBuffer,
  49647. depth: depthBuffer,
  49648. stencil: stencilBuffer
  49649. },
  49650. enable: enable,
  49651. disable: disable,
  49652. bindFramebuffer: bindFramebuffer,
  49653. drawBuffers: drawBuffers,
  49654. useProgram: useProgram,
  49655. setBlending: setBlending,
  49656. setMaterial: setMaterial,
  49657. setFlipSided: setFlipSided,
  49658. setCullFace: setCullFace,
  49659. setLineWidth: setLineWidth,
  49660. setPolygonOffset: setPolygonOffset,
  49661. setScissorTest: setScissorTest,
  49662. activeTexture: activeTexture,
  49663. bindTexture: bindTexture,
  49664. unbindTexture: unbindTexture,
  49665. compressedTexImage2D: compressedTexImage2D,
  49666. compressedTexImage3D: compressedTexImage3D,
  49667. texImage2D: texImage2D,
  49668. texImage3D: texImage3D,
  49669. updateUBOMapping: updateUBOMapping,
  49670. uniformBlockBinding: uniformBlockBinding,
  49671. texStorage2D: texStorage2D,
  49672. texStorage3D: texStorage3D,
  49673. texSubImage2D: texSubImage2D,
  49674. texSubImage3D: texSubImage3D,
  49675. compressedTexSubImage2D: compressedTexSubImage2D,
  49676. compressedTexSubImage3D: compressedTexSubImage3D,
  49677. scissor: scissor,
  49678. viewport: viewport,
  49679. reset: reset
  49680. };
  49681. }
  49682. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49683. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49684. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49685. const _imageDimensions = new Vector2();
  49686. const _videoTextures = new WeakMap();
  49687. let _canvas;
  49688. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49689. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49690. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49691. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49692. let useOffscreenCanvas = false;
  49693. try {
  49694. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49695. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49696. } catch ( err ) {
  49697. // Ignore any errors
  49698. }
  49699. function createCanvas( width, height ) {
  49700. // Use OffscreenCanvas when available. Specially needed in web workers
  49701. return useOffscreenCanvas ?
  49702. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49703. }
  49704. function resizeImage( image, needsNewCanvas, maxSize ) {
  49705. let scale = 1;
  49706. const dimensions = getDimensions( image );
  49707. // handle case if texture exceeds max size
  49708. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49709. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49710. }
  49711. // only perform resize if necessary
  49712. if ( scale < 1 ) {
  49713. // only perform resize for certain image types
  49714. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49715. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49716. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49717. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49718. const width = Math.floor( scale * dimensions.width );
  49719. const height = Math.floor( scale * dimensions.height );
  49720. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49721. // cube textures can't reuse the same canvas
  49722. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49723. canvas.width = width;
  49724. canvas.height = height;
  49725. const context = canvas.getContext( '2d' );
  49726. context.drawImage( image, 0, 0, width, height );
  49727. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49728. return canvas;
  49729. } else {
  49730. if ( 'data' in image ) {
  49731. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49732. }
  49733. return image;
  49734. }
  49735. }
  49736. return image;
  49737. }
  49738. function textureNeedsGenerateMipmaps( texture ) {
  49739. return texture.generateMipmaps;
  49740. }
  49741. function generateMipmap( target ) {
  49742. _gl.generateMipmap( target );
  49743. }
  49744. function getTargetType( texture ) {
  49745. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49746. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49747. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49748. return _gl.TEXTURE_2D;
  49749. }
  49750. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49751. if ( internalFormatName !== null ) {
  49752. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49753. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49754. }
  49755. let internalFormat = glFormat;
  49756. if ( glFormat === _gl.RED ) {
  49757. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49758. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49759. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49760. }
  49761. if ( glFormat === _gl.RED_INTEGER ) {
  49762. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49763. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49764. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49765. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49766. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49767. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49768. }
  49769. if ( glFormat === _gl.RG ) {
  49770. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49771. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49772. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49773. }
  49774. if ( glFormat === _gl.RG_INTEGER ) {
  49775. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49776. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49777. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49778. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49779. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49780. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49781. }
  49782. if ( glFormat === _gl.RGB_INTEGER ) {
  49783. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49784. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49785. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49786. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49787. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49788. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49789. }
  49790. if ( glFormat === _gl.RGBA_INTEGER ) {
  49791. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49792. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49793. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49794. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49795. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49796. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49797. }
  49798. if ( glFormat === _gl.RGB ) {
  49799. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49800. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49801. }
  49802. if ( glFormat === _gl.RGBA ) {
  49803. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49804. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49805. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49806. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49807. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49808. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49809. }
  49810. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49811. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49812. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49813. extensions.get( 'EXT_color_buffer_float' );
  49814. }
  49815. return internalFormat;
  49816. }
  49817. function getInternalDepthFormat( useStencil, depthType ) {
  49818. let glInternalFormat;
  49819. if ( useStencil ) {
  49820. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49821. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49822. } else if ( depthType === FloatType ) {
  49823. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49824. } else if ( depthType === UnsignedShortType ) {
  49825. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49826. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49827. }
  49828. } else {
  49829. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49830. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49831. } else if ( depthType === FloatType ) {
  49832. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49833. } else if ( depthType === UnsignedShortType ) {
  49834. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49835. }
  49836. }
  49837. return glInternalFormat;
  49838. }
  49839. function getMipLevels( texture, image ) {
  49840. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49841. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49842. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49843. // user-defined mipmaps
  49844. return texture.mipmaps.length;
  49845. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49846. return image.mipmaps.length;
  49847. } else {
  49848. // texture without mipmaps (only base level)
  49849. return 1;
  49850. }
  49851. }
  49852. //
  49853. function onTextureDispose( event ) {
  49854. const texture = event.target;
  49855. texture.removeEventListener( 'dispose', onTextureDispose );
  49856. deallocateTexture( texture );
  49857. if ( texture.isVideoTexture ) {
  49858. _videoTextures.delete( texture );
  49859. }
  49860. }
  49861. function onRenderTargetDispose( event ) {
  49862. const renderTarget = event.target;
  49863. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49864. deallocateRenderTarget( renderTarget );
  49865. }
  49866. //
  49867. function deallocateTexture( texture ) {
  49868. const textureProperties = properties.get( texture );
  49869. if ( textureProperties.__webglInit === undefined ) return;
  49870. // check if it's necessary to remove the WebGLTexture object
  49871. const source = texture.source;
  49872. const webglTextures = _sources.get( source );
  49873. if ( webglTextures ) {
  49874. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49875. webglTexture.usedTimes --;
  49876. // the WebGLTexture object is not used anymore, remove it
  49877. if ( webglTexture.usedTimes === 0 ) {
  49878. deleteTexture( texture );
  49879. }
  49880. // remove the weak map entry if no WebGLTexture uses the source anymore
  49881. if ( Object.keys( webglTextures ).length === 0 ) {
  49882. _sources.delete( source );
  49883. }
  49884. }
  49885. properties.remove( texture );
  49886. }
  49887. function deleteTexture( texture ) {
  49888. const textureProperties = properties.get( texture );
  49889. _gl.deleteTexture( textureProperties.__webglTexture );
  49890. const source = texture.source;
  49891. const webglTextures = _sources.get( source );
  49892. delete webglTextures[ textureProperties.__cacheKey ];
  49893. info.memory.textures --;
  49894. }
  49895. function deallocateRenderTarget( renderTarget ) {
  49896. const renderTargetProperties = properties.get( renderTarget );
  49897. if ( renderTarget.depthTexture ) {
  49898. renderTarget.depthTexture.dispose();
  49899. properties.remove( renderTarget.depthTexture );
  49900. }
  49901. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49902. for ( let i = 0; i < 6; i ++ ) {
  49903. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49904. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49905. } else {
  49906. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49907. }
  49908. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49909. }
  49910. } else {
  49911. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49912. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49913. } else {
  49914. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49915. }
  49916. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49917. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49918. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49919. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49920. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49921. }
  49922. }
  49923. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49924. }
  49925. const textures = renderTarget.textures;
  49926. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49927. const attachmentProperties = properties.get( textures[ i ] );
  49928. if ( attachmentProperties.__webglTexture ) {
  49929. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49930. info.memory.textures --;
  49931. }
  49932. properties.remove( textures[ i ] );
  49933. }
  49934. properties.remove( renderTarget );
  49935. }
  49936. //
  49937. let textureUnits = 0;
  49938. function resetTextureUnits() {
  49939. textureUnits = 0;
  49940. }
  49941. function allocateTextureUnit() {
  49942. const textureUnit = textureUnits;
  49943. if ( textureUnit >= capabilities.maxTextures ) {
  49944. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49945. }
  49946. textureUnits += 1;
  49947. return textureUnit;
  49948. }
  49949. function getTextureCacheKey( texture ) {
  49950. const array = [];
  49951. array.push( texture.wrapS );
  49952. array.push( texture.wrapT );
  49953. array.push( texture.wrapR || 0 );
  49954. array.push( texture.magFilter );
  49955. array.push( texture.minFilter );
  49956. array.push( texture.anisotropy );
  49957. array.push( texture.internalFormat );
  49958. array.push( texture.format );
  49959. array.push( texture.type );
  49960. array.push( texture.generateMipmaps );
  49961. array.push( texture.premultiplyAlpha );
  49962. array.push( texture.flipY );
  49963. array.push( texture.unpackAlignment );
  49964. array.push( texture.colorSpace );
  49965. return array.join();
  49966. }
  49967. //
  49968. function setTexture2D( texture, slot ) {
  49969. const textureProperties = properties.get( texture );
  49970. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49971. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49972. const image = texture.image;
  49973. if ( image === null ) {
  49974. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49975. } else if ( image.complete === false ) {
  49976. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49977. } else {
  49978. uploadTexture( textureProperties, texture, slot );
  49979. return;
  49980. }
  49981. } else if ( texture.isExternalTexture ) {
  49982. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49983. }
  49984. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49985. }
  49986. function setTexture2DArray( texture, slot ) {
  49987. const textureProperties = properties.get( texture );
  49988. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49989. uploadTexture( textureProperties, texture, slot );
  49990. return;
  49991. } else if ( texture.isExternalTexture ) {
  49992. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49993. }
  49994. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49995. }
  49996. function setTexture3D( texture, slot ) {
  49997. const textureProperties = properties.get( texture );
  49998. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49999. uploadTexture( textureProperties, texture, slot );
  50000. return;
  50001. }
  50002. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50003. }
  50004. function setTextureCube( texture, slot ) {
  50005. const textureProperties = properties.get( texture );
  50006. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  50007. uploadCubeTexture( textureProperties, texture, slot );
  50008. return;
  50009. }
  50010. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50011. }
  50012. const wrappingToGL = {
  50013. [ RepeatWrapping ]: _gl.REPEAT,
  50014. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  50015. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  50016. };
  50017. const filterToGL = {
  50018. [ NearestFilter ]: _gl.NEAREST,
  50019. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  50020. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  50021. [ LinearFilter ]: _gl.LINEAR,
  50022. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  50023. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  50024. };
  50025. const compareToGL = {
  50026. [ NeverCompare ]: _gl.NEVER,
  50027. [ AlwaysCompare ]: _gl.ALWAYS,
  50028. [ LessCompare ]: _gl.LESS,
  50029. [ LessEqualCompare ]: _gl.LEQUAL,
  50030. [ EqualCompare ]: _gl.EQUAL,
  50031. [ GreaterEqualCompare ]: _gl.GEQUAL,
  50032. [ GreaterCompare ]: _gl.GREATER,
  50033. [ NotEqualCompare ]: _gl.NOTEQUAL
  50034. };
  50035. function setTextureParameters( textureType, texture ) {
  50036. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  50037. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  50038. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  50039. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  50040. }
  50041. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  50042. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  50043. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  50044. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  50045. }
  50046. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  50047. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  50048. if ( texture.compareFunction ) {
  50049. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  50050. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  50051. }
  50052. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  50053. if ( texture.magFilter === NearestFilter ) return;
  50054. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  50055. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  50056. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  50057. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  50058. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  50059. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  50060. }
  50061. }
  50062. }
  50063. function initTexture( textureProperties, texture ) {
  50064. let forceUpload = false;
  50065. if ( textureProperties.__webglInit === undefined ) {
  50066. textureProperties.__webglInit = true;
  50067. texture.addEventListener( 'dispose', onTextureDispose );
  50068. }
  50069. // create Source <-> WebGLTextures mapping if necessary
  50070. const source = texture.source;
  50071. let webglTextures = _sources.get( source );
  50072. if ( webglTextures === undefined ) {
  50073. webglTextures = {};
  50074. _sources.set( source, webglTextures );
  50075. }
  50076. // check if there is already a WebGLTexture object for the given texture parameters
  50077. const textureCacheKey = getTextureCacheKey( texture );
  50078. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  50079. // if not, create a new instance of WebGLTexture
  50080. if ( webglTextures[ textureCacheKey ] === undefined ) {
  50081. // create new entry
  50082. webglTextures[ textureCacheKey ] = {
  50083. texture: _gl.createTexture(),
  50084. usedTimes: 0
  50085. };
  50086. info.memory.textures ++;
  50087. // when a new instance of WebGLTexture was created, a texture upload is required
  50088. // even if the image contents are identical
  50089. forceUpload = true;
  50090. }
  50091. webglTextures[ textureCacheKey ].usedTimes ++;
  50092. // every time the texture cache key changes, it's necessary to check if an instance of
  50093. // WebGLTexture can be deleted in order to avoid a memory leak.
  50094. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  50095. if ( webglTexture !== undefined ) {
  50096. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  50097. if ( webglTexture.usedTimes === 0 ) {
  50098. deleteTexture( texture );
  50099. }
  50100. }
  50101. // store references to cache key and WebGLTexture object
  50102. textureProperties.__cacheKey = textureCacheKey;
  50103. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  50104. }
  50105. return forceUpload;
  50106. }
  50107. function getRow( index, rowLength, componentStride ) {
  50108. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  50109. }
  50110. function updateTexture( texture, image, glFormat, glType ) {
  50111. const componentStride = 4; // only RGBA supported
  50112. const updateRanges = texture.updateRanges;
  50113. if ( updateRanges.length === 0 ) {
  50114. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  50115. } else {
  50116. // Before applying update ranges, we merge any adjacent / overlapping
  50117. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  50118. // to performance improvements for applications which make heavy use of
  50119. // update ranges. Likely due to GPU command overhead.
  50120. //
  50121. // Note that to reduce garbage collection between frames, we merge the
  50122. // update ranges in-place. This is safe because this method will clear the
  50123. // update ranges once updated.
  50124. updateRanges.sort( ( a, b ) => a.start - b.start );
  50125. // To merge the update ranges in-place, we work from left to right in the
  50126. // existing updateRanges array, merging ranges. This may result in a final
  50127. // array which is smaller than the original. This index tracks the last
  50128. // index representing a merged range, any data after this index can be
  50129. // trimmed once the merge algorithm is completed.
  50130. let mergeIndex = 0;
  50131. for ( let i = 1; i < updateRanges.length; i ++ ) {
  50132. const previousRange = updateRanges[ mergeIndex ];
  50133. const range = updateRanges[ i ];
  50134. // Only merge if in the same row and overlapping/adjacent
  50135. const previousEnd = previousRange.start + previousRange.count;
  50136. const currentRow = getRow( range.start, image.width, componentStride );
  50137. const previousRow = getRow( previousRange.start, image.width, componentStride );
  50138. // We add one here to merge adjacent ranges. This is safe because ranges
  50139. // operate over positive integers.
  50140. if (
  50141. range.start <= previousEnd + 1 &&
  50142. currentRow === previousRow &&
  50143. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  50144. ) {
  50145. previousRange.count = Math.max(
  50146. previousRange.count,
  50147. range.start + range.count - previousRange.start
  50148. );
  50149. } else {
  50150. ++ mergeIndex;
  50151. updateRanges[ mergeIndex ] = range;
  50152. }
  50153. }
  50154. // Trim the array to only contain the merged ranges.
  50155. updateRanges.length = mergeIndex + 1;
  50156. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  50157. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  50158. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  50159. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  50160. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50161. const range = updateRanges[ i ];
  50162. const pixelStart = Math.floor( range.start / componentStride );
  50163. const pixelCount = Math.ceil( range.count / componentStride );
  50164. const x = pixelStart % image.width;
  50165. const y = Math.floor( pixelStart / image.width );
  50166. // Assumes update ranges refer to contiguous memory
  50167. const width = pixelCount;
  50168. const height = 1;
  50169. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  50170. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  50171. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  50172. }
  50173. texture.clearUpdateRanges();
  50174. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  50175. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  50176. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  50177. }
  50178. }
  50179. function uploadTexture( textureProperties, texture, slot ) {
  50180. let textureType = _gl.TEXTURE_2D;
  50181. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  50182. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  50183. const forceUpload = initTexture( textureProperties, texture );
  50184. const source = texture.source;
  50185. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50186. const sourceProperties = properties.get( source );
  50187. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50188. state.activeTexture( _gl.TEXTURE0 + slot );
  50189. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50190. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50191. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50192. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50193. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50194. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50195. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50196. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  50197. image = verifyColorSpace( texture, image );
  50198. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50199. const glType = utils.convert( texture.type );
  50200. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  50201. setTextureParameters( textureType, texture );
  50202. let mipmap;
  50203. const mipmaps = texture.mipmaps;
  50204. const useTexStorage = ( texture.isVideoTexture !== true );
  50205. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50206. const dataReady = source.dataReady;
  50207. const levels = getMipLevels( texture, image );
  50208. if ( texture.isDepthTexture ) {
  50209. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  50210. //
  50211. if ( allocateMemory ) {
  50212. if ( useTexStorage ) {
  50213. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  50214. } else {
  50215. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  50216. }
  50217. }
  50218. } else if ( texture.isDataTexture ) {
  50219. // use manually created mipmaps if available
  50220. // if there are no manual mipmaps
  50221. // set 0 level mipmap and then use GL to generate other mipmap levels
  50222. if ( mipmaps.length > 0 ) {
  50223. if ( useTexStorage && allocateMemory ) {
  50224. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50225. }
  50226. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50227. mipmap = mipmaps[ i ];
  50228. if ( useTexStorage ) {
  50229. if ( dataReady ) {
  50230. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50231. }
  50232. } else {
  50233. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50234. }
  50235. }
  50236. texture.generateMipmaps = false;
  50237. } else {
  50238. if ( useTexStorage ) {
  50239. if ( allocateMemory ) {
  50240. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50241. }
  50242. if ( dataReady ) {
  50243. updateTexture( texture, image, glFormat, glType );
  50244. }
  50245. } else {
  50246. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  50247. }
  50248. }
  50249. } else if ( texture.isCompressedTexture ) {
  50250. if ( texture.isCompressedArrayTexture ) {
  50251. if ( useTexStorage && allocateMemory ) {
  50252. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  50253. }
  50254. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50255. mipmap = mipmaps[ i ];
  50256. if ( texture.format !== RGBAFormat ) {
  50257. if ( glFormat !== null ) {
  50258. if ( useTexStorage ) {
  50259. if ( dataReady ) {
  50260. if ( texture.layerUpdates.size > 0 ) {
  50261. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  50262. for ( const layerIndex of texture.layerUpdates ) {
  50263. const layerData = mipmap.data.subarray(
  50264. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  50265. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  50266. );
  50267. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  50268. }
  50269. texture.clearLayerUpdates();
  50270. } else {
  50271. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50272. }
  50273. }
  50274. } else {
  50275. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50276. }
  50277. } else {
  50278. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50279. }
  50280. } else {
  50281. if ( useTexStorage ) {
  50282. if ( dataReady ) {
  50283. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50284. }
  50285. } else {
  50286. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50287. }
  50288. }
  50289. }
  50290. } else {
  50291. if ( useTexStorage && allocateMemory ) {
  50292. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50293. }
  50294. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50295. mipmap = mipmaps[ i ];
  50296. if ( texture.format !== RGBAFormat ) {
  50297. if ( glFormat !== null ) {
  50298. if ( useTexStorage ) {
  50299. if ( dataReady ) {
  50300. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50301. }
  50302. } else {
  50303. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50304. }
  50305. } else {
  50306. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50307. }
  50308. } else {
  50309. if ( useTexStorage ) {
  50310. if ( dataReady ) {
  50311. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50312. }
  50313. } else {
  50314. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50315. }
  50316. }
  50317. }
  50318. }
  50319. } else if ( texture.isDataArrayTexture ) {
  50320. if ( useTexStorage ) {
  50321. if ( allocateMemory ) {
  50322. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50323. }
  50324. if ( dataReady ) {
  50325. if ( texture.layerUpdates.size > 0 ) {
  50326. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50327. for ( const layerIndex of texture.layerUpdates ) {
  50328. const layerData = image.data.subarray(
  50329. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50330. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50331. );
  50332. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50333. }
  50334. texture.clearLayerUpdates();
  50335. } else {
  50336. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50337. }
  50338. }
  50339. } else {
  50340. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50341. }
  50342. } else if ( texture.isData3DTexture ) {
  50343. if ( useTexStorage ) {
  50344. if ( allocateMemory ) {
  50345. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50346. }
  50347. if ( dataReady ) {
  50348. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50349. }
  50350. } else {
  50351. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50352. }
  50353. } else if ( texture.isFramebufferTexture ) {
  50354. if ( allocateMemory ) {
  50355. if ( useTexStorage ) {
  50356. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50357. } else {
  50358. let width = image.width, height = image.height;
  50359. for ( let i = 0; i < levels; i ++ ) {
  50360. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50361. width >>= 1;
  50362. height >>= 1;
  50363. }
  50364. }
  50365. }
  50366. } else {
  50367. // regular Texture (image, video, canvas)
  50368. // use manually created mipmaps if available
  50369. // if there are no manual mipmaps
  50370. // set 0 level mipmap and then use GL to generate other mipmap levels
  50371. if ( mipmaps.length > 0 ) {
  50372. if ( useTexStorage && allocateMemory ) {
  50373. const dimensions = getDimensions( mipmaps[ 0 ] );
  50374. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50375. }
  50376. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50377. mipmap = mipmaps[ i ];
  50378. if ( useTexStorage ) {
  50379. if ( dataReady ) {
  50380. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50381. }
  50382. } else {
  50383. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50384. }
  50385. }
  50386. texture.generateMipmaps = false;
  50387. } else {
  50388. if ( useTexStorage ) {
  50389. if ( allocateMemory ) {
  50390. const dimensions = getDimensions( image );
  50391. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50392. }
  50393. if ( dataReady ) {
  50394. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50395. }
  50396. } else {
  50397. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50398. }
  50399. }
  50400. }
  50401. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50402. generateMipmap( textureType );
  50403. }
  50404. sourceProperties.__version = source.version;
  50405. if ( texture.onUpdate ) texture.onUpdate( texture );
  50406. }
  50407. textureProperties.__version = texture.version;
  50408. }
  50409. function uploadCubeTexture( textureProperties, texture, slot ) {
  50410. if ( texture.image.length !== 6 ) return;
  50411. const forceUpload = initTexture( textureProperties, texture );
  50412. const source = texture.source;
  50413. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50414. const sourceProperties = properties.get( source );
  50415. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50416. state.activeTexture( _gl.TEXTURE0 + slot );
  50417. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50418. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50419. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50420. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50421. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50422. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50423. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50424. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50425. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50426. const cubeImage = [];
  50427. for ( let i = 0; i < 6; i ++ ) {
  50428. if ( ! isCompressed && ! isDataTexture ) {
  50429. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50430. } else {
  50431. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50432. }
  50433. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50434. }
  50435. const image = cubeImage[ 0 ],
  50436. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50437. glType = utils.convert( texture.type ),
  50438. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50439. const useTexStorage = ( texture.isVideoTexture !== true );
  50440. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50441. const dataReady = source.dataReady;
  50442. let levels = getMipLevels( texture, image );
  50443. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50444. let mipmaps;
  50445. if ( isCompressed ) {
  50446. if ( useTexStorage && allocateMemory ) {
  50447. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50448. }
  50449. for ( let i = 0; i < 6; i ++ ) {
  50450. mipmaps = cubeImage[ i ].mipmaps;
  50451. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50452. const mipmap = mipmaps[ j ];
  50453. if ( texture.format !== RGBAFormat ) {
  50454. if ( glFormat !== null ) {
  50455. if ( useTexStorage ) {
  50456. if ( dataReady ) {
  50457. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50458. }
  50459. } else {
  50460. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50461. }
  50462. } else {
  50463. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50464. }
  50465. } else {
  50466. if ( useTexStorage ) {
  50467. if ( dataReady ) {
  50468. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50469. }
  50470. } else {
  50471. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50472. }
  50473. }
  50474. }
  50475. }
  50476. } else {
  50477. mipmaps = texture.mipmaps;
  50478. if ( useTexStorage && allocateMemory ) {
  50479. // TODO: Uniformly handle mipmap definitions
  50480. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50481. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50482. if ( mipmaps.length > 0 ) levels ++;
  50483. const dimensions = getDimensions( cubeImage[ 0 ] );
  50484. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50485. }
  50486. for ( let i = 0; i < 6; i ++ ) {
  50487. if ( isDataTexture ) {
  50488. if ( useTexStorage ) {
  50489. if ( dataReady ) {
  50490. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50491. }
  50492. } else {
  50493. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50494. }
  50495. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50496. const mipmap = mipmaps[ j ];
  50497. const mipmapImage = mipmap.image[ i ].image;
  50498. if ( useTexStorage ) {
  50499. if ( dataReady ) {
  50500. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50501. }
  50502. } else {
  50503. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50504. }
  50505. }
  50506. } else {
  50507. if ( useTexStorage ) {
  50508. if ( dataReady ) {
  50509. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50510. }
  50511. } else {
  50512. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50513. }
  50514. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50515. const mipmap = mipmaps[ j ];
  50516. if ( useTexStorage ) {
  50517. if ( dataReady ) {
  50518. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50519. }
  50520. } else {
  50521. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50522. }
  50523. }
  50524. }
  50525. }
  50526. }
  50527. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50528. // We assume images for cube map have the same size.
  50529. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50530. }
  50531. sourceProperties.__version = source.version;
  50532. if ( texture.onUpdate ) texture.onUpdate( texture );
  50533. }
  50534. textureProperties.__version = texture.version;
  50535. }
  50536. // Render targets
  50537. // Setup storage for target texture and bind it to correct framebuffer
  50538. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50539. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50540. const glType = utils.convert( texture.type );
  50541. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50542. const renderTargetProperties = properties.get( renderTarget );
  50543. const textureProperties = properties.get( texture );
  50544. textureProperties.__renderTarget = renderTarget;
  50545. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50546. const width = Math.max( 1, renderTarget.width >> level );
  50547. const height = Math.max( 1, renderTarget.height >> level );
  50548. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50549. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50550. } else {
  50551. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50552. }
  50553. }
  50554. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50555. if ( useMultisampledRTT( renderTarget ) ) {
  50556. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50557. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50558. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50559. }
  50560. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50561. }
  50562. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50563. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50564. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50565. if ( renderTarget.depthBuffer ) {
  50566. // retrieve the depth attachment types
  50567. const depthTexture = renderTarget.depthTexture;
  50568. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50569. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50570. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50571. // set up the attachment
  50572. if ( useMultisampledRTT( renderTarget ) ) {
  50573. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50574. } else if ( useMultisample ) {
  50575. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50576. } else {
  50577. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50578. }
  50579. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50580. } else {
  50581. const textures = renderTarget.textures;
  50582. for ( let i = 0; i < textures.length; i ++ ) {
  50583. const texture = textures[ i ];
  50584. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50585. const glType = utils.convert( texture.type );
  50586. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50587. if ( useMultisampledRTT( renderTarget ) ) {
  50588. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50589. } else if ( useMultisample ) {
  50590. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50591. } else {
  50592. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50593. }
  50594. }
  50595. }
  50596. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50597. }
  50598. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50599. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50600. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50601. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50602. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50603. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50604. }
  50605. const textureProperties = properties.get( renderTarget.depthTexture );
  50606. textureProperties.__renderTarget = renderTarget;
  50607. // upload an empty depth texture with framebuffer size
  50608. if ( ! textureProperties.__webglTexture ||
  50609. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50610. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50611. renderTarget.depthTexture.image.width = renderTarget.width;
  50612. renderTarget.depthTexture.image.height = renderTarget.height;
  50613. renderTarget.depthTexture.needsUpdate = true;
  50614. }
  50615. if ( isCube ) {
  50616. // For cube depth textures, initialize and bind without uploading image data
  50617. if ( textureProperties.__webglInit === undefined ) {
  50618. textureProperties.__webglInit = true;
  50619. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50620. }
  50621. // Only create and allocate storage once
  50622. if ( textureProperties.__webglTexture === undefined ) {
  50623. textureProperties.__webglTexture = _gl.createTexture();
  50624. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50625. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50626. // Allocate storage for all 6 faces with correct depth texture format
  50627. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50628. const glType = utils.convert( renderTarget.depthTexture.type );
  50629. // Use proper internal format for depth textures
  50630. let glInternalFormat;
  50631. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50632. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50633. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50634. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50635. }
  50636. for ( let i = 0; i < 6; i ++ ) {
  50637. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50638. }
  50639. }
  50640. } else {
  50641. setTexture2D( renderTarget.depthTexture, 0 );
  50642. }
  50643. const webglDepthTexture = textureProperties.__webglTexture;
  50644. const samples = getRenderTargetSamples( renderTarget );
  50645. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50646. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50647. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50648. if ( useMultisampledRTT( renderTarget ) ) {
  50649. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50650. } else {
  50651. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50652. }
  50653. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50654. if ( useMultisampledRTT( renderTarget ) ) {
  50655. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50656. } else {
  50657. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50658. }
  50659. } else {
  50660. throw new Error( 'Unknown depthTexture format' );
  50661. }
  50662. }
  50663. // Setup GL resources for a non-texture depth buffer
  50664. function setupDepthRenderbuffer( renderTarget ) {
  50665. const renderTargetProperties = properties.get( renderTarget );
  50666. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50667. // if the bound depth texture has changed
  50668. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50669. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50670. const depthTexture = renderTarget.depthTexture;
  50671. if ( renderTargetProperties.__depthDisposeCallback ) {
  50672. renderTargetProperties.__depthDisposeCallback();
  50673. }
  50674. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50675. if ( depthTexture ) {
  50676. const disposeEvent = () => {
  50677. delete renderTargetProperties.__boundDepthTexture;
  50678. delete renderTargetProperties.__depthDisposeCallback;
  50679. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50680. };
  50681. depthTexture.addEventListener( 'dispose', disposeEvent );
  50682. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50683. }
  50684. renderTargetProperties.__boundDepthTexture = depthTexture;
  50685. }
  50686. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50687. if ( isCube ) {
  50688. // For cube render targets with depth texture, setup each face
  50689. for ( let i = 0; i < 6; i ++ ) {
  50690. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50691. }
  50692. } else {
  50693. const mipmaps = renderTarget.texture.mipmaps;
  50694. if ( mipmaps && mipmaps.length > 0 ) {
  50695. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50696. } else {
  50697. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50698. }
  50699. }
  50700. } else {
  50701. if ( isCube ) {
  50702. renderTargetProperties.__webglDepthbuffer = [];
  50703. for ( let i = 0; i < 6; i ++ ) {
  50704. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50705. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50706. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50707. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50708. } else {
  50709. // attach buffer if it's been created already
  50710. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50711. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50712. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50713. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50714. }
  50715. }
  50716. } else {
  50717. const mipmaps = renderTarget.texture.mipmaps;
  50718. if ( mipmaps && mipmaps.length > 0 ) {
  50719. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50720. } else {
  50721. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50722. }
  50723. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50724. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50725. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50726. } else {
  50727. // attach buffer if it's been created already
  50728. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50729. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50730. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50731. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50732. }
  50733. }
  50734. }
  50735. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50736. }
  50737. // rebind framebuffer with external textures
  50738. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50739. const renderTargetProperties = properties.get( renderTarget );
  50740. if ( colorTexture !== undefined ) {
  50741. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50742. }
  50743. if ( depthTexture !== undefined ) {
  50744. setupDepthRenderbuffer( renderTarget );
  50745. }
  50746. }
  50747. // Set up GL resources for the render target
  50748. function setupRenderTarget( renderTarget ) {
  50749. const texture = renderTarget.texture;
  50750. const renderTargetProperties = properties.get( renderTarget );
  50751. const textureProperties = properties.get( texture );
  50752. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50753. const textures = renderTarget.textures;
  50754. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50755. const isMultipleRenderTargets = ( textures.length > 1 );
  50756. if ( ! isMultipleRenderTargets ) {
  50757. if ( textureProperties.__webglTexture === undefined ) {
  50758. textureProperties.__webglTexture = _gl.createTexture();
  50759. }
  50760. textureProperties.__version = texture.version;
  50761. info.memory.textures ++;
  50762. }
  50763. // Setup framebuffer
  50764. if ( isCube ) {
  50765. renderTargetProperties.__webglFramebuffer = [];
  50766. for ( let i = 0; i < 6; i ++ ) {
  50767. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50768. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50769. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50770. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50771. }
  50772. } else {
  50773. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50774. }
  50775. }
  50776. } else {
  50777. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50778. renderTargetProperties.__webglFramebuffer = [];
  50779. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50780. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50781. }
  50782. } else {
  50783. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50784. }
  50785. if ( isMultipleRenderTargets ) {
  50786. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50787. const attachmentProperties = properties.get( textures[ i ] );
  50788. if ( attachmentProperties.__webglTexture === undefined ) {
  50789. attachmentProperties.__webglTexture = _gl.createTexture();
  50790. info.memory.textures ++;
  50791. }
  50792. }
  50793. }
  50794. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50795. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50796. renderTargetProperties.__webglColorRenderbuffer = [];
  50797. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50798. for ( let i = 0; i < textures.length; i ++ ) {
  50799. const texture = textures[ i ];
  50800. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50801. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50802. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50803. const glType = utils.convert( texture.type );
  50804. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50805. const samples = getRenderTargetSamples( renderTarget );
  50806. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50807. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50808. }
  50809. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50810. if ( renderTarget.depthBuffer ) {
  50811. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50812. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50813. }
  50814. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50815. }
  50816. }
  50817. // Setup color buffer
  50818. if ( isCube ) {
  50819. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50820. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50821. for ( let i = 0; i < 6; i ++ ) {
  50822. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50823. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50824. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50825. }
  50826. } else {
  50827. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50828. }
  50829. }
  50830. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50831. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50832. }
  50833. state.unbindTexture();
  50834. } else if ( isMultipleRenderTargets ) {
  50835. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50836. const attachment = textures[ i ];
  50837. const attachmentProperties = properties.get( attachment );
  50838. let glTextureType = _gl.TEXTURE_2D;
  50839. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50840. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50841. }
  50842. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  50843. setTextureParameters( glTextureType, attachment );
  50844. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  50845. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  50846. generateMipmap( glTextureType );
  50847. }
  50848. }
  50849. state.unbindTexture();
  50850. } else {
  50851. let glTextureType = _gl.TEXTURE_2D;
  50852. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50853. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50854. }
  50855. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  50856. setTextureParameters( glTextureType, texture );
  50857. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50858. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50859. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50860. }
  50861. } else {
  50862. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50863. }
  50864. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50865. generateMipmap( glTextureType );
  50866. }
  50867. state.unbindTexture();
  50868. }
  50869. // Setup depth and stencil buffers
  50870. if ( renderTarget.depthBuffer ) {
  50871. setupDepthRenderbuffer( renderTarget );
  50872. }
  50873. }
  50874. function updateRenderTargetMipmap( renderTarget ) {
  50875. const textures = renderTarget.textures;
  50876. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50877. const texture = textures[ i ];
  50878. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50879. const targetType = getTargetType( renderTarget );
  50880. const webglTexture = properties.get( texture ).__webglTexture;
  50881. state.bindTexture( targetType, webglTexture );
  50882. generateMipmap( targetType );
  50883. state.unbindTexture();
  50884. }
  50885. }
  50886. }
  50887. const invalidationArrayRead = [];
  50888. const invalidationArrayDraw = [];
  50889. function updateMultisampleRenderTarget( renderTarget ) {
  50890. if ( renderTarget.samples > 0 ) {
  50891. if ( useMultisampledRTT( renderTarget ) === false ) {
  50892. const textures = renderTarget.textures;
  50893. const width = renderTarget.width;
  50894. const height = renderTarget.height;
  50895. let mask = _gl.COLOR_BUFFER_BIT;
  50896. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50897. const renderTargetProperties = properties.get( renderTarget );
  50898. const isMultipleRenderTargets = ( textures.length > 1 );
  50899. // If MRT we need to remove FBO attachments
  50900. if ( isMultipleRenderTargets ) {
  50901. for ( let i = 0; i < textures.length; i ++ ) {
  50902. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50903. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50904. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50905. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50906. }
  50907. }
  50908. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50909. const mipmaps = renderTarget.texture.mipmaps;
  50910. if ( mipmaps && mipmaps.length > 0 ) {
  50911. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50912. } else {
  50913. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50914. }
  50915. for ( let i = 0; i < textures.length; i ++ ) {
  50916. if ( renderTarget.resolveDepthBuffer ) {
  50917. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50918. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50919. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50920. }
  50921. if ( isMultipleRenderTargets ) {
  50922. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50923. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50924. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50925. }
  50926. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50927. if ( supportsInvalidateFramebuffer === true ) {
  50928. invalidationArrayRead.length = 0;
  50929. invalidationArrayDraw.length = 0;
  50930. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50931. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50932. invalidationArrayRead.push( depthStyle );
  50933. invalidationArrayDraw.push( depthStyle );
  50934. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50935. }
  50936. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50937. }
  50938. }
  50939. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50940. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50941. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50942. if ( isMultipleRenderTargets ) {
  50943. for ( let i = 0; i < textures.length; i ++ ) {
  50944. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50945. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50946. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50947. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50948. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50949. }
  50950. }
  50951. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50952. } else {
  50953. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50954. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50955. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50956. }
  50957. }
  50958. }
  50959. }
  50960. function getRenderTargetSamples( renderTarget ) {
  50961. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50962. }
  50963. function useMultisampledRTT( renderTarget ) {
  50964. const renderTargetProperties = properties.get( renderTarget );
  50965. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50966. }
  50967. function updateVideoTexture( texture ) {
  50968. const frame = info.render.frame;
  50969. // Check the last frame we updated the VideoTexture
  50970. if ( _videoTextures.get( texture ) !== frame ) {
  50971. _videoTextures.set( texture, frame );
  50972. texture.update();
  50973. }
  50974. }
  50975. function verifyColorSpace( texture, image ) {
  50976. const colorSpace = texture.colorSpace;
  50977. const format = texture.format;
  50978. const type = texture.type;
  50979. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50980. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50981. // sRGB
  50982. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50983. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50984. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50985. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50986. }
  50987. } else {
  50988. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50989. }
  50990. }
  50991. return image;
  50992. }
  50993. function getDimensions( image ) {
  50994. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50995. // if intrinsic data are not available, fallback to width/height
  50996. _imageDimensions.width = image.naturalWidth || image.width;
  50997. _imageDimensions.height = image.naturalHeight || image.height;
  50998. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50999. _imageDimensions.width = image.displayWidth;
  51000. _imageDimensions.height = image.displayHeight;
  51001. } else {
  51002. _imageDimensions.width = image.width;
  51003. _imageDimensions.height = image.height;
  51004. }
  51005. return _imageDimensions;
  51006. }
  51007. //
  51008. this.allocateTextureUnit = allocateTextureUnit;
  51009. this.resetTextureUnits = resetTextureUnits;
  51010. this.setTexture2D = setTexture2D;
  51011. this.setTexture2DArray = setTexture2DArray;
  51012. this.setTexture3D = setTexture3D;
  51013. this.setTextureCube = setTextureCube;
  51014. this.rebindTextures = rebindTextures;
  51015. this.setupRenderTarget = setupRenderTarget;
  51016. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  51017. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  51018. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  51019. this.setupFrameBufferTexture = setupFrameBufferTexture;
  51020. this.useMultisampledRTT = useMultisampledRTT;
  51021. this.isReversedDepthBuffer = function () {
  51022. return state.buffers.depth.getReversed();
  51023. };
  51024. }
  51025. function WebGLUtils( gl, extensions ) {
  51026. function convert( p, colorSpace = NoColorSpace ) {
  51027. let extension;
  51028. const transfer = ColorManagement.getTransfer( colorSpace );
  51029. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  51030. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  51031. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  51032. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  51033. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  51034. if ( p === ByteType ) return gl.BYTE;
  51035. if ( p === ShortType ) return gl.SHORT;
  51036. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  51037. if ( p === IntType ) return gl.INT;
  51038. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  51039. if ( p === FloatType ) return gl.FLOAT;
  51040. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  51041. if ( p === AlphaFormat ) return gl.ALPHA;
  51042. if ( p === RGBFormat ) return gl.RGB;
  51043. if ( p === RGBAFormat ) return gl.RGBA;
  51044. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  51045. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  51046. // WebGL2 formats.
  51047. if ( p === RedFormat ) return gl.RED;
  51048. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  51049. if ( p === RGFormat ) return gl.RG;
  51050. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  51051. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  51052. // S3TC
  51053. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  51054. if ( transfer === SRGBTransfer ) {
  51055. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  51056. if ( extension !== null ) {
  51057. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  51058. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  51059. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  51060. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  51061. } else {
  51062. return null;
  51063. }
  51064. } else {
  51065. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  51066. if ( extension !== null ) {
  51067. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  51068. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  51069. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  51070. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  51071. } else {
  51072. return null;
  51073. }
  51074. }
  51075. }
  51076. // PVRTC
  51077. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  51078. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  51079. if ( extension !== null ) {
  51080. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  51081. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  51082. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  51083. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  51084. } else {
  51085. return null;
  51086. }
  51087. }
  51088. // ETC
  51089. 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 ) {
  51090. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  51091. if ( extension !== null ) {
  51092. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  51093. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  51094. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  51095. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  51096. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  51097. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  51098. } else {
  51099. return null;
  51100. }
  51101. }
  51102. // ASTC
  51103. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  51104. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  51105. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  51106. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  51107. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  51108. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  51109. if ( extension !== null ) {
  51110. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  51111. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  51112. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  51113. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  51114. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  51115. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  51116. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  51117. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  51118. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  51119. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  51120. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  51121. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  51122. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  51123. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  51124. } else {
  51125. return null;
  51126. }
  51127. }
  51128. // BPTC
  51129. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  51130. extension = extensions.get( 'EXT_texture_compression_bptc' );
  51131. if ( extension !== null ) {
  51132. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  51133. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  51134. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  51135. } else {
  51136. return null;
  51137. }
  51138. }
  51139. // RGTC
  51140. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  51141. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  51142. if ( extension !== null ) {
  51143. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  51144. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  51145. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  51146. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  51147. } else {
  51148. return null;
  51149. }
  51150. }
  51151. //
  51152. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  51153. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  51154. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  51155. }
  51156. return { convert: convert };
  51157. }
  51158. const _occlusion_vertex = `
  51159. void main() {
  51160. gl_Position = vec4( position, 1.0 );
  51161. }`;
  51162. const _occlusion_fragment = `
  51163. uniform sampler2DArray depthColor;
  51164. uniform float depthWidth;
  51165. uniform float depthHeight;
  51166. void main() {
  51167. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  51168. if ( coord.x >= 1.0 ) {
  51169. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  51170. } else {
  51171. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  51172. }
  51173. }`;
  51174. /**
  51175. * A XR module that manages the access to the Depth Sensing API.
  51176. */
  51177. class WebXRDepthSensing {
  51178. /**
  51179. * Constructs a new depth sensing module.
  51180. */
  51181. constructor() {
  51182. /**
  51183. * An opaque texture representing the depth of the user's environment.
  51184. *
  51185. * @type {?ExternalTexture}
  51186. */
  51187. this.texture = null;
  51188. /**
  51189. * A plane mesh for visualizing the depth texture.
  51190. *
  51191. * @type {?Mesh}
  51192. */
  51193. this.mesh = null;
  51194. /**
  51195. * The depth near value.
  51196. *
  51197. * @type {number}
  51198. */
  51199. this.depthNear = 0;
  51200. /**
  51201. * The depth near far.
  51202. *
  51203. * @type {number}
  51204. */
  51205. this.depthFar = 0;
  51206. }
  51207. /**
  51208. * Inits the depth sensing module
  51209. *
  51210. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  51211. * @param {XRRenderState} renderState - The XR render state.
  51212. */
  51213. init( depthData, renderState ) {
  51214. if ( this.texture === null ) {
  51215. const texture = new ExternalTexture( depthData.texture );
  51216. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  51217. this.depthNear = depthData.depthNear;
  51218. this.depthFar = depthData.depthFar;
  51219. }
  51220. this.texture = texture;
  51221. }
  51222. }
  51223. /**
  51224. * Returns a plane mesh that visualizes the depth texture.
  51225. *
  51226. * @param {ArrayCamera} cameraXR - The XR camera.
  51227. * @return {?Mesh} The plane mesh.
  51228. */
  51229. getMesh( cameraXR ) {
  51230. if ( this.texture !== null ) {
  51231. if ( this.mesh === null ) {
  51232. const viewport = cameraXR.cameras[ 0 ].viewport;
  51233. const material = new ShaderMaterial( {
  51234. vertexShader: _occlusion_vertex,
  51235. fragmentShader: _occlusion_fragment,
  51236. uniforms: {
  51237. depthColor: { value: this.texture },
  51238. depthWidth: { value: viewport.z },
  51239. depthHeight: { value: viewport.w }
  51240. }
  51241. } );
  51242. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  51243. }
  51244. }
  51245. return this.mesh;
  51246. }
  51247. /**
  51248. * Resets the module
  51249. */
  51250. reset() {
  51251. this.texture = null;
  51252. this.mesh = null;
  51253. }
  51254. /**
  51255. * Returns a texture representing the depth of the user's environment.
  51256. *
  51257. * @return {?ExternalTexture} The depth texture.
  51258. */
  51259. getDepthTexture() {
  51260. return this.texture;
  51261. }
  51262. }
  51263. /**
  51264. * This class represents an abstraction of the WebXR Device API and is
  51265. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  51266. * interface that allows users to enable/disable XR and perform XR related
  51267. * tasks like for instance retrieving controllers.
  51268. *
  51269. * @augments EventDispatcher
  51270. * @hideconstructor
  51271. */
  51272. class WebXRManager extends EventDispatcher {
  51273. /**
  51274. * Constructs a new WebGL renderer.
  51275. *
  51276. * @param {WebGLRenderer} renderer - The renderer.
  51277. * @param {WebGL2RenderingContext} gl - The rendering context.
  51278. */
  51279. constructor( renderer, gl ) {
  51280. super();
  51281. const scope = this;
  51282. let session = null;
  51283. let framebufferScaleFactor = 1.0;
  51284. let referenceSpace = null;
  51285. let referenceSpaceType = 'local-floor';
  51286. // Set default foveation to maximum.
  51287. let foveation = 1.0;
  51288. let customReferenceSpace = null;
  51289. let pose = null;
  51290. let glBinding = null;
  51291. let glProjLayer = null;
  51292. let glBaseLayer = null;
  51293. let xrFrame = null;
  51294. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51295. const depthSensing = new WebXRDepthSensing();
  51296. const cameraAccessTextures = {};
  51297. const attributes = gl.getContextAttributes();
  51298. let initialRenderTarget = null;
  51299. let newRenderTarget = null;
  51300. const controllers = [];
  51301. const controllerInputSources = [];
  51302. const currentSize = new Vector2();
  51303. let currentPixelRatio = null;
  51304. //
  51305. const cameraL = new PerspectiveCamera();
  51306. cameraL.viewport = new Vector4();
  51307. const cameraR = new PerspectiveCamera();
  51308. cameraR.viewport = new Vector4();
  51309. const cameras = [ cameraL, cameraR ];
  51310. const cameraXR = new ArrayCamera();
  51311. let _currentDepthNear = null;
  51312. let _currentDepthFar = null;
  51313. //
  51314. /**
  51315. * Whether the manager's XR camera should be automatically updated or not.
  51316. *
  51317. * @type {boolean}
  51318. * @default true
  51319. */
  51320. this.cameraAutoUpdate = true;
  51321. /**
  51322. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51323. * if you are going to use XR in your app.
  51324. *
  51325. * @type {boolean}
  51326. * @default false
  51327. */
  51328. this.enabled = false;
  51329. /**
  51330. * Whether XR presentation is active or not.
  51331. *
  51332. * @type {boolean}
  51333. * @readonly
  51334. * @default false
  51335. */
  51336. this.isPresenting = false;
  51337. /**
  51338. * Returns a group representing the `target ray` space of the XR controller.
  51339. * Use this space for visualizing 3D objects that support the user in pointing
  51340. * tasks like UI interaction.
  51341. *
  51342. * @param {number} index - The index of the controller.
  51343. * @return {Group} A group representing the `target ray` space.
  51344. */
  51345. this.getController = function ( index ) {
  51346. let controller = controllers[ index ];
  51347. if ( controller === undefined ) {
  51348. controller = new WebXRController();
  51349. controllers[ index ] = controller;
  51350. }
  51351. return controller.getTargetRaySpace();
  51352. };
  51353. /**
  51354. * Returns a group representing the `grip` space of the XR controller.
  51355. * Use this space for visualizing 3D objects that support the user in pointing
  51356. * tasks like UI interaction.
  51357. *
  51358. * Note: If you want to show something in the user's hand AND offer a
  51359. * pointing ray at the same time, you'll want to attached the handheld object
  51360. * to the group returned by `getControllerGrip()` and the ray to the
  51361. * group returned by `getController()`. The idea is to have two
  51362. * different groups in two different coordinate spaces for the same WebXR
  51363. * controller.
  51364. *
  51365. * @param {number} index - The index of the controller.
  51366. * @return {Group} A group representing the `grip` space.
  51367. */
  51368. this.getControllerGrip = function ( index ) {
  51369. let controller = controllers[ index ];
  51370. if ( controller === undefined ) {
  51371. controller = new WebXRController();
  51372. controllers[ index ] = controller;
  51373. }
  51374. return controller.getGripSpace();
  51375. };
  51376. /**
  51377. * Returns a group representing the `hand` space of the XR controller.
  51378. * Use this space for visualizing 3D objects that support the user in pointing
  51379. * tasks like UI interaction.
  51380. *
  51381. * @param {number} index - The index of the controller.
  51382. * @return {Group} A group representing the `hand` space.
  51383. */
  51384. this.getHand = function ( index ) {
  51385. let controller = controllers[ index ];
  51386. if ( controller === undefined ) {
  51387. controller = new WebXRController();
  51388. controllers[ index ] = controller;
  51389. }
  51390. return controller.getHandSpace();
  51391. };
  51392. //
  51393. function onSessionEvent( event ) {
  51394. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51395. if ( controllerIndex === -1 ) {
  51396. return;
  51397. }
  51398. const controller = controllers[ controllerIndex ];
  51399. if ( controller !== undefined ) {
  51400. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51401. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51402. }
  51403. }
  51404. function onSessionEnd() {
  51405. session.removeEventListener( 'select', onSessionEvent );
  51406. session.removeEventListener( 'selectstart', onSessionEvent );
  51407. session.removeEventListener( 'selectend', onSessionEvent );
  51408. session.removeEventListener( 'squeeze', onSessionEvent );
  51409. session.removeEventListener( 'squeezestart', onSessionEvent );
  51410. session.removeEventListener( 'squeezeend', onSessionEvent );
  51411. session.removeEventListener( 'end', onSessionEnd );
  51412. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51413. for ( let i = 0; i < controllers.length; i ++ ) {
  51414. const inputSource = controllerInputSources[ i ];
  51415. if ( inputSource === null ) continue;
  51416. controllerInputSources[ i ] = null;
  51417. controllers[ i ].disconnect( inputSource );
  51418. }
  51419. _currentDepthNear = null;
  51420. _currentDepthFar = null;
  51421. depthSensing.reset();
  51422. for ( const key in cameraAccessTextures ) {
  51423. delete cameraAccessTextures[ key ];
  51424. }
  51425. // restore framebuffer/rendering state
  51426. renderer.setRenderTarget( initialRenderTarget );
  51427. glBaseLayer = null;
  51428. glProjLayer = null;
  51429. glBinding = null;
  51430. session = null;
  51431. newRenderTarget = null;
  51432. //
  51433. animation.stop();
  51434. scope.isPresenting = false;
  51435. renderer.setPixelRatio( currentPixelRatio );
  51436. renderer.setSize( currentSize.width, currentSize.height, false );
  51437. scope.dispatchEvent( { type: 'sessionend' } );
  51438. }
  51439. /**
  51440. * Sets the framebuffer scale factor.
  51441. *
  51442. * This method can not be used during a XR session.
  51443. *
  51444. * @param {number} value - The framebuffer scale factor.
  51445. */
  51446. this.setFramebufferScaleFactor = function ( value ) {
  51447. framebufferScaleFactor = value;
  51448. if ( scope.isPresenting === true ) {
  51449. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51450. }
  51451. };
  51452. /**
  51453. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51454. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51455. * improve tracking. Default is `local-floor`. Valid values can be found here
  51456. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51457. *
  51458. * This method can not be used during a XR session.
  51459. *
  51460. * @param {string} value - The reference space type.
  51461. */
  51462. this.setReferenceSpaceType = function ( value ) {
  51463. referenceSpaceType = value;
  51464. if ( scope.isPresenting === true ) {
  51465. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51466. }
  51467. };
  51468. /**
  51469. * Returns the XR reference space.
  51470. *
  51471. * @return {XRReferenceSpace} The XR reference space.
  51472. */
  51473. this.getReferenceSpace = function () {
  51474. return customReferenceSpace || referenceSpace;
  51475. };
  51476. /**
  51477. * Sets a custom XR reference space.
  51478. *
  51479. * @param {XRReferenceSpace} space - The XR reference space.
  51480. */
  51481. this.setReferenceSpace = function ( space ) {
  51482. customReferenceSpace = space;
  51483. };
  51484. /**
  51485. * Returns the current base layer.
  51486. *
  51487. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51488. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51489. *
  51490. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51491. */
  51492. this.getBaseLayer = function () {
  51493. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51494. };
  51495. /**
  51496. * Returns the current XR binding.
  51497. *
  51498. * Creates a new binding if needed and the browser is
  51499. * capable of doing so.
  51500. *
  51501. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51502. */
  51503. this.getBinding = function () {
  51504. if ( glBinding === null && supportsGlBinding ) {
  51505. glBinding = new XRWebGLBinding( session, gl );
  51506. }
  51507. return glBinding;
  51508. };
  51509. /**
  51510. * Returns the current XR frame.
  51511. *
  51512. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51513. */
  51514. this.getFrame = function () {
  51515. return xrFrame;
  51516. };
  51517. /**
  51518. * Returns the current XR session.
  51519. *
  51520. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51521. */
  51522. this.getSession = function () {
  51523. return session;
  51524. };
  51525. /**
  51526. * After a XR session has been requested usually with one of the `*Button` modules, it
  51527. * is injected into the renderer with this method. This method triggers the start of
  51528. * the actual XR rendering.
  51529. *
  51530. * @async
  51531. * @param {XRSession} value - The XR session to set.
  51532. * @return {Promise} A Promise that resolves when the session has been set.
  51533. */
  51534. this.setSession = async function ( value ) {
  51535. session = value;
  51536. if ( session !== null ) {
  51537. initialRenderTarget = renderer.getRenderTarget();
  51538. session.addEventListener( 'select', onSessionEvent );
  51539. session.addEventListener( 'selectstart', onSessionEvent );
  51540. session.addEventListener( 'selectend', onSessionEvent );
  51541. session.addEventListener( 'squeeze', onSessionEvent );
  51542. session.addEventListener( 'squeezestart', onSessionEvent );
  51543. session.addEventListener( 'squeezeend', onSessionEvent );
  51544. session.addEventListener( 'end', onSessionEnd );
  51545. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51546. if ( attributes.xrCompatible !== true ) {
  51547. await gl.makeXRCompatible();
  51548. }
  51549. currentPixelRatio = renderer.getPixelRatio();
  51550. renderer.getSize( currentSize );
  51551. // Check that the browser implements the necessary APIs to use an
  51552. // XRProjectionLayer rather than an XRWebGLLayer
  51553. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51554. if ( ! supportsLayers ) {
  51555. const layerInit = {
  51556. antialias: attributes.antialias,
  51557. alpha: true,
  51558. depth: attributes.depth,
  51559. stencil: attributes.stencil,
  51560. framebufferScaleFactor: framebufferScaleFactor
  51561. };
  51562. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51563. session.updateRenderState( { baseLayer: glBaseLayer } );
  51564. renderer.setPixelRatio( 1 );
  51565. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51566. newRenderTarget = new WebGLRenderTarget(
  51567. glBaseLayer.framebufferWidth,
  51568. glBaseLayer.framebufferHeight,
  51569. {
  51570. format: RGBAFormat,
  51571. type: UnsignedByteType,
  51572. colorSpace: renderer.outputColorSpace,
  51573. stencilBuffer: attributes.stencil,
  51574. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51575. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51576. }
  51577. );
  51578. } else {
  51579. let depthFormat = null;
  51580. let depthType = null;
  51581. let glDepthFormat = null;
  51582. if ( attributes.depth ) {
  51583. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51584. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51585. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51586. }
  51587. const projectionlayerInit = {
  51588. colorFormat: gl.RGBA8,
  51589. depthFormat: glDepthFormat,
  51590. scaleFactor: framebufferScaleFactor
  51591. };
  51592. glBinding = this.getBinding();
  51593. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51594. session.updateRenderState( { layers: [ glProjLayer ] } );
  51595. renderer.setPixelRatio( 1 );
  51596. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51597. newRenderTarget = new WebGLRenderTarget(
  51598. glProjLayer.textureWidth,
  51599. glProjLayer.textureHeight,
  51600. {
  51601. format: RGBAFormat,
  51602. type: UnsignedByteType,
  51603. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51604. stencilBuffer: attributes.stencil,
  51605. colorSpace: renderer.outputColorSpace,
  51606. samples: attributes.antialias ? 4 : 0,
  51607. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51608. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51609. } );
  51610. }
  51611. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51612. this.setFoveation( foveation );
  51613. customReferenceSpace = null;
  51614. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51615. animation.setContext( session );
  51616. animation.start();
  51617. scope.isPresenting = true;
  51618. scope.dispatchEvent( { type: 'sessionstart' } );
  51619. }
  51620. };
  51621. /**
  51622. * Returns the environment blend mode from the current XR session.
  51623. *
  51624. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51625. */
  51626. this.getEnvironmentBlendMode = function () {
  51627. if ( session !== null ) {
  51628. return session.environmentBlendMode;
  51629. }
  51630. };
  51631. /**
  51632. * Returns the current depth texture computed via depth sensing.
  51633. *
  51634. * See {@link WebXRDepthSensing#getDepthTexture}.
  51635. *
  51636. * @return {?Texture} The depth texture.
  51637. */
  51638. this.getDepthTexture = function () {
  51639. return depthSensing.getDepthTexture();
  51640. };
  51641. function onInputSourcesChange( event ) {
  51642. // Notify disconnected
  51643. for ( let i = 0; i < event.removed.length; i ++ ) {
  51644. const inputSource = event.removed[ i ];
  51645. const index = controllerInputSources.indexOf( inputSource );
  51646. if ( index >= 0 ) {
  51647. controllerInputSources[ index ] = null;
  51648. controllers[ index ].disconnect( inputSource );
  51649. }
  51650. }
  51651. // Notify connected
  51652. for ( let i = 0; i < event.added.length; i ++ ) {
  51653. const inputSource = event.added[ i ];
  51654. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51655. if ( controllerIndex === -1 ) {
  51656. // Assign input source a controller that currently has no input source
  51657. for ( let i = 0; i < controllers.length; i ++ ) {
  51658. if ( i >= controllerInputSources.length ) {
  51659. controllerInputSources.push( inputSource );
  51660. controllerIndex = i;
  51661. break;
  51662. } else if ( controllerInputSources[ i ] === null ) {
  51663. controllerInputSources[ i ] = inputSource;
  51664. controllerIndex = i;
  51665. break;
  51666. }
  51667. }
  51668. // If all controllers do currently receive input we ignore new ones
  51669. if ( controllerIndex === -1 ) break;
  51670. }
  51671. const controller = controllers[ controllerIndex ];
  51672. if ( controller ) {
  51673. controller.connect( inputSource );
  51674. }
  51675. }
  51676. }
  51677. //
  51678. const cameraLPos = new Vector3();
  51679. const cameraRPos = new Vector3();
  51680. /**
  51681. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51682. * the cameras' projection and world matrices have already been set.
  51683. * And that near and far planes are identical for both cameras.
  51684. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51685. *
  51686. * @param {ArrayCamera} camera - The camera to update.
  51687. * @param {PerspectiveCamera} cameraL - The left camera.
  51688. * @param {PerspectiveCamera} cameraR - The right camera.
  51689. */
  51690. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51691. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51692. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51693. const ipd = cameraLPos.distanceTo( cameraRPos );
  51694. const projL = cameraL.projectionMatrix.elements;
  51695. const projR = cameraR.projectionMatrix.elements;
  51696. // VR systems will have identical far and near planes, and
  51697. // most likely identical top and bottom frustum extents.
  51698. // Use the left camera for these values.
  51699. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51700. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51701. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51702. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51703. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51704. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51705. const left = near * leftFov;
  51706. const right = near * rightFov;
  51707. // Calculate the new camera's position offset from the
  51708. // left camera. xOffset should be roughly half `ipd`.
  51709. const zOffset = ipd / ( - leftFov + rightFov );
  51710. const xOffset = zOffset * - leftFov;
  51711. // TODO: Better way to apply this offset?
  51712. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51713. camera.translateX( xOffset );
  51714. camera.translateZ( zOffset );
  51715. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51716. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51717. // Check if the projection uses an infinite far plane.
  51718. if ( projL[ 10 ] === -1 ) {
  51719. // Use the projection matrix from the left eye.
  51720. // The camera offset is sufficient to include the view volumes
  51721. // of both eyes (assuming symmetric projections).
  51722. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51723. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51724. } else {
  51725. // Find the union of the frustum values of the cameras and scale
  51726. // the values so that the near plane's position does not change in world space,
  51727. // although must now be relative to the new union camera.
  51728. const near2 = near + zOffset;
  51729. const far2 = far + zOffset;
  51730. const left2 = left - xOffset;
  51731. const right2 = right + ( ipd - xOffset );
  51732. const top2 = topFov * far / far2 * near2;
  51733. const bottom2 = bottomFov * far / far2 * near2;
  51734. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51735. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51736. }
  51737. }
  51738. function updateCamera( camera, parent ) {
  51739. if ( parent === null ) {
  51740. camera.matrixWorld.copy( camera.matrix );
  51741. } else {
  51742. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51743. }
  51744. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51745. }
  51746. /**
  51747. * Updates the state of the XR camera. Use this method on app level if you
  51748. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51749. * camera of the scene as a parameter. The passed in camera's transformation
  51750. * is automatically adjusted to the position of the XR camera when calling
  51751. * this method.
  51752. *
  51753. * @param {Camera} camera - The camera.
  51754. */
  51755. this.updateCamera = function ( camera ) {
  51756. if ( session === null ) return;
  51757. let depthNear = camera.near;
  51758. let depthFar = camera.far;
  51759. if ( depthSensing.texture !== null ) {
  51760. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51761. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51762. }
  51763. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51764. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51765. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51766. // Note that the new renderState won't apply until the next frame. See #18320
  51767. session.updateRenderState( {
  51768. depthNear: cameraXR.near,
  51769. depthFar: cameraXR.far
  51770. } );
  51771. _currentDepthNear = cameraXR.near;
  51772. _currentDepthFar = cameraXR.far;
  51773. }
  51774. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51775. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51776. cameraL.layers.mask = cameraXR.layers.mask & -5;
  51777. cameraR.layers.mask = cameraXR.layers.mask & -3;
  51778. const parent = camera.parent;
  51779. const cameras = cameraXR.cameras;
  51780. updateCamera( cameraXR, parent );
  51781. for ( let i = 0; i < cameras.length; i ++ ) {
  51782. updateCamera( cameras[ i ], parent );
  51783. }
  51784. // update projection matrix for proper view frustum culling
  51785. if ( cameras.length === 2 ) {
  51786. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51787. } else {
  51788. // assume single camera setup (AR)
  51789. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51790. }
  51791. // update user camera and its children
  51792. updateUserCamera( camera, cameraXR, parent );
  51793. };
  51794. function updateUserCamera( camera, cameraXR, parent ) {
  51795. if ( parent === null ) {
  51796. camera.matrix.copy( cameraXR.matrixWorld );
  51797. } else {
  51798. camera.matrix.copy( parent.matrixWorld );
  51799. camera.matrix.invert();
  51800. camera.matrix.multiply( cameraXR.matrixWorld );
  51801. }
  51802. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51803. camera.updateMatrixWorld( true );
  51804. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51805. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51806. if ( camera.isPerspectiveCamera ) {
  51807. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51808. camera.zoom = 1;
  51809. }
  51810. }
  51811. /**
  51812. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51813. * of the active XR session. For each view it holds a separate camera object.
  51814. *
  51815. * The camera's `fov` is currently not used and does not reflect the fov of
  51816. * the XR camera. If you need the fov on app level, you have to compute in
  51817. * manually from the XR camera's projection matrices.
  51818. *
  51819. * @return {ArrayCamera} The XR camera.
  51820. */
  51821. this.getCamera = function () {
  51822. return cameraXR;
  51823. };
  51824. /**
  51825. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51826. *
  51827. * @return {number|undefined} The amount of foveation.
  51828. */
  51829. this.getFoveation = function () {
  51830. if ( glProjLayer === null && glBaseLayer === null ) {
  51831. return undefined;
  51832. }
  51833. return foveation;
  51834. };
  51835. /**
  51836. * Sets the foveation value.
  51837. *
  51838. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  51839. * and `1` means maximum foveation (the edges render at lower resolution).
  51840. */
  51841. this.setFoveation = function ( value ) {
  51842. // 0 = no foveation = full resolution
  51843. // 1 = maximum foveation = the edges render at lower resolution
  51844. foveation = value;
  51845. if ( glProjLayer !== null ) {
  51846. glProjLayer.fixedFoveation = value;
  51847. }
  51848. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  51849. glBaseLayer.fixedFoveation = value;
  51850. }
  51851. };
  51852. /**
  51853. * Returns `true` if depth sensing is supported.
  51854. *
  51855. * @return {boolean} Whether depth sensing is supported or not.
  51856. */
  51857. this.hasDepthSensing = function () {
  51858. return depthSensing.texture !== null;
  51859. };
  51860. /**
  51861. * Returns the depth sensing mesh.
  51862. *
  51863. * See {@link WebXRDepthSensing#getMesh}.
  51864. *
  51865. * @return {Mesh} The depth sensing mesh.
  51866. */
  51867. this.getDepthSensingMesh = function () {
  51868. return depthSensing.getMesh( cameraXR );
  51869. };
  51870. /**
  51871. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51872. * Only available during the current animation loop.
  51873. *
  51874. * @param {XRCamera} xrCamera - The camera to query.
  51875. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51876. */
  51877. this.getCameraTexture = function ( xrCamera ) {
  51878. return cameraAccessTextures[ xrCamera ];
  51879. };
  51880. // Animation Loop
  51881. let onAnimationFrameCallback = null;
  51882. function onAnimationFrame( time, frame ) {
  51883. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51884. xrFrame = frame;
  51885. if ( pose !== null ) {
  51886. const views = pose.views;
  51887. if ( glBaseLayer !== null ) {
  51888. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51889. renderer.setRenderTarget( newRenderTarget );
  51890. }
  51891. let cameraXRNeedsUpdate = false;
  51892. // check if it's necessary to rebuild cameraXR's camera list
  51893. if ( views.length !== cameraXR.cameras.length ) {
  51894. cameraXR.cameras.length = 0;
  51895. cameraXRNeedsUpdate = true;
  51896. }
  51897. for ( let i = 0; i < views.length; i ++ ) {
  51898. const view = views[ i ];
  51899. let viewport = null;
  51900. if ( glBaseLayer !== null ) {
  51901. viewport = glBaseLayer.getViewport( view );
  51902. } else {
  51903. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51904. viewport = glSubImage.viewport;
  51905. // For side-by-side projection, we only produce a single texture for both eyes.
  51906. if ( i === 0 ) {
  51907. renderer.setRenderTargetTextures(
  51908. newRenderTarget,
  51909. glSubImage.colorTexture,
  51910. glSubImage.depthStencilTexture );
  51911. renderer.setRenderTarget( newRenderTarget );
  51912. }
  51913. }
  51914. let camera = cameras[ i ];
  51915. if ( camera === undefined ) {
  51916. camera = new PerspectiveCamera();
  51917. camera.layers.enable( i );
  51918. camera.viewport = new Vector4();
  51919. cameras[ i ] = camera;
  51920. }
  51921. camera.matrix.fromArray( view.transform.matrix );
  51922. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51923. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51924. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51925. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51926. if ( i === 0 ) {
  51927. cameraXR.matrix.copy( camera.matrix );
  51928. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51929. }
  51930. if ( cameraXRNeedsUpdate === true ) {
  51931. cameraXR.cameras.push( camera );
  51932. }
  51933. }
  51934. //
  51935. const enabledFeatures = session.enabledFeatures;
  51936. const gpuDepthSensingEnabled = enabledFeatures &&
  51937. enabledFeatures.includes( 'depth-sensing' ) &&
  51938. session.depthUsage == 'gpu-optimized';
  51939. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51940. glBinding = scope.getBinding();
  51941. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51942. if ( depthData && depthData.isValid && depthData.texture ) {
  51943. depthSensing.init( depthData, session.renderState );
  51944. }
  51945. }
  51946. const cameraAccessEnabled = enabledFeatures &&
  51947. enabledFeatures.includes( 'camera-access' );
  51948. if ( cameraAccessEnabled && supportsGlBinding ) {
  51949. renderer.state.unbindTexture();
  51950. glBinding = scope.getBinding();
  51951. for ( let i = 0; i < views.length; i ++ ) {
  51952. const camera = views[ i ].camera;
  51953. if ( camera ) {
  51954. let cameraTex = cameraAccessTextures[ camera ];
  51955. if ( ! cameraTex ) {
  51956. cameraTex = new ExternalTexture();
  51957. cameraAccessTextures[ camera ] = cameraTex;
  51958. }
  51959. const glTexture = glBinding.getCameraImage( camera );
  51960. cameraTex.sourceTexture = glTexture;
  51961. }
  51962. }
  51963. }
  51964. }
  51965. //
  51966. for ( let i = 0; i < controllers.length; i ++ ) {
  51967. const inputSource = controllerInputSources[ i ];
  51968. const controller = controllers[ i ];
  51969. if ( inputSource !== null && controller !== undefined ) {
  51970. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51971. }
  51972. }
  51973. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51974. if ( frame.detectedPlanes ) {
  51975. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51976. }
  51977. xrFrame = null;
  51978. }
  51979. const animation = new WebGLAnimation();
  51980. animation.setAnimationLoop( onAnimationFrame );
  51981. this.setAnimationLoop = function ( callback ) {
  51982. onAnimationFrameCallback = callback;
  51983. };
  51984. this.dispose = function () {};
  51985. }
  51986. }
  51987. const _e1 = /*@__PURE__*/ new Euler();
  51988. const _m1 = /*@__PURE__*/ new Matrix4();
  51989. function WebGLMaterials( renderer, properties ) {
  51990. function refreshTransformUniform( map, uniform ) {
  51991. if ( map.matrixAutoUpdate === true ) {
  51992. map.updateMatrix();
  51993. }
  51994. uniform.value.copy( map.matrix );
  51995. }
  51996. function refreshFogUniforms( uniforms, fog ) {
  51997. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51998. if ( fog.isFog ) {
  51999. uniforms.fogNear.value = fog.near;
  52000. uniforms.fogFar.value = fog.far;
  52001. } else if ( fog.isFogExp2 ) {
  52002. uniforms.fogDensity.value = fog.density;
  52003. }
  52004. }
  52005. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  52006. if ( material.isMeshBasicMaterial ) {
  52007. refreshUniformsCommon( uniforms, material );
  52008. } else if ( material.isMeshLambertMaterial ) {
  52009. refreshUniformsCommon( uniforms, material );
  52010. } else if ( material.isMeshToonMaterial ) {
  52011. refreshUniformsCommon( uniforms, material );
  52012. refreshUniformsToon( uniforms, material );
  52013. } else if ( material.isMeshPhongMaterial ) {
  52014. refreshUniformsCommon( uniforms, material );
  52015. refreshUniformsPhong( uniforms, material );
  52016. } else if ( material.isMeshStandardMaterial ) {
  52017. refreshUniformsCommon( uniforms, material );
  52018. refreshUniformsStandard( uniforms, material );
  52019. if ( material.isMeshPhysicalMaterial ) {
  52020. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  52021. }
  52022. } else if ( material.isMeshMatcapMaterial ) {
  52023. refreshUniformsCommon( uniforms, material );
  52024. refreshUniformsMatcap( uniforms, material );
  52025. } else if ( material.isMeshDepthMaterial ) {
  52026. refreshUniformsCommon( uniforms, material );
  52027. } else if ( material.isMeshDistanceMaterial ) {
  52028. refreshUniformsCommon( uniforms, material );
  52029. refreshUniformsDistance( uniforms, material );
  52030. } else if ( material.isMeshNormalMaterial ) {
  52031. refreshUniformsCommon( uniforms, material );
  52032. } else if ( material.isLineBasicMaterial ) {
  52033. refreshUniformsLine( uniforms, material );
  52034. if ( material.isLineDashedMaterial ) {
  52035. refreshUniformsDash( uniforms, material );
  52036. }
  52037. } else if ( material.isPointsMaterial ) {
  52038. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  52039. } else if ( material.isSpriteMaterial ) {
  52040. refreshUniformsSprites( uniforms, material );
  52041. } else if ( material.isShadowMaterial ) {
  52042. uniforms.color.value.copy( material.color );
  52043. uniforms.opacity.value = material.opacity;
  52044. } else if ( material.isShaderMaterial ) {
  52045. material.uniformsNeedUpdate = false; // #15581
  52046. }
  52047. }
  52048. function refreshUniformsCommon( uniforms, material ) {
  52049. uniforms.opacity.value = material.opacity;
  52050. if ( material.color ) {
  52051. uniforms.diffuse.value.copy( material.color );
  52052. }
  52053. if ( material.emissive ) {
  52054. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  52055. }
  52056. if ( material.map ) {
  52057. uniforms.map.value = material.map;
  52058. refreshTransformUniform( material.map, uniforms.mapTransform );
  52059. }
  52060. if ( material.alphaMap ) {
  52061. uniforms.alphaMap.value = material.alphaMap;
  52062. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52063. }
  52064. if ( material.bumpMap ) {
  52065. uniforms.bumpMap.value = material.bumpMap;
  52066. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  52067. uniforms.bumpScale.value = material.bumpScale;
  52068. if ( material.side === BackSide ) {
  52069. uniforms.bumpScale.value *= -1;
  52070. }
  52071. }
  52072. if ( material.normalMap ) {
  52073. uniforms.normalMap.value = material.normalMap;
  52074. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  52075. uniforms.normalScale.value.copy( material.normalScale );
  52076. if ( material.side === BackSide ) {
  52077. uniforms.normalScale.value.negate();
  52078. }
  52079. }
  52080. if ( material.displacementMap ) {
  52081. uniforms.displacementMap.value = material.displacementMap;
  52082. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  52083. uniforms.displacementScale.value = material.displacementScale;
  52084. uniforms.displacementBias.value = material.displacementBias;
  52085. }
  52086. if ( material.emissiveMap ) {
  52087. uniforms.emissiveMap.value = material.emissiveMap;
  52088. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  52089. }
  52090. if ( material.specularMap ) {
  52091. uniforms.specularMap.value = material.specularMap;
  52092. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  52093. }
  52094. if ( material.alphaTest > 0 ) {
  52095. uniforms.alphaTest.value = material.alphaTest;
  52096. }
  52097. const materialProperties = properties.get( material );
  52098. const envMap = materialProperties.envMap;
  52099. const envMapRotation = materialProperties.envMapRotation;
  52100. if ( envMap ) {
  52101. uniforms.envMap.value = envMap;
  52102. _e1.copy( envMapRotation );
  52103. // accommodate left-handed frame
  52104. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  52105. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  52106. // environment maps which are not cube render targets or PMREMs follow a different convention
  52107. _e1.y *= -1;
  52108. _e1.z *= -1;
  52109. }
  52110. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  52111. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  52112. uniforms.reflectivity.value = material.reflectivity;
  52113. uniforms.ior.value = material.ior;
  52114. uniforms.refractionRatio.value = material.refractionRatio;
  52115. }
  52116. if ( material.lightMap ) {
  52117. uniforms.lightMap.value = material.lightMap;
  52118. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  52119. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  52120. }
  52121. if ( material.aoMap ) {
  52122. uniforms.aoMap.value = material.aoMap;
  52123. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  52124. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  52125. }
  52126. }
  52127. function refreshUniformsLine( uniforms, material ) {
  52128. uniforms.diffuse.value.copy( material.color );
  52129. uniforms.opacity.value = material.opacity;
  52130. if ( material.map ) {
  52131. uniforms.map.value = material.map;
  52132. refreshTransformUniform( material.map, uniforms.mapTransform );
  52133. }
  52134. }
  52135. function refreshUniformsDash( uniforms, material ) {
  52136. uniforms.dashSize.value = material.dashSize;
  52137. uniforms.totalSize.value = material.dashSize + material.gapSize;
  52138. uniforms.scale.value = material.scale;
  52139. }
  52140. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  52141. uniforms.diffuse.value.copy( material.color );
  52142. uniforms.opacity.value = material.opacity;
  52143. uniforms.size.value = material.size * pixelRatio;
  52144. uniforms.scale.value = height * 0.5;
  52145. if ( material.map ) {
  52146. uniforms.map.value = material.map;
  52147. refreshTransformUniform( material.map, uniforms.uvTransform );
  52148. }
  52149. if ( material.alphaMap ) {
  52150. uniforms.alphaMap.value = material.alphaMap;
  52151. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52152. }
  52153. if ( material.alphaTest > 0 ) {
  52154. uniforms.alphaTest.value = material.alphaTest;
  52155. }
  52156. }
  52157. function refreshUniformsSprites( uniforms, material ) {
  52158. uniforms.diffuse.value.copy( material.color );
  52159. uniforms.opacity.value = material.opacity;
  52160. uniforms.rotation.value = material.rotation;
  52161. if ( material.map ) {
  52162. uniforms.map.value = material.map;
  52163. refreshTransformUniform( material.map, uniforms.mapTransform );
  52164. }
  52165. if ( material.alphaMap ) {
  52166. uniforms.alphaMap.value = material.alphaMap;
  52167. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  52168. }
  52169. if ( material.alphaTest > 0 ) {
  52170. uniforms.alphaTest.value = material.alphaTest;
  52171. }
  52172. }
  52173. function refreshUniformsPhong( uniforms, material ) {
  52174. uniforms.specular.value.copy( material.specular );
  52175. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  52176. }
  52177. function refreshUniformsToon( uniforms, material ) {
  52178. if ( material.gradientMap ) {
  52179. uniforms.gradientMap.value = material.gradientMap;
  52180. }
  52181. }
  52182. function refreshUniformsStandard( uniforms, material ) {
  52183. uniforms.metalness.value = material.metalness;
  52184. if ( material.metalnessMap ) {
  52185. uniforms.metalnessMap.value = material.metalnessMap;
  52186. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  52187. }
  52188. uniforms.roughness.value = material.roughness;
  52189. if ( material.roughnessMap ) {
  52190. uniforms.roughnessMap.value = material.roughnessMap;
  52191. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  52192. }
  52193. if ( material.envMap ) {
  52194. //uniforms.envMap.value = material.envMap; // part of uniforms common
  52195. uniforms.envMapIntensity.value = material.envMapIntensity;
  52196. }
  52197. }
  52198. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  52199. uniforms.ior.value = material.ior; // also part of uniforms common
  52200. if ( material.sheen > 0 ) {
  52201. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  52202. uniforms.sheenRoughness.value = material.sheenRoughness;
  52203. if ( material.sheenColorMap ) {
  52204. uniforms.sheenColorMap.value = material.sheenColorMap;
  52205. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  52206. }
  52207. if ( material.sheenRoughnessMap ) {
  52208. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  52209. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  52210. }
  52211. }
  52212. if ( material.clearcoat > 0 ) {
  52213. uniforms.clearcoat.value = material.clearcoat;
  52214. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  52215. if ( material.clearcoatMap ) {
  52216. uniforms.clearcoatMap.value = material.clearcoatMap;
  52217. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  52218. }
  52219. if ( material.clearcoatRoughnessMap ) {
  52220. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  52221. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  52222. }
  52223. if ( material.clearcoatNormalMap ) {
  52224. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  52225. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  52226. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  52227. if ( material.side === BackSide ) {
  52228. uniforms.clearcoatNormalScale.value.negate();
  52229. }
  52230. }
  52231. }
  52232. if ( material.dispersion > 0 ) {
  52233. uniforms.dispersion.value = material.dispersion;
  52234. }
  52235. if ( material.iridescence > 0 ) {
  52236. uniforms.iridescence.value = material.iridescence;
  52237. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  52238. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  52239. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  52240. if ( material.iridescenceMap ) {
  52241. uniforms.iridescenceMap.value = material.iridescenceMap;
  52242. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  52243. }
  52244. if ( material.iridescenceThicknessMap ) {
  52245. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  52246. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  52247. }
  52248. }
  52249. if ( material.transmission > 0 ) {
  52250. uniforms.transmission.value = material.transmission;
  52251. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  52252. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  52253. if ( material.transmissionMap ) {
  52254. uniforms.transmissionMap.value = material.transmissionMap;
  52255. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  52256. }
  52257. uniforms.thickness.value = material.thickness;
  52258. if ( material.thicknessMap ) {
  52259. uniforms.thicknessMap.value = material.thicknessMap;
  52260. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  52261. }
  52262. uniforms.attenuationDistance.value = material.attenuationDistance;
  52263. uniforms.attenuationColor.value.copy( material.attenuationColor );
  52264. }
  52265. if ( material.anisotropy > 0 ) {
  52266. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  52267. if ( material.anisotropyMap ) {
  52268. uniforms.anisotropyMap.value = material.anisotropyMap;
  52269. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  52270. }
  52271. }
  52272. uniforms.specularIntensity.value = material.specularIntensity;
  52273. uniforms.specularColor.value.copy( material.specularColor );
  52274. if ( material.specularColorMap ) {
  52275. uniforms.specularColorMap.value = material.specularColorMap;
  52276. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52277. }
  52278. if ( material.specularIntensityMap ) {
  52279. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52280. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52281. }
  52282. }
  52283. function refreshUniformsMatcap( uniforms, material ) {
  52284. if ( material.matcap ) {
  52285. uniforms.matcap.value = material.matcap;
  52286. }
  52287. }
  52288. function refreshUniformsDistance( uniforms, material ) {
  52289. const light = properties.get( material ).light;
  52290. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52291. uniforms.nearDistance.value = light.shadow.camera.near;
  52292. uniforms.farDistance.value = light.shadow.camera.far;
  52293. }
  52294. return {
  52295. refreshFogUniforms: refreshFogUniforms,
  52296. refreshMaterialUniforms: refreshMaterialUniforms
  52297. };
  52298. }
  52299. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52300. let buffers = {};
  52301. let updateList = {};
  52302. let allocatedBindingPoints = [];
  52303. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52304. function bind( uniformsGroup, program ) {
  52305. const webglProgram = program.program;
  52306. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52307. }
  52308. function update( uniformsGroup, program ) {
  52309. let buffer = buffers[ uniformsGroup.id ];
  52310. if ( buffer === undefined ) {
  52311. prepareUniformsGroup( uniformsGroup );
  52312. buffer = createBuffer( uniformsGroup );
  52313. buffers[ uniformsGroup.id ] = buffer;
  52314. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52315. }
  52316. // ensure to update the binding points/block indices mapping for this program
  52317. const webglProgram = program.program;
  52318. state.updateUBOMapping( uniformsGroup, webglProgram );
  52319. // update UBO once per frame
  52320. const frame = info.render.frame;
  52321. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52322. updateBufferData( uniformsGroup );
  52323. updateList[ uniformsGroup.id ] = frame;
  52324. }
  52325. }
  52326. function createBuffer( uniformsGroup ) {
  52327. // the setup of an UBO is independent of a particular shader program but global
  52328. const bindingPointIndex = allocateBindingPointIndex();
  52329. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52330. const buffer = gl.createBuffer();
  52331. const size = uniformsGroup.__size;
  52332. const usage = uniformsGroup.usage;
  52333. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52334. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52335. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52336. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52337. return buffer;
  52338. }
  52339. function allocateBindingPointIndex() {
  52340. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52341. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52342. allocatedBindingPoints.push( i );
  52343. return i;
  52344. }
  52345. }
  52346. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52347. return 0;
  52348. }
  52349. function updateBufferData( uniformsGroup ) {
  52350. const buffer = buffers[ uniformsGroup.id ];
  52351. const uniforms = uniformsGroup.uniforms;
  52352. const cache = uniformsGroup.__cache;
  52353. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52354. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52355. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52356. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52357. const uniform = uniformArray[ j ];
  52358. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52359. const offset = uniform.__offset;
  52360. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52361. let arrayOffset = 0;
  52362. for ( let k = 0; k < values.length; k ++ ) {
  52363. const value = values[ k ];
  52364. const info = getUniformSize( value );
  52365. // TODO add integer and struct support
  52366. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52367. uniform.__data[ 0 ] = value;
  52368. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52369. } else if ( value.isMatrix3 ) {
  52370. // manually converting 3x3 to 3x4
  52371. uniform.__data[ 0 ] = value.elements[ 0 ];
  52372. uniform.__data[ 1 ] = value.elements[ 1 ];
  52373. uniform.__data[ 2 ] = value.elements[ 2 ];
  52374. uniform.__data[ 3 ] = 0;
  52375. uniform.__data[ 4 ] = value.elements[ 3 ];
  52376. uniform.__data[ 5 ] = value.elements[ 4 ];
  52377. uniform.__data[ 6 ] = value.elements[ 5 ];
  52378. uniform.__data[ 7 ] = 0;
  52379. uniform.__data[ 8 ] = value.elements[ 6 ];
  52380. uniform.__data[ 9 ] = value.elements[ 7 ];
  52381. uniform.__data[ 10 ] = value.elements[ 8 ];
  52382. uniform.__data[ 11 ] = 0;
  52383. } else {
  52384. value.toArray( uniform.__data, arrayOffset );
  52385. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52386. }
  52387. }
  52388. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52389. }
  52390. }
  52391. }
  52392. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52393. }
  52394. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52395. const value = uniform.value;
  52396. const indexString = index + '_' + indexArray;
  52397. if ( cache[ indexString ] === undefined ) {
  52398. // cache entry does not exist so far
  52399. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52400. cache[ indexString ] = value;
  52401. } else {
  52402. cache[ indexString ] = value.clone();
  52403. }
  52404. return true;
  52405. } else {
  52406. const cachedObject = cache[ indexString ];
  52407. // compare current value with cached entry
  52408. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52409. if ( cachedObject !== value ) {
  52410. cache[ indexString ] = value;
  52411. return true;
  52412. }
  52413. } else {
  52414. if ( cachedObject.equals( value ) === false ) {
  52415. cachedObject.copy( value );
  52416. return true;
  52417. }
  52418. }
  52419. }
  52420. return false;
  52421. }
  52422. function prepareUniformsGroup( uniformsGroup ) {
  52423. // determine total buffer size according to the STD140 layout
  52424. // Hint: STD140 is the only supported layout in WebGL 2
  52425. const uniforms = uniformsGroup.uniforms;
  52426. let offset = 0; // global buffer offset in bytes
  52427. const chunkSize = 16; // size of a chunk in bytes
  52428. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52429. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52430. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52431. const uniform = uniformArray[ j ];
  52432. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52433. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52434. const value = values[ k ];
  52435. const info = getUniformSize( value );
  52436. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52437. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52438. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52439. offset += chunkPadding;
  52440. // Check for chunk overflow
  52441. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52442. // Add padding and adjust offset
  52443. offset += ( chunkSize - chunkStart );
  52444. }
  52445. // the following two properties will be used for partial buffer updates
  52446. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52447. uniform.__offset = offset;
  52448. // Update the global offset
  52449. offset += info.storage;
  52450. }
  52451. }
  52452. }
  52453. // ensure correct final padding
  52454. const chunkOffset = offset % chunkSize;
  52455. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52456. //
  52457. uniformsGroup.__size = offset;
  52458. uniformsGroup.__cache = {};
  52459. return this;
  52460. }
  52461. function getUniformSize( value ) {
  52462. const info = {
  52463. boundary: 0, // bytes
  52464. storage: 0 // bytes
  52465. };
  52466. // determine sizes according to STD140
  52467. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52468. // float/int/bool
  52469. info.boundary = 4;
  52470. info.storage = 4;
  52471. } else if ( value.isVector2 ) {
  52472. // vec2
  52473. info.boundary = 8;
  52474. info.storage = 8;
  52475. } else if ( value.isVector3 || value.isColor ) {
  52476. // vec3
  52477. info.boundary = 16;
  52478. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52479. } else if ( value.isVector4 ) {
  52480. // vec4
  52481. info.boundary = 16;
  52482. info.storage = 16;
  52483. } else if ( value.isMatrix3 ) {
  52484. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52485. info.boundary = 48;
  52486. info.storage = 48;
  52487. } else if ( value.isMatrix4 ) {
  52488. // mat4
  52489. info.boundary = 64;
  52490. info.storage = 64;
  52491. } else if ( value.isTexture ) {
  52492. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52493. } else {
  52494. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52495. }
  52496. return info;
  52497. }
  52498. function onUniformsGroupsDispose( event ) {
  52499. const uniformsGroup = event.target;
  52500. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52501. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52502. allocatedBindingPoints.splice( index, 1 );
  52503. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52504. delete buffers[ uniformsGroup.id ];
  52505. delete updateList[ uniformsGroup.id ];
  52506. }
  52507. function dispose() {
  52508. for ( const id in buffers ) {
  52509. gl.deleteBuffer( buffers[ id ] );
  52510. }
  52511. allocatedBindingPoints = [];
  52512. buffers = {};
  52513. updateList = {};
  52514. }
  52515. return {
  52516. bind: bind,
  52517. update: update,
  52518. dispose: dispose
  52519. };
  52520. }
  52521. /**
  52522. * Precomputed DFG LUT for Image-Based Lighting
  52523. * Resolution: 16x16
  52524. * Samples: 4096 per texel
  52525. * Format: RG16F (2 half floats per texel: scale, bias)
  52526. */
  52527. const DATA = new Uint16Array( [
  52528. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  52529. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  52530. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  52531. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  52532. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  52533. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  52534. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  52535. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  52536. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  52537. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  52538. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  52539. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  52540. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  52541. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  52542. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  52543. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  52544. ] );
  52545. let lut = null;
  52546. function getDFGLUT() {
  52547. if ( lut === null ) {
  52548. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52549. lut.name = 'DFG_LUT';
  52550. lut.minFilter = LinearFilter;
  52551. lut.magFilter = LinearFilter;
  52552. lut.wrapS = ClampToEdgeWrapping;
  52553. lut.wrapT = ClampToEdgeWrapping;
  52554. lut.generateMipmaps = false;
  52555. lut.needsUpdate = true;
  52556. }
  52557. return lut;
  52558. }
  52559. /**
  52560. * This renderer uses WebGL 2 to display scenes.
  52561. *
  52562. * WebGL 1 is not supported since `r163`.
  52563. */
  52564. class WebGLRenderer {
  52565. /**
  52566. * Constructs a new WebGL renderer.
  52567. *
  52568. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52569. */
  52570. constructor( parameters = {} ) {
  52571. const {
  52572. canvas = createCanvasElement(),
  52573. context = null,
  52574. depth = true,
  52575. stencil = false,
  52576. alpha = false,
  52577. antialias = false,
  52578. premultipliedAlpha = true,
  52579. preserveDrawingBuffer = false,
  52580. powerPreference = 'default',
  52581. failIfMajorPerformanceCaveat = false,
  52582. reversedDepthBuffer = false,
  52583. outputBufferType = UnsignedByteType,
  52584. } = parameters;
  52585. /**
  52586. * This flag can be used for type testing.
  52587. *
  52588. * @type {boolean}
  52589. * @readonly
  52590. * @default true
  52591. */
  52592. this.isWebGLRenderer = true;
  52593. let _alpha;
  52594. if ( context !== null ) {
  52595. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52596. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52597. }
  52598. _alpha = context.getContextAttributes().alpha;
  52599. } else {
  52600. _alpha = alpha;
  52601. }
  52602. const _outputBufferType = outputBufferType;
  52603. const INTEGER_FORMATS = new Set( [
  52604. RGBAIntegerFormat,
  52605. RGIntegerFormat,
  52606. RedIntegerFormat
  52607. ] );
  52608. const UNSIGNED_TYPES = new Set( [
  52609. UnsignedByteType,
  52610. UnsignedIntType,
  52611. UnsignedShortType,
  52612. UnsignedInt248Type,
  52613. UnsignedShort4444Type,
  52614. UnsignedShort5551Type
  52615. ] );
  52616. const uintClearColor = new Uint32Array( 4 );
  52617. const intClearColor = new Int32Array( 4 );
  52618. let currentRenderList = null;
  52619. let currentRenderState = null;
  52620. // render() can be called from within a callback triggered by another render.
  52621. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52622. const renderListStack = [];
  52623. const renderStateStack = [];
  52624. // internal render target for non-UnsignedByteType color buffer
  52625. let output = null;
  52626. // public properties
  52627. /**
  52628. * A canvas where the renderer draws its output. This is automatically created by the renderer
  52629. * in the constructor (if not provided already); you just need to add it to your page like so:
  52630. * ```js
  52631. * document.body.appendChild( renderer.domElement );
  52632. * ```
  52633. *
  52634. * @type {HTMLCanvasElement|OffscreenCanvas}
  52635. */
  52636. this.domElement = canvas;
  52637. /**
  52638. * A object with debug configuration settings.
  52639. *
  52640. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52641. * checked for errors during compilation and linkage process. It may be useful to disable
  52642. * this check in production for performance gain. It is strongly recommended to keep these
  52643. * checks enabled during development. If the shader does not compile and link, it will not
  52644. * work and associated material will not render.
  52645. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52646. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52647. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52648. * Assigning a custom function disables the default error reporting.
  52649. *
  52650. * @type {Object}
  52651. */
  52652. this.debug = {
  52653. /**
  52654. * Enables error checking and reporting when shader programs are being compiled.
  52655. * @type {boolean}
  52656. */
  52657. checkShaderErrors: true,
  52658. /**
  52659. * Callback for custom error reporting.
  52660. * @type {?Function}
  52661. */
  52662. onShaderError: null
  52663. };
  52664. // clearing
  52665. /**
  52666. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52667. *
  52668. * @type {boolean}
  52669. * @default true
  52670. */
  52671. this.autoClear = true;
  52672. /**
  52673. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52674. * the color buffer or not.
  52675. *
  52676. * @type {boolean}
  52677. * @default true
  52678. */
  52679. this.autoClearColor = true;
  52680. /**
  52681. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52682. * the depth buffer or not.
  52683. *
  52684. * @type {boolean}
  52685. * @default true
  52686. */
  52687. this.autoClearDepth = true;
  52688. /**
  52689. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52690. * the stencil buffer or not.
  52691. *
  52692. * @type {boolean}
  52693. * @default true
  52694. */
  52695. this.autoClearStencil = true;
  52696. // scene graph
  52697. /**
  52698. * Whether the renderer should sort objects or not.
  52699. *
  52700. * Note: Sorting is used to attempt to properly render objects that have some
  52701. * degree of transparency. By definition, sorting objects may not work in all
  52702. * cases. Depending on the needs of application, it may be necessary to turn
  52703. * off sorting and use other methods to deal with transparency rendering e.g.
  52704. * manually determining each object's rendering order.
  52705. *
  52706. * @type {boolean}
  52707. * @default true
  52708. */
  52709. this.sortObjects = true;
  52710. // user-defined clipping
  52711. /**
  52712. * User-defined clipping planes specified in world space. These planes apply globally.
  52713. * Points in space whose dot product with the plane is negative are cut away.
  52714. *
  52715. * @type {Array<Plane>}
  52716. */
  52717. this.clippingPlanes = [];
  52718. /**
  52719. * Whether the renderer respects object-level clipping planes or not.
  52720. *
  52721. * @type {boolean}
  52722. * @default false
  52723. */
  52724. this.localClippingEnabled = false;
  52725. // tone mapping
  52726. /**
  52727. * The tone mapping technique of the renderer.
  52728. *
  52729. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52730. * @default NoToneMapping
  52731. */
  52732. this.toneMapping = NoToneMapping;
  52733. /**
  52734. * Exposure level of tone mapping.
  52735. *
  52736. * @type {number}
  52737. * @default 1
  52738. */
  52739. this.toneMappingExposure = 1.0;
  52740. // transmission
  52741. /**
  52742. * The normalized resolution scale for the transmission render target, measured in percentage
  52743. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52744. * when using {@link MeshPhysicalMaterial#transmission}.
  52745. *
  52746. * @type {number}
  52747. * @default 1
  52748. */
  52749. this.transmissionResolutionScale = 1.0;
  52750. // internal properties
  52751. const _this = this;
  52752. let _isContextLost = false;
  52753. // internal state cache
  52754. this._outputColorSpace = SRGBColorSpace;
  52755. let _currentActiveCubeFace = 0;
  52756. let _currentActiveMipmapLevel = 0;
  52757. let _currentRenderTarget = null;
  52758. let _currentMaterialId = -1;
  52759. let _currentCamera = null;
  52760. const _currentViewport = new Vector4();
  52761. const _currentScissor = new Vector4();
  52762. let _currentScissorTest = null;
  52763. const _currentClearColor = new Color( 0x000000 );
  52764. let _currentClearAlpha = 0;
  52765. //
  52766. let _width = canvas.width;
  52767. let _height = canvas.height;
  52768. let _pixelRatio = 1;
  52769. let _opaqueSort = null;
  52770. let _transparentSort = null;
  52771. const _viewport = new Vector4( 0, 0, _width, _height );
  52772. const _scissor = new Vector4( 0, 0, _width, _height );
  52773. let _scissorTest = false;
  52774. // frustum
  52775. const _frustum = new Frustum();
  52776. // clipping
  52777. let _clippingEnabled = false;
  52778. let _localClippingEnabled = false;
  52779. // camera matrices cache
  52780. const _projScreenMatrix = new Matrix4();
  52781. const _vector3 = new Vector3();
  52782. const _vector4 = new Vector4();
  52783. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52784. let _renderBackground = false;
  52785. function getTargetPixelRatio() {
  52786. return _currentRenderTarget === null ? _pixelRatio : 1;
  52787. }
  52788. // initialize
  52789. let _gl = context;
  52790. function getContext( contextName, contextAttributes ) {
  52791. return canvas.getContext( contextName, contextAttributes );
  52792. }
  52793. try {
  52794. const contextAttributes = {
  52795. alpha: true,
  52796. depth,
  52797. stencil,
  52798. antialias,
  52799. premultipliedAlpha,
  52800. preserveDrawingBuffer,
  52801. powerPreference,
  52802. failIfMajorPerformanceCaveat,
  52803. };
  52804. // OffscreenCanvas does not have setAttribute, see #22811
  52805. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52806. // event listeners must be registered before WebGL context is created, see #12753
  52807. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52808. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52809. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52810. if ( _gl === null ) {
  52811. const contextName = 'webgl2';
  52812. _gl = getContext( contextName, contextAttributes );
  52813. if ( _gl === null ) {
  52814. if ( getContext( contextName ) ) {
  52815. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52816. } else {
  52817. throw new Error( 'Error creating WebGL context.' );
  52818. }
  52819. }
  52820. }
  52821. } catch ( e ) {
  52822. error( 'WebGLRenderer: ' + e.message );
  52823. throw e;
  52824. }
  52825. let extensions, capabilities, state, info;
  52826. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  52827. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  52828. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  52829. let utils, bindingStates, uniformsGroups;
  52830. function initGLContext() {
  52831. extensions = new WebGLExtensions( _gl );
  52832. extensions.init();
  52833. utils = new WebGLUtils( _gl, extensions );
  52834. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  52835. state = new WebGLState( _gl, extensions );
  52836. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  52837. state.buffers.depth.setReversed( true );
  52838. }
  52839. info = new WebGLInfo( _gl );
  52840. properties = new WebGLProperties();
  52841. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  52842. cubemaps = new WebGLCubeMaps( _this );
  52843. cubeuvmaps = new WebGLCubeUVMaps( _this );
  52844. attributes = new WebGLAttributes( _gl );
  52845. bindingStates = new WebGLBindingStates( _gl, attributes );
  52846. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  52847. objects = new WebGLObjects( _gl, geometries, attributes, bindingStates, info );
  52848. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  52849. clipping = new WebGLClipping( properties );
  52850. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  52851. materials = new WebGLMaterials( _this, properties );
  52852. renderLists = new WebGLRenderLists();
  52853. renderStates = new WebGLRenderStates( extensions );
  52854. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  52855. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  52856. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  52857. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  52858. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  52859. info.programs = programCache.programs;
  52860. /**
  52861. * Holds details about the capabilities of the current rendering context.
  52862. *
  52863. * @name WebGLRenderer#capabilities
  52864. * @type {WebGLRenderer~Capabilities}
  52865. */
  52866. _this.capabilities = capabilities;
  52867. /**
  52868. * Provides methods for retrieving and testing WebGL extensions.
  52869. *
  52870. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  52871. * and return the extension object if available.
  52872. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  52873. *
  52874. * @name WebGLRenderer#extensions
  52875. * @type {Object}
  52876. */
  52877. _this.extensions = extensions;
  52878. /**
  52879. * Used to track properties of other objects like native WebGL objects.
  52880. *
  52881. * @name WebGLRenderer#properties
  52882. * @type {Object}
  52883. */
  52884. _this.properties = properties;
  52885. /**
  52886. * Manages the render lists of the renderer.
  52887. *
  52888. * @name WebGLRenderer#renderLists
  52889. * @type {Object}
  52890. */
  52891. _this.renderLists = renderLists;
  52892. /**
  52893. * Interface for managing shadows.
  52894. *
  52895. * @name WebGLRenderer#shadowMap
  52896. * @type {WebGLRenderer~ShadowMap}
  52897. */
  52898. _this.shadowMap = shadowMap;
  52899. /**
  52900. * Interface for managing the WebGL state.
  52901. *
  52902. * @name WebGLRenderer#state
  52903. * @type {Object}
  52904. */
  52905. _this.state = state;
  52906. /**
  52907. * Holds a series of statistical information about the GPU memory
  52908. * and the rendering process. Useful for debugging and monitoring.
  52909. *
  52910. * By default these data are reset at each render call but when having
  52911. * multiple render passes per frame (e.g. when using post processing) it can
  52912. * be preferred to reset with a custom pattern. First, set `autoReset` to
  52913. * `false`.
  52914. * ```js
  52915. * renderer.info.autoReset = false;
  52916. * ```
  52917. * Call `reset()` whenever you have finished to render a single frame.
  52918. * ```js
  52919. * renderer.info.reset();
  52920. * ```
  52921. *
  52922. * @name WebGLRenderer#info
  52923. * @type {WebGLRenderer~Info}
  52924. */
  52925. _this.info = info;
  52926. }
  52927. initGLContext();
  52928. // initialize internal render target for non-UnsignedByteType color buffer
  52929. if ( _outputBufferType !== UnsignedByteType ) {
  52930. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  52931. }
  52932. // xr
  52933. const xr = new WebXRManager( _this, _gl );
  52934. /**
  52935. * A reference to the XR manager.
  52936. *
  52937. * @type {WebXRManager}
  52938. */
  52939. this.xr = xr;
  52940. /**
  52941. * Returns the rendering context.
  52942. *
  52943. * @return {WebGL2RenderingContext} The rendering context.
  52944. */
  52945. this.getContext = function () {
  52946. return _gl;
  52947. };
  52948. /**
  52949. * Returns the rendering context attributes.
  52950. *
  52951. * @return {WebGLContextAttributes} The rendering context attributes.
  52952. */
  52953. this.getContextAttributes = function () {
  52954. return _gl.getContextAttributes();
  52955. };
  52956. /**
  52957. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52958. */
  52959. this.forceContextLoss = function () {
  52960. const extension = extensions.get( 'WEBGL_lose_context' );
  52961. if ( extension ) extension.loseContext();
  52962. };
  52963. /**
  52964. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52965. */
  52966. this.forceContextRestore = function () {
  52967. const extension = extensions.get( 'WEBGL_lose_context' );
  52968. if ( extension ) extension.restoreContext();
  52969. };
  52970. /**
  52971. * Returns the pixel ratio.
  52972. *
  52973. * @return {number} The pixel ratio.
  52974. */
  52975. this.getPixelRatio = function () {
  52976. return _pixelRatio;
  52977. };
  52978. /**
  52979. * Sets the given pixel ratio and resizes the canvas if necessary.
  52980. *
  52981. * @param {number} value - The pixel ratio.
  52982. */
  52983. this.setPixelRatio = function ( value ) {
  52984. if ( value === undefined ) return;
  52985. _pixelRatio = value;
  52986. this.setSize( _width, _height, false );
  52987. };
  52988. /**
  52989. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52990. *
  52991. * @param {Vector2} target - The method writes the result in this target object.
  52992. * @return {Vector2} The renderer's size in logical pixels.
  52993. */
  52994. this.getSize = function ( target ) {
  52995. return target.set( _width, _height );
  52996. };
  52997. /**
  52998. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52999. * into account, and also sets the viewport to fit that size, starting in (0,
  53000. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  53001. *
  53002. * @param {number} width - The width in logical pixels.
  53003. * @param {number} height - The height in logical pixels.
  53004. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  53005. */
  53006. this.setSize = function ( width, height, updateStyle = true ) {
  53007. if ( xr.isPresenting ) {
  53008. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  53009. return;
  53010. }
  53011. _width = width;
  53012. _height = height;
  53013. canvas.width = Math.floor( width * _pixelRatio );
  53014. canvas.height = Math.floor( height * _pixelRatio );
  53015. if ( updateStyle === true ) {
  53016. canvas.style.width = width + 'px';
  53017. canvas.style.height = height + 'px';
  53018. }
  53019. if ( output !== null ) {
  53020. output.setSize( canvas.width, canvas.height );
  53021. }
  53022. this.setViewport( 0, 0, width, height );
  53023. };
  53024. /**
  53025. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  53026. *
  53027. * @param {Vector2} target - The method writes the result in this target object.
  53028. * @return {Vector2} The drawing buffer size.
  53029. */
  53030. this.getDrawingBufferSize = function ( target ) {
  53031. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  53032. };
  53033. /**
  53034. * This method allows to define the drawing buffer size by specifying
  53035. * width, height and pixel ratio all at once. The size of the drawing
  53036. * buffer is computed with this formula:
  53037. * ```js
  53038. * size.x = width * pixelRatio;
  53039. * size.y = height * pixelRatio;
  53040. * ```
  53041. *
  53042. * @param {number} width - The width in logical pixels.
  53043. * @param {number} height - The height in logical pixels.
  53044. * @param {number} pixelRatio - The pixel ratio.
  53045. */
  53046. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  53047. _width = width;
  53048. _height = height;
  53049. _pixelRatio = pixelRatio;
  53050. canvas.width = Math.floor( width * pixelRatio );
  53051. canvas.height = Math.floor( height * pixelRatio );
  53052. this.setViewport( 0, 0, width, height );
  53053. };
  53054. /**
  53055. * Sets the post-processing effects to be applied after rendering.
  53056. *
  53057. * @param {Array} effects - An array of post-processing effects.
  53058. */
  53059. this.setEffects = function ( effects ) {
  53060. if ( _outputBufferType === UnsignedByteType ) {
  53061. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  53062. return;
  53063. }
  53064. if ( effects ) {
  53065. for ( let i = 0; i < effects.length; i ++ ) {
  53066. if ( effects[ i ].isOutputPass === true ) {
  53067. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  53068. break;
  53069. }
  53070. }
  53071. }
  53072. output.setEffects( effects || [] );
  53073. };
  53074. /**
  53075. * Returns the current viewport definition.
  53076. *
  53077. * @param {Vector2} target - The method writes the result in this target object.
  53078. * @return {Vector2} The current viewport definition.
  53079. */
  53080. this.getCurrentViewport = function ( target ) {
  53081. return target.copy( _currentViewport );
  53082. };
  53083. /**
  53084. * Returns the viewport definition.
  53085. *
  53086. * @param {Vector4} target - The method writes the result in this target object.
  53087. * @return {Vector4} The viewport definition.
  53088. */
  53089. this.getViewport = function ( target ) {
  53090. return target.copy( _viewport );
  53091. };
  53092. /**
  53093. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  53094. *
  53095. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53096. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  53097. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  53098. * @param {number} width - The width of the viewport in logical pixel unit.
  53099. * @param {number} height - The height of the viewport in logical pixel unit.
  53100. */
  53101. this.setViewport = function ( x, y, width, height ) {
  53102. if ( x.isVector4 ) {
  53103. _viewport.set( x.x, x.y, x.z, x.w );
  53104. } else {
  53105. _viewport.set( x, y, width, height );
  53106. }
  53107. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  53108. };
  53109. /**
  53110. * Returns the scissor region.
  53111. *
  53112. * @param {Vector4} target - The method writes the result in this target object.
  53113. * @return {Vector4} The scissor region.
  53114. */
  53115. this.getScissor = function ( target ) {
  53116. return target.copy( _scissor );
  53117. };
  53118. /**
  53119. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  53120. *
  53121. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53122. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  53123. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  53124. * @param {number} width - The width of the scissor region in logical pixel unit.
  53125. * @param {number} height - The height of the scissor region in logical pixel unit.
  53126. */
  53127. this.setScissor = function ( x, y, width, height ) {
  53128. if ( x.isVector4 ) {
  53129. _scissor.set( x.x, x.y, x.z, x.w );
  53130. } else {
  53131. _scissor.set( x, y, width, height );
  53132. }
  53133. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  53134. };
  53135. /**
  53136. * Returns `true` if the scissor test is enabled.
  53137. *
  53138. * @return {boolean} Whether the scissor test is enabled or not.
  53139. */
  53140. this.getScissorTest = function () {
  53141. return _scissorTest;
  53142. };
  53143. /**
  53144. * Enable or disable the scissor test. When this is enabled, only the pixels
  53145. * within the defined scissor area will be affected by further renderer
  53146. * actions.
  53147. *
  53148. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  53149. */
  53150. this.setScissorTest = function ( boolean ) {
  53151. state.setScissorTest( _scissorTest = boolean );
  53152. };
  53153. /**
  53154. * Sets a custom opaque sort function for the render lists. Pass `null`
  53155. * to use the default `painterSortStable` function.
  53156. *
  53157. * @param {?Function} method - The opaque sort function.
  53158. */
  53159. this.setOpaqueSort = function ( method ) {
  53160. _opaqueSort = method;
  53161. };
  53162. /**
  53163. * Sets a custom transparent sort function for the render lists. Pass `null`
  53164. * to use the default `reversePainterSortStable` function.
  53165. *
  53166. * @param {?Function} method - The opaque sort function.
  53167. */
  53168. this.setTransparentSort = function ( method ) {
  53169. _transparentSort = method;
  53170. };
  53171. // Clearing
  53172. /**
  53173. * Returns the clear color.
  53174. *
  53175. * @param {Color} target - The method writes the result in this target object.
  53176. * @return {Color} The clear color.
  53177. */
  53178. this.getClearColor = function ( target ) {
  53179. return target.copy( background.getClearColor() );
  53180. };
  53181. /**
  53182. * Sets the clear color and alpha.
  53183. *
  53184. * @param {Color} color - The clear color.
  53185. * @param {number} [alpha=1] - The clear alpha.
  53186. */
  53187. this.setClearColor = function () {
  53188. background.setClearColor( ...arguments );
  53189. };
  53190. /**
  53191. * Returns the clear alpha. Ranges within `[0,1]`.
  53192. *
  53193. * @return {number} The clear alpha.
  53194. */
  53195. this.getClearAlpha = function () {
  53196. return background.getClearAlpha();
  53197. };
  53198. /**
  53199. * Sets the clear alpha.
  53200. *
  53201. * @param {number} alpha - The clear alpha.
  53202. */
  53203. this.setClearAlpha = function () {
  53204. background.setClearAlpha( ...arguments );
  53205. };
  53206. /**
  53207. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  53208. * This method initializes the buffers to the current clear color values.
  53209. *
  53210. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  53211. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  53212. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  53213. */
  53214. this.clear = function ( color = true, depth = true, stencil = true ) {
  53215. let bits = 0;
  53216. if ( color ) {
  53217. // check if we're trying to clear an integer target
  53218. let isIntegerFormat = false;
  53219. if ( _currentRenderTarget !== null ) {
  53220. const targetFormat = _currentRenderTarget.texture.format;
  53221. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  53222. }
  53223. // use the appropriate clear functions to clear the target if it's a signed
  53224. // or unsigned integer target
  53225. if ( isIntegerFormat ) {
  53226. const targetType = _currentRenderTarget.texture.type;
  53227. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  53228. const clearColor = background.getClearColor();
  53229. const a = background.getClearAlpha();
  53230. const r = clearColor.r;
  53231. const g = clearColor.g;
  53232. const b = clearColor.b;
  53233. if ( isUnsignedType ) {
  53234. uintClearColor[ 0 ] = r;
  53235. uintClearColor[ 1 ] = g;
  53236. uintClearColor[ 2 ] = b;
  53237. uintClearColor[ 3 ] = a;
  53238. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  53239. } else {
  53240. intClearColor[ 0 ] = r;
  53241. intClearColor[ 1 ] = g;
  53242. intClearColor[ 2 ] = b;
  53243. intClearColor[ 3 ] = a;
  53244. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  53245. }
  53246. } else {
  53247. bits |= _gl.COLOR_BUFFER_BIT;
  53248. }
  53249. }
  53250. if ( depth ) {
  53251. bits |= _gl.DEPTH_BUFFER_BIT;
  53252. }
  53253. if ( stencil ) {
  53254. bits |= _gl.STENCIL_BUFFER_BIT;
  53255. this.state.buffers.stencil.setMask( 0xffffffff );
  53256. }
  53257. _gl.clear( bits );
  53258. };
  53259. /**
  53260. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  53261. */
  53262. this.clearColor = function () {
  53263. this.clear( true, false, false );
  53264. };
  53265. /**
  53266. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  53267. */
  53268. this.clearDepth = function () {
  53269. this.clear( false, true, false );
  53270. };
  53271. /**
  53272. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53273. */
  53274. this.clearStencil = function () {
  53275. this.clear( false, false, true );
  53276. };
  53277. /**
  53278. * Frees the GPU-related resources allocated by this instance. Call this
  53279. * method whenever this instance is no longer used in your app.
  53280. */
  53281. this.dispose = function () {
  53282. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53283. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53284. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53285. background.dispose();
  53286. renderLists.dispose();
  53287. renderStates.dispose();
  53288. properties.dispose();
  53289. cubemaps.dispose();
  53290. cubeuvmaps.dispose();
  53291. objects.dispose();
  53292. bindingStates.dispose();
  53293. uniformsGroups.dispose();
  53294. programCache.dispose();
  53295. xr.dispose();
  53296. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53297. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53298. animation.stop();
  53299. };
  53300. // Events
  53301. function onContextLost( event ) {
  53302. event.preventDefault();
  53303. log( 'WebGLRenderer: Context Lost.' );
  53304. _isContextLost = true;
  53305. }
  53306. function onContextRestore( /* event */ ) {
  53307. log( 'WebGLRenderer: Context Restored.' );
  53308. _isContextLost = false;
  53309. const infoAutoReset = info.autoReset;
  53310. const shadowMapEnabled = shadowMap.enabled;
  53311. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53312. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53313. const shadowMapType = shadowMap.type;
  53314. initGLContext();
  53315. info.autoReset = infoAutoReset;
  53316. shadowMap.enabled = shadowMapEnabled;
  53317. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53318. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53319. shadowMap.type = shadowMapType;
  53320. }
  53321. function onContextCreationError( event ) {
  53322. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53323. }
  53324. function onMaterialDispose( event ) {
  53325. const material = event.target;
  53326. material.removeEventListener( 'dispose', onMaterialDispose );
  53327. deallocateMaterial( material );
  53328. }
  53329. // Buffer deallocation
  53330. function deallocateMaterial( material ) {
  53331. releaseMaterialProgramReferences( material );
  53332. properties.remove( material );
  53333. }
  53334. function releaseMaterialProgramReferences( material ) {
  53335. const programs = properties.get( material ).programs;
  53336. if ( programs !== undefined ) {
  53337. programs.forEach( function ( program ) {
  53338. programCache.releaseProgram( program );
  53339. } );
  53340. if ( material.isShaderMaterial ) {
  53341. programCache.releaseShaderCache( material );
  53342. }
  53343. }
  53344. }
  53345. // Buffer rendering
  53346. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53347. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53348. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53349. const program = setProgram( camera, scene, geometry, material, object );
  53350. state.setMaterial( material, frontFaceCW );
  53351. //
  53352. let index = geometry.index;
  53353. let rangeFactor = 1;
  53354. if ( material.wireframe === true ) {
  53355. index = geometries.getWireframeAttribute( geometry );
  53356. if ( index === undefined ) return;
  53357. rangeFactor = 2;
  53358. }
  53359. //
  53360. const drawRange = geometry.drawRange;
  53361. const position = geometry.attributes.position;
  53362. let drawStart = drawRange.start * rangeFactor;
  53363. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53364. if ( group !== null ) {
  53365. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53366. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53367. }
  53368. if ( index !== null ) {
  53369. drawStart = Math.max( drawStart, 0 );
  53370. drawEnd = Math.min( drawEnd, index.count );
  53371. } else if ( position !== undefined && position !== null ) {
  53372. drawStart = Math.max( drawStart, 0 );
  53373. drawEnd = Math.min( drawEnd, position.count );
  53374. }
  53375. const drawCount = drawEnd - drawStart;
  53376. if ( drawCount < 0 || drawCount === Infinity ) return;
  53377. //
  53378. bindingStates.setup( object, material, program, geometry, index );
  53379. let attribute;
  53380. let renderer = bufferRenderer;
  53381. if ( index !== null ) {
  53382. attribute = attributes.get( index );
  53383. renderer = indexedBufferRenderer;
  53384. renderer.setIndex( attribute );
  53385. }
  53386. //
  53387. if ( object.isMesh ) {
  53388. if ( material.wireframe === true ) {
  53389. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53390. renderer.setMode( _gl.LINES );
  53391. } else {
  53392. renderer.setMode( _gl.TRIANGLES );
  53393. }
  53394. } else if ( object.isLine ) {
  53395. let lineWidth = material.linewidth;
  53396. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53397. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53398. if ( object.isLineSegments ) {
  53399. renderer.setMode( _gl.LINES );
  53400. } else if ( object.isLineLoop ) {
  53401. renderer.setMode( _gl.LINE_LOOP );
  53402. } else {
  53403. renderer.setMode( _gl.LINE_STRIP );
  53404. }
  53405. } else if ( object.isPoints ) {
  53406. renderer.setMode( _gl.POINTS );
  53407. } else if ( object.isSprite ) {
  53408. renderer.setMode( _gl.TRIANGLES );
  53409. }
  53410. if ( object.isBatchedMesh ) {
  53411. if ( object._multiDrawInstances !== null ) {
  53412. // @deprecated, r174
  53413. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53414. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53415. } else {
  53416. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53417. const starts = object._multiDrawStarts;
  53418. const counts = object._multiDrawCounts;
  53419. const drawCount = object._multiDrawCount;
  53420. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53421. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53422. for ( let i = 0; i < drawCount; i ++ ) {
  53423. uniforms.setValue( _gl, '_gl_DrawID', i );
  53424. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53425. }
  53426. } else {
  53427. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53428. }
  53429. }
  53430. } else if ( object.isInstancedMesh ) {
  53431. renderer.renderInstances( drawStart, drawCount, object.count );
  53432. } else if ( geometry.isInstancedBufferGeometry ) {
  53433. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53434. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53435. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53436. } else {
  53437. renderer.render( drawStart, drawCount );
  53438. }
  53439. };
  53440. // Compile
  53441. function prepareMaterial( material, scene, object ) {
  53442. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53443. material.side = BackSide;
  53444. material.needsUpdate = true;
  53445. getProgram( material, scene, object );
  53446. material.side = FrontSide;
  53447. material.needsUpdate = true;
  53448. getProgram( material, scene, object );
  53449. material.side = DoubleSide;
  53450. } else {
  53451. getProgram( material, scene, object );
  53452. }
  53453. }
  53454. /**
  53455. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53456. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53457. * optional parameter for applying the target scene.
  53458. *
  53459. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53460. *
  53461. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53462. * @param {Camera} camera - The camera.
  53463. * @param {?Scene} [targetScene=null] - The target scene.
  53464. * @return {Set<Material>} The precompiled materials.
  53465. */
  53466. this.compile = function ( scene, camera, targetScene = null ) {
  53467. if ( targetScene === null ) targetScene = scene;
  53468. currentRenderState = renderStates.get( targetScene );
  53469. currentRenderState.init( camera );
  53470. renderStateStack.push( currentRenderState );
  53471. // gather lights from both the target scene and the new object that will be added to the scene.
  53472. targetScene.traverseVisible( function ( object ) {
  53473. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53474. currentRenderState.pushLight( object );
  53475. if ( object.castShadow ) {
  53476. currentRenderState.pushShadow( object );
  53477. }
  53478. }
  53479. } );
  53480. if ( scene !== targetScene ) {
  53481. scene.traverseVisible( function ( object ) {
  53482. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53483. currentRenderState.pushLight( object );
  53484. if ( object.castShadow ) {
  53485. currentRenderState.pushShadow( object );
  53486. }
  53487. }
  53488. } );
  53489. }
  53490. currentRenderState.setupLights();
  53491. // Only initialize materials in the new scene, not the targetScene.
  53492. const materials = new Set();
  53493. scene.traverse( function ( object ) {
  53494. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53495. return;
  53496. }
  53497. const material = object.material;
  53498. if ( material ) {
  53499. if ( Array.isArray( material ) ) {
  53500. for ( let i = 0; i < material.length; i ++ ) {
  53501. const material2 = material[ i ];
  53502. prepareMaterial( material2, targetScene, object );
  53503. materials.add( material2 );
  53504. }
  53505. } else {
  53506. prepareMaterial( material, targetScene, object );
  53507. materials.add( material );
  53508. }
  53509. }
  53510. } );
  53511. currentRenderState = renderStateStack.pop();
  53512. return materials;
  53513. };
  53514. // compileAsync
  53515. /**
  53516. * Asynchronous version of {@link WebGLRenderer#compile}.
  53517. *
  53518. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53519. * it is recommended to use this version of `compile()` whenever possible.
  53520. *
  53521. * @async
  53522. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53523. * @param {Camera} camera - The camera.
  53524. * @param {?Scene} [targetScene=null] - The target scene.
  53525. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53526. */
  53527. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53528. const materials = this.compile( scene, camera, targetScene );
  53529. // Wait for all the materials in the new object to indicate that they're
  53530. // ready to be used before resolving the promise.
  53531. return new Promise( ( resolve ) => {
  53532. function checkMaterialsReady() {
  53533. materials.forEach( function ( material ) {
  53534. const materialProperties = properties.get( material );
  53535. const program = materialProperties.currentProgram;
  53536. if ( program.isReady() ) {
  53537. // remove any programs that report they're ready to use from the list
  53538. materials.delete( material );
  53539. }
  53540. } );
  53541. // once the list of compiling materials is empty, call the callback
  53542. if ( materials.size === 0 ) {
  53543. resolve( scene );
  53544. return;
  53545. }
  53546. // if some materials are still not ready, wait a bit and check again
  53547. setTimeout( checkMaterialsReady, 10 );
  53548. }
  53549. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53550. // If we can check the compilation status of the materials without
  53551. // blocking then do so right away.
  53552. checkMaterialsReady();
  53553. } else {
  53554. // Otherwise start by waiting a bit to give the materials we just
  53555. // initialized a chance to finish.
  53556. setTimeout( checkMaterialsReady, 10 );
  53557. }
  53558. } );
  53559. };
  53560. // Animation Loop
  53561. let onAnimationFrameCallback = null;
  53562. function onAnimationFrame( time ) {
  53563. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53564. }
  53565. function onXRSessionStart() {
  53566. animation.stop();
  53567. }
  53568. function onXRSessionEnd() {
  53569. animation.start();
  53570. }
  53571. const animation = new WebGLAnimation();
  53572. animation.setAnimationLoop( onAnimationFrame );
  53573. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53574. /**
  53575. * Applications are advised to always define the animation loop
  53576. * with this method and not manually with `requestAnimationFrame()`
  53577. * for best compatibility.
  53578. *
  53579. * @param {?onAnimationCallback} callback - The application's animation loop.
  53580. */
  53581. this.setAnimationLoop = function ( callback ) {
  53582. onAnimationFrameCallback = callback;
  53583. xr.setAnimationLoop( callback );
  53584. ( callback === null ) ? animation.stop() : animation.start();
  53585. };
  53586. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53587. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53588. // Rendering
  53589. /**
  53590. * Renders the given scene (or other type of 3D object) using the given camera.
  53591. *
  53592. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53593. * or to the canvas as usual.
  53594. *
  53595. * By default render buffers are cleared before rendering but you can prevent
  53596. * this by setting the property `autoClear` to `false`. If you want to prevent
  53597. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53598. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53599. *
  53600. * @param {Object3D} scene - The scene to render.
  53601. * @param {Camera} camera - The camera.
  53602. */
  53603. this.render = function ( scene, camera ) {
  53604. if ( camera !== undefined && camera.isCamera !== true ) {
  53605. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53606. return;
  53607. }
  53608. if ( _isContextLost === true ) return;
  53609. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53610. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53611. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53612. // update scene graph
  53613. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53614. // update camera matrices and frustum
  53615. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53616. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53617. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53618. camera = xr.getCamera(); // use XR camera for rendering
  53619. }
  53620. //
  53621. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53622. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53623. currentRenderState.init( camera );
  53624. renderStateStack.push( currentRenderState );
  53625. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53626. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53627. _localClippingEnabled = this.localClippingEnabled;
  53628. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53629. currentRenderList = renderLists.get( scene, renderListStack.length );
  53630. currentRenderList.init();
  53631. renderListStack.push( currentRenderList );
  53632. if ( xr.enabled === true && xr.isPresenting === true ) {
  53633. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53634. if ( depthSensingMesh !== null ) {
  53635. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53636. }
  53637. }
  53638. projectObject( scene, camera, 0, _this.sortObjects );
  53639. currentRenderList.finish();
  53640. if ( _this.sortObjects === true ) {
  53641. currentRenderList.sort( _opaqueSort, _transparentSort );
  53642. }
  53643. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53644. if ( _renderBackground ) {
  53645. background.addToRenderList( currentRenderList, scene );
  53646. }
  53647. //
  53648. this.info.render.frame ++;
  53649. if ( _clippingEnabled === true ) clipping.beginShadows();
  53650. const shadowsArray = currentRenderState.state.shadowsArray;
  53651. shadowMap.render( shadowsArray, scene, camera );
  53652. if ( _clippingEnabled === true ) clipping.endShadows();
  53653. //
  53654. if ( this.info.autoReset === true ) this.info.reset();
  53655. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53656. const skipSceneRender = useOutput && output.hasRenderPass();
  53657. if ( skipSceneRender === false ) {
  53658. const opaqueObjects = currentRenderList.opaque;
  53659. const transmissiveObjects = currentRenderList.transmissive;
  53660. currentRenderState.setupLights();
  53661. if ( camera.isArrayCamera ) {
  53662. const cameras = camera.cameras;
  53663. if ( transmissiveObjects.length > 0 ) {
  53664. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53665. const camera2 = cameras[ i ];
  53666. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53667. }
  53668. }
  53669. if ( _renderBackground ) background.render( scene );
  53670. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53671. const camera2 = cameras[ i ];
  53672. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53673. }
  53674. } else {
  53675. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53676. if ( _renderBackground ) background.render( scene );
  53677. renderScene( currentRenderList, scene, camera );
  53678. }
  53679. }
  53680. //
  53681. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53682. // resolve multisample renderbuffers to a single-sample texture if necessary
  53683. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53684. // Generate mipmap if we're using any kind of mipmap filtering
  53685. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53686. }
  53687. // copy from internal render target to canvas using fullscreen quad
  53688. if ( useOutput ) {
  53689. output.end( _this );
  53690. }
  53691. //
  53692. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53693. // _gl.finish();
  53694. bindingStates.resetDefaultState();
  53695. _currentMaterialId = -1;
  53696. _currentCamera = null;
  53697. renderStateStack.pop();
  53698. if ( renderStateStack.length > 0 ) {
  53699. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53700. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53701. } else {
  53702. currentRenderState = null;
  53703. }
  53704. renderListStack.pop();
  53705. if ( renderListStack.length > 0 ) {
  53706. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53707. } else {
  53708. currentRenderList = null;
  53709. }
  53710. };
  53711. function projectObject( object, camera, groupOrder, sortObjects ) {
  53712. if ( object.visible === false ) return;
  53713. const visible = object.layers.test( camera.layers );
  53714. if ( visible ) {
  53715. if ( object.isGroup ) {
  53716. groupOrder = object.renderOrder;
  53717. } else if ( object.isLOD ) {
  53718. if ( object.autoUpdate === true ) object.update( camera );
  53719. } else if ( object.isLight ) {
  53720. currentRenderState.pushLight( object );
  53721. if ( object.castShadow ) {
  53722. currentRenderState.pushShadow( object );
  53723. }
  53724. } else if ( object.isSprite ) {
  53725. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53726. if ( sortObjects ) {
  53727. _vector4.setFromMatrixPosition( object.matrixWorld )
  53728. .applyMatrix4( _projScreenMatrix );
  53729. }
  53730. const geometry = objects.update( object );
  53731. const material = object.material;
  53732. if ( material.visible ) {
  53733. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53734. }
  53735. }
  53736. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53737. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53738. const geometry = objects.update( object );
  53739. const material = object.material;
  53740. if ( sortObjects ) {
  53741. if ( object.boundingSphere !== undefined ) {
  53742. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53743. _vector4.copy( object.boundingSphere.center );
  53744. } else {
  53745. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53746. _vector4.copy( geometry.boundingSphere.center );
  53747. }
  53748. _vector4
  53749. .applyMatrix4( object.matrixWorld )
  53750. .applyMatrix4( _projScreenMatrix );
  53751. }
  53752. if ( Array.isArray( material ) ) {
  53753. const groups = geometry.groups;
  53754. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53755. const group = groups[ i ];
  53756. const groupMaterial = material[ group.materialIndex ];
  53757. if ( groupMaterial && groupMaterial.visible ) {
  53758. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53759. }
  53760. }
  53761. } else if ( material.visible ) {
  53762. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53763. }
  53764. }
  53765. }
  53766. }
  53767. const children = object.children;
  53768. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53769. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53770. }
  53771. }
  53772. function renderScene( currentRenderList, scene, camera, viewport ) {
  53773. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53774. currentRenderState.setupLightsView( camera );
  53775. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53776. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53777. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53778. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53779. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53780. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53781. state.buffers.depth.setTest( true );
  53782. state.buffers.depth.setMask( true );
  53783. state.buffers.color.setMask( true );
  53784. state.setPolygonOffset( false );
  53785. }
  53786. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53787. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53788. if ( overrideMaterial !== null ) {
  53789. return;
  53790. }
  53791. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53792. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  53793. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53794. generateMipmaps: true,
  53795. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  53796. minFilter: LinearMipmapLinearFilter,
  53797. samples: capabilities.samples,
  53798. stencilBuffer: stencil,
  53799. resolveDepthBuffer: false,
  53800. resolveStencilBuffer: false,
  53801. colorSpace: ColorManagement.workingColorSpace,
  53802. } );
  53803. // debug
  53804. /*
  53805. const geometry = new PlaneGeometry();
  53806. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53807. const mesh = new Mesh( geometry, material );
  53808. scene.add( mesh );
  53809. */
  53810. }
  53811. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53812. const activeViewport = camera.viewport || _currentViewport;
  53813. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53814. //
  53815. const currentRenderTarget = _this.getRenderTarget();
  53816. const currentActiveCubeFace = _this.getActiveCubeFace();
  53817. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53818. _this.setRenderTarget( transmissionRenderTarget );
  53819. _this.getClearColor( _currentClearColor );
  53820. _currentClearAlpha = _this.getClearAlpha();
  53821. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53822. _this.clear();
  53823. if ( _renderBackground ) background.render( scene );
  53824. // Turn off the features which can affect the frag color for opaque objects pass.
  53825. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  53826. const currentToneMapping = _this.toneMapping;
  53827. _this.toneMapping = NoToneMapping;
  53828. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  53829. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  53830. const currentCameraViewport = camera.viewport;
  53831. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  53832. currentRenderState.setupLightsView( camera );
  53833. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53834. renderObjects( opaqueObjects, scene, camera );
  53835. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53836. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53837. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  53838. let renderTargetNeedsUpdate = false;
  53839. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  53840. const renderItem = transmissiveObjects[ i ];
  53841. const { object, geometry, material, group } = renderItem;
  53842. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  53843. const currentSide = material.side;
  53844. material.side = BackSide;
  53845. material.needsUpdate = true;
  53846. renderObject( object, scene, camera, geometry, material, group );
  53847. material.side = currentSide;
  53848. material.needsUpdate = true;
  53849. renderTargetNeedsUpdate = true;
  53850. }
  53851. }
  53852. if ( renderTargetNeedsUpdate === true ) {
  53853. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53854. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53855. }
  53856. }
  53857. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  53858. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  53859. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  53860. _this.toneMapping = currentToneMapping;
  53861. }
  53862. function renderObjects( renderList, scene, camera ) {
  53863. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53864. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  53865. const renderItem = renderList[ i ];
  53866. const { object, geometry, group } = renderItem;
  53867. let material = renderItem.material;
  53868. if ( material.allowOverride === true && overrideMaterial !== null ) {
  53869. material = overrideMaterial;
  53870. }
  53871. if ( object.layers.test( camera.layers ) ) {
  53872. renderObject( object, scene, camera, geometry, material, group );
  53873. }
  53874. }
  53875. }
  53876. function renderObject( object, scene, camera, geometry, material, group ) {
  53877. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  53878. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  53879. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  53880. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  53881. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53882. material.side = BackSide;
  53883. material.needsUpdate = true;
  53884. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53885. material.side = FrontSide;
  53886. material.needsUpdate = true;
  53887. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53888. material.side = DoubleSide;
  53889. } else {
  53890. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53891. }
  53892. object.onAfterRender( _this, scene, camera, geometry, material, group );
  53893. }
  53894. function getProgram( material, scene, object ) {
  53895. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53896. const materialProperties = properties.get( material );
  53897. const lights = currentRenderState.state.lights;
  53898. const shadowsArray = currentRenderState.state.shadowsArray;
  53899. const lightsStateVersion = lights.state.version;
  53900. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  53901. const programCacheKey = programCache.getProgramCacheKey( parameters );
  53902. let programs = materialProperties.programs;
  53903. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  53904. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  53905. materialProperties.fog = scene.fog;
  53906. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  53907. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  53908. if ( programs === undefined ) {
  53909. // new material
  53910. material.addEventListener( 'dispose', onMaterialDispose );
  53911. programs = new Map();
  53912. materialProperties.programs = programs;
  53913. }
  53914. let program = programs.get( programCacheKey );
  53915. if ( program !== undefined ) {
  53916. // early out if program and light state is identical
  53917. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  53918. updateCommonMaterialProperties( material, parameters );
  53919. return program;
  53920. }
  53921. } else {
  53922. parameters.uniforms = programCache.getUniforms( material );
  53923. material.onBeforeCompile( parameters, _this );
  53924. program = programCache.acquireProgram( parameters, programCacheKey );
  53925. programs.set( programCacheKey, program );
  53926. materialProperties.uniforms = parameters.uniforms;
  53927. }
  53928. const uniforms = materialProperties.uniforms;
  53929. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  53930. uniforms.clippingPlanes = clipping.uniform;
  53931. }
  53932. updateCommonMaterialProperties( material, parameters );
  53933. // store the light setup it was created for
  53934. materialProperties.needsLights = materialNeedsLights( material );
  53935. materialProperties.lightsStateVersion = lightsStateVersion;
  53936. if ( materialProperties.needsLights ) {
  53937. // wire up the material to this renderer's lighting state
  53938. uniforms.ambientLightColor.value = lights.state.ambient;
  53939. uniforms.lightProbe.value = lights.state.probe;
  53940. uniforms.directionalLights.value = lights.state.directional;
  53941. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  53942. uniforms.spotLights.value = lights.state.spot;
  53943. uniforms.spotLightShadows.value = lights.state.spotShadow;
  53944. uniforms.rectAreaLights.value = lights.state.rectArea;
  53945. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  53946. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  53947. uniforms.pointLights.value = lights.state.point;
  53948. uniforms.pointLightShadows.value = lights.state.pointShadow;
  53949. uniforms.hemisphereLights.value = lights.state.hemi;
  53950. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53951. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53952. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53953. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53954. // TODO (abelnation): add area lights shadow info to uniforms
  53955. }
  53956. materialProperties.currentProgram = program;
  53957. materialProperties.uniformsList = null;
  53958. return program;
  53959. }
  53960. function getUniformList( materialProperties ) {
  53961. if ( materialProperties.uniformsList === null ) {
  53962. const progUniforms = materialProperties.currentProgram.getUniforms();
  53963. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53964. }
  53965. return materialProperties.uniformsList;
  53966. }
  53967. function updateCommonMaterialProperties( material, parameters ) {
  53968. const materialProperties = properties.get( material );
  53969. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53970. materialProperties.batching = parameters.batching;
  53971. materialProperties.batchingColor = parameters.batchingColor;
  53972. materialProperties.instancing = parameters.instancing;
  53973. materialProperties.instancingColor = parameters.instancingColor;
  53974. materialProperties.instancingMorph = parameters.instancingMorph;
  53975. materialProperties.skinning = parameters.skinning;
  53976. materialProperties.morphTargets = parameters.morphTargets;
  53977. materialProperties.morphNormals = parameters.morphNormals;
  53978. materialProperties.morphColors = parameters.morphColors;
  53979. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53980. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53981. materialProperties.numIntersection = parameters.numClipIntersection;
  53982. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53983. materialProperties.vertexTangents = parameters.vertexTangents;
  53984. materialProperties.toneMapping = parameters.toneMapping;
  53985. }
  53986. function setProgram( camera, scene, geometry, material, object ) {
  53987. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53988. textures.resetTextureUnits();
  53989. const fog = scene.fog;
  53990. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53991. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53992. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53993. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53994. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53995. const morphTargets = !! geometry.morphAttributes.position;
  53996. const morphNormals = !! geometry.morphAttributes.normal;
  53997. const morphColors = !! geometry.morphAttributes.color;
  53998. let toneMapping = NoToneMapping;
  53999. if ( material.toneMapped ) {
  54000. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  54001. toneMapping = _this.toneMapping;
  54002. }
  54003. }
  54004. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  54005. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  54006. const materialProperties = properties.get( material );
  54007. const lights = currentRenderState.state.lights;
  54008. if ( _clippingEnabled === true ) {
  54009. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  54010. const useCache =
  54011. camera === _currentCamera &&
  54012. material.id === _currentMaterialId;
  54013. // we might want to call this function with some ClippingGroup
  54014. // object instead of the material, once it becomes feasible
  54015. // (#8465, #8379)
  54016. clipping.setState( material, camera, useCache );
  54017. }
  54018. }
  54019. //
  54020. let needsProgramChange = false;
  54021. if ( material.version === materialProperties.__version ) {
  54022. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  54023. needsProgramChange = true;
  54024. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  54025. needsProgramChange = true;
  54026. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  54027. needsProgramChange = true;
  54028. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  54029. needsProgramChange = true;
  54030. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  54031. needsProgramChange = true;
  54032. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  54033. needsProgramChange = true;
  54034. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  54035. needsProgramChange = true;
  54036. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  54037. needsProgramChange = true;
  54038. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  54039. needsProgramChange = true;
  54040. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  54041. needsProgramChange = true;
  54042. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  54043. needsProgramChange = true;
  54044. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  54045. needsProgramChange = true;
  54046. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  54047. needsProgramChange = true;
  54048. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  54049. needsProgramChange = true;
  54050. } else if ( materialProperties.envMap !== envMap ) {
  54051. needsProgramChange = true;
  54052. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  54053. needsProgramChange = true;
  54054. } else if ( materialProperties.numClippingPlanes !== undefined &&
  54055. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  54056. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  54057. needsProgramChange = true;
  54058. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  54059. needsProgramChange = true;
  54060. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  54061. needsProgramChange = true;
  54062. } else if ( materialProperties.morphTargets !== morphTargets ) {
  54063. needsProgramChange = true;
  54064. } else if ( materialProperties.morphNormals !== morphNormals ) {
  54065. needsProgramChange = true;
  54066. } else if ( materialProperties.morphColors !== morphColors ) {
  54067. needsProgramChange = true;
  54068. } else if ( materialProperties.toneMapping !== toneMapping ) {
  54069. needsProgramChange = true;
  54070. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  54071. needsProgramChange = true;
  54072. }
  54073. } else {
  54074. needsProgramChange = true;
  54075. materialProperties.__version = material.version;
  54076. }
  54077. //
  54078. let program = materialProperties.currentProgram;
  54079. if ( needsProgramChange === true ) {
  54080. program = getProgram( material, scene, object );
  54081. }
  54082. let refreshProgram = false;
  54083. let refreshMaterial = false;
  54084. let refreshLights = false;
  54085. const p_uniforms = program.getUniforms(),
  54086. m_uniforms = materialProperties.uniforms;
  54087. if ( state.useProgram( program.program ) ) {
  54088. refreshProgram = true;
  54089. refreshMaterial = true;
  54090. refreshLights = true;
  54091. }
  54092. if ( material.id !== _currentMaterialId ) {
  54093. _currentMaterialId = material.id;
  54094. refreshMaterial = true;
  54095. }
  54096. if ( refreshProgram || _currentCamera !== camera ) {
  54097. // common camera uniforms
  54098. const reversedDepthBuffer = state.buffers.depth.getReversed();
  54099. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  54100. camera._reversedDepth = true;
  54101. camera.updateProjectionMatrix();
  54102. }
  54103. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  54104. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  54105. const uCamPos = p_uniforms.map.cameraPosition;
  54106. if ( uCamPos !== undefined ) {
  54107. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  54108. }
  54109. if ( capabilities.logarithmicDepthBuffer ) {
  54110. p_uniforms.setValue( _gl, 'logDepthBufFC',
  54111. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  54112. }
  54113. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  54114. if ( material.isMeshPhongMaterial ||
  54115. material.isMeshToonMaterial ||
  54116. material.isMeshLambertMaterial ||
  54117. material.isMeshBasicMaterial ||
  54118. material.isMeshStandardMaterial ||
  54119. material.isShaderMaterial ) {
  54120. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  54121. }
  54122. if ( _currentCamera !== camera ) {
  54123. _currentCamera = camera;
  54124. // lighting uniforms depend on the camera so enforce an update
  54125. // now, in case this material supports lights - or later, when
  54126. // the next material that does gets activated:
  54127. refreshMaterial = true; // set to true on material change
  54128. refreshLights = true; // remains set until update done
  54129. }
  54130. }
  54131. // Pre-allocate texture units for shadow samplers before setting data textures
  54132. if ( materialProperties.needsLights ) {
  54133. // Set shadow map uniforms first to ensure they get the first texture units
  54134. if ( lights.state.directionalShadowMap.length > 0 ) {
  54135. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  54136. }
  54137. if ( lights.state.spotShadowMap.length > 0 ) {
  54138. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  54139. }
  54140. if ( lights.state.pointShadowMap.length > 0 ) {
  54141. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  54142. }
  54143. }
  54144. // skinning and morph target uniforms must be set even if material didn't change
  54145. // auto-setting of texture unit for bone and morph texture must go before other textures
  54146. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  54147. if ( object.isSkinnedMesh ) {
  54148. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  54149. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  54150. const skeleton = object.skeleton;
  54151. if ( skeleton ) {
  54152. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  54153. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  54154. }
  54155. }
  54156. if ( object.isBatchedMesh ) {
  54157. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  54158. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  54159. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  54160. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  54161. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  54162. if ( object._colorsTexture !== null ) {
  54163. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  54164. }
  54165. }
  54166. const morphAttributes = geometry.morphAttributes;
  54167. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  54168. morphtargets.update( object, geometry, program );
  54169. }
  54170. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  54171. materialProperties.receiveShadow = object.receiveShadow;
  54172. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  54173. }
  54174. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  54175. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  54176. }
  54177. // Set DFG LUT for physically-based materials
  54178. if ( m_uniforms.dfgLUT !== undefined ) {
  54179. m_uniforms.dfgLUT.value = getDFGLUT();
  54180. }
  54181. if ( refreshMaterial ) {
  54182. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  54183. if ( materialProperties.needsLights ) {
  54184. // the current material requires lighting info
  54185. // note: all lighting uniforms are always set correctly
  54186. // they simply reference the renderer's state for their
  54187. // values
  54188. //
  54189. // use the current material's .needsUpdate flags to set
  54190. // the GL state when required
  54191. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  54192. }
  54193. // refresh uniforms common to several materials
  54194. if ( fog && material.fog === true ) {
  54195. materials.refreshFogUniforms( m_uniforms, fog );
  54196. }
  54197. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  54198. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54199. }
  54200. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  54201. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  54202. material.uniformsNeedUpdate = false;
  54203. }
  54204. if ( material.isSpriteMaterial ) {
  54205. p_uniforms.setValue( _gl, 'center', object.center );
  54206. }
  54207. // common matrices
  54208. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  54209. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  54210. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  54211. // UBOs
  54212. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  54213. const groups = material.uniformsGroups;
  54214. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  54215. const group = groups[ i ];
  54216. uniformsGroups.update( group, program );
  54217. uniformsGroups.bind( group, program );
  54218. }
  54219. }
  54220. return program;
  54221. }
  54222. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  54223. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  54224. uniforms.ambientLightColor.needsUpdate = value;
  54225. uniforms.lightProbe.needsUpdate = value;
  54226. uniforms.directionalLights.needsUpdate = value;
  54227. uniforms.directionalLightShadows.needsUpdate = value;
  54228. uniforms.pointLights.needsUpdate = value;
  54229. uniforms.pointLightShadows.needsUpdate = value;
  54230. uniforms.spotLights.needsUpdate = value;
  54231. uniforms.spotLightShadows.needsUpdate = value;
  54232. uniforms.rectAreaLights.needsUpdate = value;
  54233. uniforms.hemisphereLights.needsUpdate = value;
  54234. }
  54235. function materialNeedsLights( material ) {
  54236. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  54237. material.isMeshStandardMaterial || material.isShadowMaterial ||
  54238. ( material.isShaderMaterial && material.lights === true );
  54239. }
  54240. /**
  54241. * Returns the active cube face.
  54242. *
  54243. * @return {number} The active cube face.
  54244. */
  54245. this.getActiveCubeFace = function () {
  54246. return _currentActiveCubeFace;
  54247. };
  54248. /**
  54249. * Returns the active mipmap level.
  54250. *
  54251. * @return {number} The active mipmap level.
  54252. */
  54253. this.getActiveMipmapLevel = function () {
  54254. return _currentActiveMipmapLevel;
  54255. };
  54256. /**
  54257. * Returns the active render target.
  54258. *
  54259. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  54260. * is currently set.
  54261. */
  54262. this.getRenderTarget = function () {
  54263. return _currentRenderTarget;
  54264. };
  54265. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54266. const renderTargetProperties = properties.get( renderTarget );
  54267. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54268. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54269. // The multisample_render_to_texture extension doesn't work properly if there
  54270. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54271. renderTargetProperties.__useRenderToTexture = false;
  54272. }
  54273. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54274. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54275. renderTargetProperties.__hasExternalTextures = true;
  54276. };
  54277. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54278. const renderTargetProperties = properties.get( renderTarget );
  54279. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54280. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54281. };
  54282. const _scratchFrameBuffer = _gl.createFramebuffer();
  54283. /**
  54284. * Sets the active rendertarget.
  54285. *
  54286. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54287. * the canvas is set as the active render target instead.
  54288. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54289. * Indicates the z layer to render in to when using 3D or array render targets.
  54290. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54291. */
  54292. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54293. _currentRenderTarget = renderTarget;
  54294. _currentActiveCubeFace = activeCubeFace;
  54295. _currentActiveMipmapLevel = activeMipmapLevel;
  54296. let framebuffer = null;
  54297. let isCube = false;
  54298. let isRenderTarget3D = false;
  54299. if ( renderTarget ) {
  54300. const renderTargetProperties = properties.get( renderTarget );
  54301. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54302. // Externally-managed framebuffer (e.g. XR)
  54303. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54304. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54305. _currentViewport.copy( renderTarget.viewport );
  54306. _currentScissor.copy( renderTarget.scissor );
  54307. _currentScissorTest = renderTarget.scissorTest;
  54308. state.viewport( _currentViewport );
  54309. state.scissor( _currentScissor );
  54310. state.setScissorTest( _currentScissorTest );
  54311. _currentMaterialId = -1;
  54312. return;
  54313. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54314. textures.setupRenderTarget( renderTarget );
  54315. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54316. // Color and depth texture must be rebound in order for the swapchain to update.
  54317. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54318. } else if ( renderTarget.depthBuffer ) {
  54319. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54320. const depthTexture = renderTarget.depthTexture;
  54321. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54322. // check if the depth texture is compatible
  54323. if (
  54324. depthTexture !== null &&
  54325. properties.has( depthTexture ) &&
  54326. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54327. ) {
  54328. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54329. }
  54330. // Swap the depth buffer to the currently attached one
  54331. textures.setupDepthRenderbuffer( renderTarget );
  54332. }
  54333. }
  54334. const texture = renderTarget.texture;
  54335. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54336. isRenderTarget3D = true;
  54337. }
  54338. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54339. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54340. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54341. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54342. } else {
  54343. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54344. }
  54345. isCube = true;
  54346. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54347. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54348. } else {
  54349. if ( Array.isArray( __webglFramebuffer ) ) {
  54350. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54351. } else {
  54352. framebuffer = __webglFramebuffer;
  54353. }
  54354. }
  54355. _currentViewport.copy( renderTarget.viewport );
  54356. _currentScissor.copy( renderTarget.scissor );
  54357. _currentScissorTest = renderTarget.scissorTest;
  54358. } else {
  54359. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54360. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54361. _currentScissorTest = _scissorTest;
  54362. }
  54363. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54364. // being bound that are different sizes.
  54365. if ( activeMipmapLevel !== 0 ) {
  54366. framebuffer = _scratchFrameBuffer;
  54367. }
  54368. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54369. if ( framebufferBound ) {
  54370. state.drawBuffers( renderTarget, framebuffer );
  54371. }
  54372. state.viewport( _currentViewport );
  54373. state.scissor( _currentScissor );
  54374. state.setScissorTest( _currentScissorTest );
  54375. if ( isCube ) {
  54376. const textureProperties = properties.get( renderTarget.texture );
  54377. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54378. } else if ( isRenderTarget3D ) {
  54379. const layer = activeCubeFace;
  54380. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54381. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54382. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54383. }
  54384. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54385. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54386. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54387. const textureProperties = properties.get( renderTarget.texture );
  54388. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54389. }
  54390. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54391. };
  54392. /**
  54393. * Reads the pixel data from the given render target into the given buffer.
  54394. *
  54395. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54396. * @param {number} x - The `x` coordinate of the copy region's origin.
  54397. * @param {number} y - The `y` coordinate of the copy region's origin.
  54398. * @param {number} width - The width of the copy region.
  54399. * @param {number} height - The height of the copy region.
  54400. * @param {TypedArray} buffer - The result buffer.
  54401. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54402. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54403. */
  54404. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54405. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54406. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54407. return;
  54408. }
  54409. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54410. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54411. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54412. }
  54413. if ( framebuffer ) {
  54414. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54415. try {
  54416. const texture = renderTarget.textures[ textureIndex ];
  54417. const textureFormat = texture.format;
  54418. const textureType = texture.type;
  54419. // when using MRT, select the correct color buffer for the subsequent read command
  54420. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54421. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54422. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54423. return;
  54424. }
  54425. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54426. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54427. return;
  54428. }
  54429. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54430. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54431. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54432. }
  54433. } finally {
  54434. // restore framebuffer of current render target if necessary
  54435. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54436. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54437. }
  54438. }
  54439. };
  54440. /**
  54441. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54442. *
  54443. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54444. *
  54445. * @async
  54446. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54447. * @param {number} x - The `x` coordinate of the copy region's origin.
  54448. * @param {number} y - The `y` coordinate of the copy region's origin.
  54449. * @param {number} width - The width of the copy region.
  54450. * @param {number} height - The height of the copy region.
  54451. * @param {TypedArray} buffer - The result buffer.
  54452. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54453. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54454. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54455. */
  54456. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54457. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54458. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54459. }
  54460. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54461. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54462. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54463. }
  54464. if ( framebuffer ) {
  54465. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54466. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54467. // set the active frame buffer to the one we want to read
  54468. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54469. const texture = renderTarget.textures[ textureIndex ];
  54470. const textureFormat = texture.format;
  54471. const textureType = texture.type;
  54472. // when using MRT, select the correct color buffer for the subsequent read command
  54473. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54474. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54475. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54476. }
  54477. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54478. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54479. }
  54480. const glBuffer = _gl.createBuffer();
  54481. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54482. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54483. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54484. // reset the frame buffer to the currently set buffer before waiting
  54485. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54486. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54487. // check if the commands have finished every 8 ms
  54488. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54489. _gl.flush();
  54490. await probeAsync( _gl, sync, 4 );
  54491. // read the data and delete the buffer
  54492. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54493. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54494. _gl.deleteBuffer( glBuffer );
  54495. _gl.deleteSync( sync );
  54496. return buffer;
  54497. } else {
  54498. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54499. }
  54500. }
  54501. };
  54502. /**
  54503. * Copies pixels from the current bound framebuffer into the given texture.
  54504. *
  54505. * @param {FramebufferTexture} texture - The texture.
  54506. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54507. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54508. */
  54509. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54510. const levelScale = Math.pow( 2, - level );
  54511. const width = Math.floor( texture.image.width * levelScale );
  54512. const height = Math.floor( texture.image.height * levelScale );
  54513. const x = position !== null ? position.x : 0;
  54514. const y = position !== null ? position.y : 0;
  54515. textures.setTexture2D( texture, 0 );
  54516. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54517. state.unbindTexture();
  54518. };
  54519. const _srcFramebuffer = _gl.createFramebuffer();
  54520. const _dstFramebuffer = _gl.createFramebuffer();
  54521. /**
  54522. * Copies data of the given source texture into a destination texture.
  54523. *
  54524. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54525. * {@link WebGLRenderer#initRenderTarget}.
  54526. *
  54527. * @param {Texture} srcTexture - The source texture.
  54528. * @param {Texture} dstTexture - The destination texture.
  54529. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54530. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54531. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54532. * @param {?number} [dstLevel=0] - The destination mipmap level.
  54533. */
  54534. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  54535. // gather the necessary dimensions to copy
  54536. let width, height, depth, minX, minY, minZ;
  54537. let dstX, dstY, dstZ;
  54538. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54539. if ( srcRegion !== null ) {
  54540. width = srcRegion.max.x - srcRegion.min.x;
  54541. height = srcRegion.max.y - srcRegion.min.y;
  54542. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54543. minX = srcRegion.min.x;
  54544. minY = srcRegion.min.y;
  54545. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54546. } else {
  54547. const levelScale = Math.pow( 2, - srcLevel );
  54548. width = Math.floor( image.width * levelScale );
  54549. height = Math.floor( image.height * levelScale );
  54550. if ( srcTexture.isDataArrayTexture ) {
  54551. depth = image.depth;
  54552. } else if ( srcTexture.isData3DTexture ) {
  54553. depth = Math.floor( image.depth * levelScale );
  54554. } else {
  54555. depth = 1;
  54556. }
  54557. minX = 0;
  54558. minY = 0;
  54559. minZ = 0;
  54560. }
  54561. if ( dstPosition !== null ) {
  54562. dstX = dstPosition.x;
  54563. dstY = dstPosition.y;
  54564. dstZ = dstPosition.z;
  54565. } else {
  54566. dstX = 0;
  54567. dstY = 0;
  54568. dstZ = 0;
  54569. }
  54570. // Set up the destination target
  54571. const glFormat = utils.convert( dstTexture.format );
  54572. const glType = utils.convert( dstTexture.type );
  54573. let glTarget;
  54574. if ( dstTexture.isData3DTexture ) {
  54575. textures.setTexture3D( dstTexture, 0 );
  54576. glTarget = _gl.TEXTURE_3D;
  54577. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54578. textures.setTexture2DArray( dstTexture, 0 );
  54579. glTarget = _gl.TEXTURE_2D_ARRAY;
  54580. } else {
  54581. textures.setTexture2D( dstTexture, 0 );
  54582. glTarget = _gl.TEXTURE_2D;
  54583. }
  54584. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54585. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54586. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54587. // used for copying data from cpu
  54588. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54589. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54590. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54591. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54592. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54593. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54594. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54595. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54596. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54597. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54598. // set up the src texture
  54599. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54600. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54601. if ( srcTexture.isDepthTexture ) {
  54602. const srcTextureProperties = properties.get( srcTexture );
  54603. const dstTextureProperties = properties.get( dstTexture );
  54604. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54605. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54606. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54607. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54608. for ( let i = 0; i < depth; i ++ ) {
  54609. // if the source or destination are a 3d target then a layer needs to be bound
  54610. if ( isSrc3D ) {
  54611. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54612. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54613. }
  54614. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54615. }
  54616. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54617. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54618. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54619. // get the appropriate frame buffers
  54620. const srcTextureProperties = properties.get( srcTexture );
  54621. const dstTextureProperties = properties.get( dstTexture );
  54622. // bind the frame buffer targets
  54623. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54624. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54625. for ( let i = 0; i < depth; i ++ ) {
  54626. // assign the correct layers and mip maps to the frame buffers
  54627. if ( isSrc3D ) {
  54628. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54629. } else {
  54630. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54631. }
  54632. if ( isDst3D ) {
  54633. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54634. } else {
  54635. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54636. }
  54637. // copy the data using the fastest function that can achieve the copy
  54638. if ( srcLevel !== 0 ) {
  54639. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54640. } else if ( isDst3D ) {
  54641. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54642. } else {
  54643. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54644. }
  54645. }
  54646. // unbind read, draw buffers
  54647. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54648. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54649. } else {
  54650. if ( isDst3D ) {
  54651. // copy data into the 3d texture
  54652. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54653. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54654. } else if ( dstTexture.isCompressedArrayTexture ) {
  54655. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54656. } else {
  54657. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54658. }
  54659. } else {
  54660. // copy data into the 2d texture
  54661. if ( srcTexture.isDataTexture ) {
  54662. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54663. } else if ( srcTexture.isCompressedTexture ) {
  54664. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54665. } else {
  54666. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54667. }
  54668. }
  54669. }
  54670. // reset values
  54671. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54672. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54673. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54674. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54675. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54676. // Generate mipmaps only when copying level 0
  54677. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54678. _gl.generateMipmap( glTarget );
  54679. }
  54680. state.unbindTexture();
  54681. };
  54682. /**
  54683. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54684. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54685. * rendered to.
  54686. *
  54687. * @param {WebGLRenderTarget} target - The render target.
  54688. */
  54689. this.initRenderTarget = function ( target ) {
  54690. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54691. textures.setupRenderTarget( target );
  54692. }
  54693. };
  54694. /**
  54695. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54696. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54697. *
  54698. * @param {Texture} texture - The texture.
  54699. */
  54700. this.initTexture = function ( texture ) {
  54701. if ( texture.isCubeTexture ) {
  54702. textures.setTextureCube( texture, 0 );
  54703. } else if ( texture.isData3DTexture ) {
  54704. textures.setTexture3D( texture, 0 );
  54705. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54706. textures.setTexture2DArray( texture, 0 );
  54707. } else {
  54708. textures.setTexture2D( texture, 0 );
  54709. }
  54710. state.unbindTexture();
  54711. };
  54712. /**
  54713. * Can be used to reset the internal WebGL state. This method is mostly
  54714. * relevant for applications which share a single WebGL context across
  54715. * multiple WebGL libraries.
  54716. */
  54717. this.resetState = function () {
  54718. _currentActiveCubeFace = 0;
  54719. _currentActiveMipmapLevel = 0;
  54720. _currentRenderTarget = null;
  54721. state.reset();
  54722. bindingStates.reset();
  54723. };
  54724. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54725. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54726. }
  54727. }
  54728. /**
  54729. * Defines the coordinate system of the renderer.
  54730. *
  54731. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54732. *
  54733. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54734. * @default WebGLCoordinateSystem
  54735. * @readonly
  54736. */
  54737. get coordinateSystem() {
  54738. return WebGLCoordinateSystem;
  54739. }
  54740. /**
  54741. * Defines the output color space of the renderer.
  54742. *
  54743. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54744. * @default SRGBColorSpace
  54745. */
  54746. get outputColorSpace() {
  54747. return this._outputColorSpace;
  54748. }
  54749. set outputColorSpace( colorSpace ) {
  54750. this._outputColorSpace = colorSpace;
  54751. const gl = this.getContext();
  54752. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54753. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54754. }
  54755. }
  54756. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54757. exports.AddEquation = AddEquation;
  54758. exports.AddOperation = AddOperation;
  54759. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54760. exports.AdditiveBlending = AdditiveBlending;
  54761. exports.AgXToneMapping = AgXToneMapping;
  54762. exports.AlphaFormat = AlphaFormat;
  54763. exports.AlwaysCompare = AlwaysCompare;
  54764. exports.AlwaysDepth = AlwaysDepth;
  54765. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54766. exports.AmbientLight = AmbientLight;
  54767. exports.AnimationAction = AnimationAction;
  54768. exports.AnimationClip = AnimationClip;
  54769. exports.AnimationLoader = AnimationLoader;
  54770. exports.AnimationMixer = AnimationMixer;
  54771. exports.AnimationObjectGroup = AnimationObjectGroup;
  54772. exports.AnimationUtils = AnimationUtils;
  54773. exports.ArcCurve = ArcCurve;
  54774. exports.ArrayCamera = ArrayCamera;
  54775. exports.ArrowHelper = ArrowHelper;
  54776. exports.AttachedBindMode = AttachedBindMode;
  54777. exports.Audio = Audio;
  54778. exports.AudioAnalyser = AudioAnalyser;
  54779. exports.AudioContext = AudioContext;
  54780. exports.AudioListener = AudioListener;
  54781. exports.AudioLoader = AudioLoader;
  54782. exports.AxesHelper = AxesHelper;
  54783. exports.BackSide = BackSide;
  54784. exports.BasicDepthPacking = BasicDepthPacking;
  54785. exports.BasicShadowMap = BasicShadowMap;
  54786. exports.BatchedMesh = BatchedMesh;
  54787. exports.Bone = Bone;
  54788. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54789. exports.Box2 = Box2;
  54790. exports.Box3 = Box3;
  54791. exports.Box3Helper = Box3Helper;
  54792. exports.BoxGeometry = BoxGeometry;
  54793. exports.BoxHelper = BoxHelper;
  54794. exports.BufferAttribute = BufferAttribute;
  54795. exports.BufferGeometry = BufferGeometry;
  54796. exports.BufferGeometryLoader = BufferGeometryLoader;
  54797. exports.ByteType = ByteType;
  54798. exports.Cache = Cache;
  54799. exports.Camera = Camera;
  54800. exports.CameraHelper = CameraHelper;
  54801. exports.CanvasTexture = CanvasTexture;
  54802. exports.CapsuleGeometry = CapsuleGeometry;
  54803. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54804. exports.CineonToneMapping = CineonToneMapping;
  54805. exports.CircleGeometry = CircleGeometry;
  54806. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54807. exports.Clock = Clock;
  54808. exports.Color = Color;
  54809. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54810. exports.ColorManagement = ColorManagement;
  54811. exports.Compatibility = Compatibility;
  54812. exports.CompressedArrayTexture = CompressedArrayTexture;
  54813. exports.CompressedCubeTexture = CompressedCubeTexture;
  54814. exports.CompressedTexture = CompressedTexture;
  54815. exports.CompressedTextureLoader = CompressedTextureLoader;
  54816. exports.ConeGeometry = ConeGeometry;
  54817. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54818. exports.ConstantColorFactor = ConstantColorFactor;
  54819. exports.Controls = Controls;
  54820. exports.CubeCamera = CubeCamera;
  54821. exports.CubeDepthTexture = CubeDepthTexture;
  54822. exports.CubeReflectionMapping = CubeReflectionMapping;
  54823. exports.CubeRefractionMapping = CubeRefractionMapping;
  54824. exports.CubeTexture = CubeTexture;
  54825. exports.CubeTextureLoader = CubeTextureLoader;
  54826. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  54827. exports.CubicBezierCurve = CubicBezierCurve;
  54828. exports.CubicBezierCurve3 = CubicBezierCurve3;
  54829. exports.CubicInterpolant = CubicInterpolant;
  54830. exports.CullFaceBack = CullFaceBack;
  54831. exports.CullFaceFront = CullFaceFront;
  54832. exports.CullFaceFrontBack = CullFaceFrontBack;
  54833. exports.CullFaceNone = CullFaceNone;
  54834. exports.Curve = Curve;
  54835. exports.CurvePath = CurvePath;
  54836. exports.CustomBlending = CustomBlending;
  54837. exports.CustomToneMapping = CustomToneMapping;
  54838. exports.CylinderGeometry = CylinderGeometry;
  54839. exports.Cylindrical = Cylindrical;
  54840. exports.Data3DTexture = Data3DTexture;
  54841. exports.DataArrayTexture = DataArrayTexture;
  54842. exports.DataTexture = DataTexture;
  54843. exports.DataTextureLoader = DataTextureLoader;
  54844. exports.DataUtils = DataUtils;
  54845. exports.DecrementStencilOp = DecrementStencilOp;
  54846. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  54847. exports.DefaultLoadingManager = DefaultLoadingManager;
  54848. exports.DepthFormat = DepthFormat;
  54849. exports.DepthStencilFormat = DepthStencilFormat;
  54850. exports.DepthTexture = DepthTexture;
  54851. exports.DetachedBindMode = DetachedBindMode;
  54852. exports.DirectionalLight = DirectionalLight;
  54853. exports.DirectionalLightHelper = DirectionalLightHelper;
  54854. exports.DiscreteInterpolant = DiscreteInterpolant;
  54855. exports.DodecahedronGeometry = DodecahedronGeometry;
  54856. exports.DoubleSide = DoubleSide;
  54857. exports.DstAlphaFactor = DstAlphaFactor;
  54858. exports.DstColorFactor = DstColorFactor;
  54859. exports.DynamicCopyUsage = DynamicCopyUsage;
  54860. exports.DynamicDrawUsage = DynamicDrawUsage;
  54861. exports.DynamicReadUsage = DynamicReadUsage;
  54862. exports.EdgesGeometry = EdgesGeometry;
  54863. exports.EllipseCurve = EllipseCurve;
  54864. exports.EqualCompare = EqualCompare;
  54865. exports.EqualDepth = EqualDepth;
  54866. exports.EqualStencilFunc = EqualStencilFunc;
  54867. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  54868. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  54869. exports.Euler = Euler;
  54870. exports.EventDispatcher = EventDispatcher;
  54871. exports.ExternalTexture = ExternalTexture;
  54872. exports.ExtrudeGeometry = ExtrudeGeometry;
  54873. exports.FileLoader = FileLoader;
  54874. exports.Float16BufferAttribute = Float16BufferAttribute;
  54875. exports.Float32BufferAttribute = Float32BufferAttribute;
  54876. exports.FloatType = FloatType;
  54877. exports.Fog = Fog;
  54878. exports.FogExp2 = FogExp2;
  54879. exports.FramebufferTexture = FramebufferTexture;
  54880. exports.FrontSide = FrontSide;
  54881. exports.Frustum = Frustum;
  54882. exports.FrustumArray = FrustumArray;
  54883. exports.GLBufferAttribute = GLBufferAttribute;
  54884. exports.GLSL1 = GLSL1;
  54885. exports.GLSL3 = GLSL3;
  54886. exports.GreaterCompare = GreaterCompare;
  54887. exports.GreaterDepth = GreaterDepth;
  54888. exports.GreaterEqualCompare = GreaterEqualCompare;
  54889. exports.GreaterEqualDepth = GreaterEqualDepth;
  54890. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  54891. exports.GreaterStencilFunc = GreaterStencilFunc;
  54892. exports.GridHelper = GridHelper;
  54893. exports.Group = Group;
  54894. exports.HalfFloatType = HalfFloatType;
  54895. exports.HemisphereLight = HemisphereLight;
  54896. exports.HemisphereLightHelper = HemisphereLightHelper;
  54897. exports.IcosahedronGeometry = IcosahedronGeometry;
  54898. exports.ImageBitmapLoader = ImageBitmapLoader;
  54899. exports.ImageLoader = ImageLoader;
  54900. exports.ImageUtils = ImageUtils;
  54901. exports.IncrementStencilOp = IncrementStencilOp;
  54902. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  54903. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  54904. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  54905. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  54906. exports.InstancedMesh = InstancedMesh;
  54907. exports.Int16BufferAttribute = Int16BufferAttribute;
  54908. exports.Int32BufferAttribute = Int32BufferAttribute;
  54909. exports.Int8BufferAttribute = Int8BufferAttribute;
  54910. exports.IntType = IntType;
  54911. exports.InterleavedBuffer = InterleavedBuffer;
  54912. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  54913. exports.Interpolant = Interpolant;
  54914. exports.InterpolateDiscrete = InterpolateDiscrete;
  54915. exports.InterpolateLinear = InterpolateLinear;
  54916. exports.InterpolateSmooth = InterpolateSmooth;
  54917. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  54918. exports.InterpolationSamplingType = InterpolationSamplingType;
  54919. exports.InvertStencilOp = InvertStencilOp;
  54920. exports.KeepStencilOp = KeepStencilOp;
  54921. exports.KeyframeTrack = KeyframeTrack;
  54922. exports.LOD = LOD;
  54923. exports.LatheGeometry = LatheGeometry;
  54924. exports.Layers = Layers;
  54925. exports.LessCompare = LessCompare;
  54926. exports.LessDepth = LessDepth;
  54927. exports.LessEqualCompare = LessEqualCompare;
  54928. exports.LessEqualDepth = LessEqualDepth;
  54929. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  54930. exports.LessStencilFunc = LessStencilFunc;
  54931. exports.Light = Light;
  54932. exports.LightProbe = LightProbe;
  54933. exports.Line = Line;
  54934. exports.Line3 = Line3;
  54935. exports.LineBasicMaterial = LineBasicMaterial;
  54936. exports.LineCurve = LineCurve;
  54937. exports.LineCurve3 = LineCurve3;
  54938. exports.LineDashedMaterial = LineDashedMaterial;
  54939. exports.LineLoop = LineLoop;
  54940. exports.LineSegments = LineSegments;
  54941. exports.LinearFilter = LinearFilter;
  54942. exports.LinearInterpolant = LinearInterpolant;
  54943. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  54944. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  54945. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  54946. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  54947. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  54948. exports.LinearToneMapping = LinearToneMapping;
  54949. exports.LinearTransfer = LinearTransfer;
  54950. exports.Loader = Loader;
  54951. exports.LoaderUtils = LoaderUtils;
  54952. exports.LoadingManager = LoadingManager;
  54953. exports.LoopOnce = LoopOnce;
  54954. exports.LoopPingPong = LoopPingPong;
  54955. exports.LoopRepeat = LoopRepeat;
  54956. exports.MOUSE = MOUSE;
  54957. exports.Material = Material;
  54958. exports.MaterialBlending = MaterialBlending;
  54959. exports.MaterialLoader = MaterialLoader;
  54960. exports.MathUtils = MathUtils;
  54961. exports.Matrix2 = Matrix2;
  54962. exports.Matrix3 = Matrix3;
  54963. exports.Matrix4 = Matrix4;
  54964. exports.MaxEquation = MaxEquation;
  54965. exports.Mesh = Mesh;
  54966. exports.MeshBasicMaterial = MeshBasicMaterial;
  54967. exports.MeshDepthMaterial = MeshDepthMaterial;
  54968. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54969. exports.MeshLambertMaterial = MeshLambertMaterial;
  54970. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54971. exports.MeshNormalMaterial = MeshNormalMaterial;
  54972. exports.MeshPhongMaterial = MeshPhongMaterial;
  54973. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54974. exports.MeshStandardMaterial = MeshStandardMaterial;
  54975. exports.MeshToonMaterial = MeshToonMaterial;
  54976. exports.MinEquation = MinEquation;
  54977. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54978. exports.MixOperation = MixOperation;
  54979. exports.MultiplyBlending = MultiplyBlending;
  54980. exports.MultiplyOperation = MultiplyOperation;
  54981. exports.NearestFilter = NearestFilter;
  54982. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54983. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54984. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54985. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54986. exports.NeutralToneMapping = NeutralToneMapping;
  54987. exports.NeverCompare = NeverCompare;
  54988. exports.NeverDepth = NeverDepth;
  54989. exports.NeverStencilFunc = NeverStencilFunc;
  54990. exports.NoBlending = NoBlending;
  54991. exports.NoColorSpace = NoColorSpace;
  54992. exports.NoNormalPacking = NoNormalPacking;
  54993. exports.NoToneMapping = NoToneMapping;
  54994. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54995. exports.NormalBlending = NormalBlending;
  54996. exports.NormalGAPacking = NormalGAPacking;
  54997. exports.NormalRGPacking = NormalRGPacking;
  54998. exports.NotEqualCompare = NotEqualCompare;
  54999. exports.NotEqualDepth = NotEqualDepth;
  55000. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  55001. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  55002. exports.Object3D = Object3D;
  55003. exports.ObjectLoader = ObjectLoader;
  55004. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  55005. exports.OctahedronGeometry = OctahedronGeometry;
  55006. exports.OneFactor = OneFactor;
  55007. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  55008. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  55009. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  55010. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  55011. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  55012. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  55013. exports.OrthographicCamera = OrthographicCamera;
  55014. exports.PCFShadowMap = PCFShadowMap;
  55015. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  55016. exports.PMREMGenerator = PMREMGenerator;
  55017. exports.Path = Path;
  55018. exports.PerspectiveCamera = PerspectiveCamera;
  55019. exports.Plane = Plane;
  55020. exports.PlaneGeometry = PlaneGeometry;
  55021. exports.PlaneHelper = PlaneHelper;
  55022. exports.PointLight = PointLight;
  55023. exports.PointLightHelper = PointLightHelper;
  55024. exports.Points = Points;
  55025. exports.PointsMaterial = PointsMaterial;
  55026. exports.PolarGridHelper = PolarGridHelper;
  55027. exports.PolyhedronGeometry = PolyhedronGeometry;
  55028. exports.PositionalAudio = PositionalAudio;
  55029. exports.PropertyBinding = PropertyBinding;
  55030. exports.PropertyMixer = PropertyMixer;
  55031. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  55032. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  55033. exports.Quaternion = Quaternion;
  55034. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  55035. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  55036. exports.R11_EAC_Format = R11_EAC_Format;
  55037. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  55038. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  55039. exports.REVISION = REVISION;
  55040. exports.RG11_EAC_Format = RG11_EAC_Format;
  55041. exports.RGBADepthPacking = RGBADepthPacking;
  55042. exports.RGBAFormat = RGBAFormat;
  55043. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  55044. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  55045. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  55046. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  55047. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  55048. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  55049. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  55050. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  55051. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  55052. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  55053. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  55054. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  55055. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  55056. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  55057. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  55058. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  55059. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  55060. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  55061. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  55062. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  55063. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  55064. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  55065. exports.RGBDepthPacking = RGBDepthPacking;
  55066. exports.RGBFormat = RGBFormat;
  55067. exports.RGBIntegerFormat = RGBIntegerFormat;
  55068. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  55069. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  55070. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  55071. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  55072. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  55073. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  55074. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  55075. exports.RGDepthPacking = RGDepthPacking;
  55076. exports.RGFormat = RGFormat;
  55077. exports.RGIntegerFormat = RGIntegerFormat;
  55078. exports.RawShaderMaterial = RawShaderMaterial;
  55079. exports.Ray = Ray;
  55080. exports.Raycaster = Raycaster;
  55081. exports.RectAreaLight = RectAreaLight;
  55082. exports.RedFormat = RedFormat;
  55083. exports.RedIntegerFormat = RedIntegerFormat;
  55084. exports.ReinhardToneMapping = ReinhardToneMapping;
  55085. exports.RenderTarget = RenderTarget;
  55086. exports.RenderTarget3D = RenderTarget3D;
  55087. exports.RepeatWrapping = RepeatWrapping;
  55088. exports.ReplaceStencilOp = ReplaceStencilOp;
  55089. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  55090. exports.RingGeometry = RingGeometry;
  55091. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  55092. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  55093. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  55094. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  55095. exports.SRGBColorSpace = SRGBColorSpace;
  55096. exports.SRGBTransfer = SRGBTransfer;
  55097. exports.Scene = Scene;
  55098. exports.ShaderChunk = ShaderChunk;
  55099. exports.ShaderLib = ShaderLib;
  55100. exports.ShaderMaterial = ShaderMaterial;
  55101. exports.ShadowMaterial = ShadowMaterial;
  55102. exports.Shape = Shape;
  55103. exports.ShapeGeometry = ShapeGeometry;
  55104. exports.ShapePath = ShapePath;
  55105. exports.ShapeUtils = ShapeUtils;
  55106. exports.ShortType = ShortType;
  55107. exports.Skeleton = Skeleton;
  55108. exports.SkeletonHelper = SkeletonHelper;
  55109. exports.SkinnedMesh = SkinnedMesh;
  55110. exports.Source = Source;
  55111. exports.Sphere = Sphere;
  55112. exports.SphereGeometry = SphereGeometry;
  55113. exports.Spherical = Spherical;
  55114. exports.SphericalHarmonics3 = SphericalHarmonics3;
  55115. exports.SplineCurve = SplineCurve;
  55116. exports.SpotLight = SpotLight;
  55117. exports.SpotLightHelper = SpotLightHelper;
  55118. exports.Sprite = Sprite;
  55119. exports.SpriteMaterial = SpriteMaterial;
  55120. exports.SrcAlphaFactor = SrcAlphaFactor;
  55121. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  55122. exports.SrcColorFactor = SrcColorFactor;
  55123. exports.StaticCopyUsage = StaticCopyUsage;
  55124. exports.StaticDrawUsage = StaticDrawUsage;
  55125. exports.StaticReadUsage = StaticReadUsage;
  55126. exports.StereoCamera = StereoCamera;
  55127. exports.StreamCopyUsage = StreamCopyUsage;
  55128. exports.StreamDrawUsage = StreamDrawUsage;
  55129. exports.StreamReadUsage = StreamReadUsage;
  55130. exports.StringKeyframeTrack = StringKeyframeTrack;
  55131. exports.SubtractEquation = SubtractEquation;
  55132. exports.SubtractiveBlending = SubtractiveBlending;
  55133. exports.TOUCH = TOUCH;
  55134. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  55135. exports.TetrahedronGeometry = TetrahedronGeometry;
  55136. exports.Texture = Texture;
  55137. exports.TextureLoader = TextureLoader;
  55138. exports.TextureUtils = TextureUtils;
  55139. exports.Timer = Timer;
  55140. exports.TimestampQuery = TimestampQuery;
  55141. exports.TorusGeometry = TorusGeometry;
  55142. exports.TorusKnotGeometry = TorusKnotGeometry;
  55143. exports.Triangle = Triangle;
  55144. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  55145. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  55146. exports.TrianglesDrawMode = TrianglesDrawMode;
  55147. exports.TubeGeometry = TubeGeometry;
  55148. exports.UVMapping = UVMapping;
  55149. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  55150. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  55151. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  55152. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  55153. exports.Uniform = Uniform;
  55154. exports.UniformsGroup = UniformsGroup;
  55155. exports.UniformsLib = UniformsLib;
  55156. exports.UniformsUtils = UniformsUtils;
  55157. exports.UnsignedByteType = UnsignedByteType;
  55158. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  55159. exports.UnsignedInt248Type = UnsignedInt248Type;
  55160. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  55161. exports.UnsignedIntType = UnsignedIntType;
  55162. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  55163. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  55164. exports.UnsignedShortType = UnsignedShortType;
  55165. exports.VSMShadowMap = VSMShadowMap;
  55166. exports.Vector2 = Vector2;
  55167. exports.Vector3 = Vector3;
  55168. exports.Vector4 = Vector4;
  55169. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  55170. exports.VideoFrameTexture = VideoFrameTexture;
  55171. exports.VideoTexture = VideoTexture;
  55172. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  55173. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  55174. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  55175. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  55176. exports.WebGLRenderTarget = WebGLRenderTarget;
  55177. exports.WebGLRenderer = WebGLRenderer;
  55178. exports.WebGLUtils = WebGLUtils;
  55179. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  55180. exports.WebXRController = WebXRController;
  55181. exports.WireframeGeometry = WireframeGeometry;
  55182. exports.WrapAroundEnding = WrapAroundEnding;
  55183. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  55184. exports.ZeroFactor = ZeroFactor;
  55185. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  55186. exports.ZeroStencilOp = ZeroStencilOp;
  55187. exports.createCanvasElement = createCanvasElement;
  55188. exports.error = error;
  55189. exports.getConsoleFunction = getConsoleFunction;
  55190. exports.log = log;
  55191. exports.setConsoleFunction = setConsoleFunction;
  55192. exports.warn = warn;
  55193. exports.warnOnce = warnOnce;
粤ICP备19079148号