three.cjs 1.9 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '181dev';
  8. /**
  9. * Represents mouse buttons and interaction types in context of controls.
  10. *
  11. * @type {ConstantsMouse}
  12. * @constant
  13. */
  14. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  15. /**
  16. * Represents touch interaction types in context of controls.
  17. *
  18. * @type {ConstantsTouch}
  19. * @constant
  20. */
  21. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  22. /**
  23. * Disables face culling.
  24. *
  25. * @type {number}
  26. * @constant
  27. */
  28. const CullFaceNone = 0;
  29. /**
  30. * Culls back faces.
  31. *
  32. * @type {number}
  33. * @constant
  34. */
  35. const CullFaceBack = 1;
  36. /**
  37. * Culls front faces.
  38. *
  39. * @type {number}
  40. * @constant
  41. */
  42. const CullFaceFront = 2;
  43. /**
  44. * Culls both front and back faces.
  45. *
  46. * @type {number}
  47. * @constant
  48. */
  49. const CullFaceFrontBack = 3;
  50. /**
  51. * Gives unfiltered shadow maps - fastest, but lowest quality.
  52. *
  53. * @type {number}
  54. * @constant
  55. */
  56. const BasicShadowMap = 0;
  57. /**
  58. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  59. *
  60. * @type {number}
  61. * @constant
  62. */
  63. const PCFShadowMap = 1;
  64. /**
  65. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  66. * better soft shadows especially when using low-resolution shadow maps.
  67. *
  68. * @type {number}
  69. * @constant
  70. */
  71. const PCFSoftShadowMap = 2;
  72. /**
  73. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  74. * When using VSMShadowMap all shadow receivers will also cast shadows.
  75. *
  76. * @type {number}
  77. * @constant
  78. */
  79. const VSMShadowMap = 3;
  80. /**
  81. * Only front faces are rendered.
  82. *
  83. * @type {number}
  84. * @constant
  85. */
  86. const FrontSide = 0;
  87. /**
  88. * Only back faces are rendered.
  89. *
  90. * @type {number}
  91. * @constant
  92. */
  93. const BackSide = 1;
  94. /**
  95. * Both front and back faces are rendered.
  96. *
  97. * @type {number}
  98. * @constant
  99. */
  100. const DoubleSide = 2;
  101. /**
  102. * No blending is performed which effectively disables
  103. * alpha transparency.
  104. *
  105. * @type {number}
  106. * @constant
  107. */
  108. const NoBlending = 0;
  109. /**
  110. * The default blending.
  111. *
  112. * @type {number}
  113. * @constant
  114. */
  115. const NormalBlending = 1;
  116. /**
  117. * Represents additive blending.
  118. *
  119. * @type {number}
  120. * @constant
  121. */
  122. const AdditiveBlending = 2;
  123. /**
  124. * Represents subtractive blending.
  125. *
  126. * @type {number}
  127. * @constant
  128. */
  129. const SubtractiveBlending = 3;
  130. /**
  131. * Represents multiply blending.
  132. *
  133. * @type {number}
  134. * @constant
  135. */
  136. const MultiplyBlending = 4;
  137. /**
  138. * Represents custom blending.
  139. *
  140. * @type {number}
  141. * @constant
  142. */
  143. const CustomBlending = 5;
  144. /**
  145. * A `source + destination` blending equation.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const AddEquation = 100;
  151. /**
  152. * A `source - destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const SubtractEquation = 101;
  158. /**
  159. * A `destination - source` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const ReverseSubtractEquation = 102;
  165. /**
  166. * A blend equation that uses the minimum of source and destination.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const MinEquation = 103;
  172. /**
  173. * A blend equation that uses the maximum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MaxEquation = 104;
  179. /**
  180. * Multiplies all colors by `0`.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const ZeroFactor = 200;
  186. /**
  187. * Multiplies all colors by `1`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const OneFactor = 201;
  193. /**
  194. * Multiplies all colors by the source colors.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const SrcColorFactor = 202;
  200. /**
  201. * Multiplies all colors by `1` minus each source color.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const OneMinusSrcColorFactor = 203;
  207. /**
  208. * Multiplies all colors by the source alpha value.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const SrcAlphaFactor = 204;
  214. /**
  215. * Multiplies all colors by 1 minus the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const OneMinusSrcAlphaFactor = 205;
  221. /**
  222. * Multiplies all colors by the destination alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const DstAlphaFactor = 206;
  228. /**
  229. * Multiplies all colors by `1` minus the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const OneMinusDstAlphaFactor = 207;
  235. /**
  236. * Multiplies all colors by the destination color.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const DstColorFactor = 208;
  242. /**
  243. * Multiplies all colors by `1` minus each destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const OneMinusDstColorFactor = 209;
  249. /**
  250. * Multiplies the RGB colors by the smaller of either the source alpha
  251. * value or the value of `1` minus the destination alpha value. The alpha
  252. * value is multiplied by `1`.
  253. *
  254. * @type {number}
  255. * @constant
  256. */
  257. const SrcAlphaSaturateFactor = 210;
  258. /**
  259. * Multiplies all colors by a constant color.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const ConstantColorFactor = 211;
  265. /**
  266. * Multiplies all colors by `1` minus a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const OneMinusConstantColorFactor = 212;
  272. /**
  273. * Multiplies all colors by a constant alpha value.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const ConstantAlphaFactor = 213;
  279. /**
  280. * Multiplies all colors by 1 minus a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const OneMinusConstantAlphaFactor = 214;
  286. /**
  287. * Never pass.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const NeverDepth = 0;
  293. /**
  294. * Always pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const AlwaysDepth = 1;
  300. /**
  301. * Pass if the incoming value is less than the depth buffer value.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const LessDepth = 2;
  307. /**
  308. * Pass if the incoming value is less than or equal to the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessEqualDepth = 3;
  314. /**
  315. * Pass if the incoming value equals the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const EqualDepth = 4;
  321. /**
  322. * Pass if the incoming value is greater than or equal to the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const GreaterEqualDepth = 5;
  328. /**
  329. * Pass if the incoming value is greater than the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterDepth = 6;
  335. /**
  336. * Pass if the incoming value is not equal to the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const NotEqualDepth = 7;
  342. /**
  343. * Multiplies the environment map color with the surface color.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const MultiplyOperation = 0;
  349. /**
  350. * Uses reflectivity to blend between the two colors.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MixOperation = 1;
  356. /**
  357. * Adds the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const AddOperation = 2;
  363. /**
  364. * No tone mapping is applied.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const NoToneMapping = 0;
  370. /**
  371. * Linear tone mapping.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const LinearToneMapping = 1;
  377. /**
  378. * Reinhard tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const ReinhardToneMapping = 2;
  384. /**
  385. * Cineon tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const CineonToneMapping = 3;
  391. /**
  392. * ACES Filmic tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const ACESFilmicToneMapping = 4;
  398. /**
  399. * Custom tone mapping.
  400. *
  401. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  402. *
  403. * @type {number}
  404. * @constant
  405. */
  406. const CustomToneMapping = 5;
  407. /**
  408. * AgX tone mapping.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const AgXToneMapping = 6;
  414. /**
  415. * Neutral tone mapping.
  416. *
  417. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  418. *
  419. * @type {number}
  420. * @constant
  421. */
  422. const NeutralToneMapping = 7;
  423. /**
  424. * The skinned mesh shares the same world space as the skeleton.
  425. *
  426. * @type {string}
  427. * @constant
  428. */
  429. const AttachedBindMode = 'attached';
  430. /**
  431. * The skinned mesh does not share the same world space as the skeleton.
  432. * This is useful when a skeleton is shared across multiple skinned meshes.
  433. *
  434. * @type {string}
  435. * @constant
  436. */
  437. const DetachedBindMode = 'detached';
  438. /**
  439. * Maps textures using the geometry's UV coordinates.
  440. *
  441. * @type {number}
  442. * @constant
  443. */
  444. const UVMapping = 300;
  445. /**
  446. * Reflection mapping for cube textures.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const CubeReflectionMapping = 301;
  452. /**
  453. * Refraction mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeRefractionMapping = 302;
  459. /**
  460. * Reflection mapping for equirectangular textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const EquirectangularReflectionMapping = 303;
  466. /**
  467. * Refraction mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularRefractionMapping = 304;
  473. /**
  474. * Reflection mapping for PMREM textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const CubeUVReflectionMapping = 306;
  480. /**
  481. * The texture will simply repeat to infinity.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const RepeatWrapping = 1000;
  487. /**
  488. * The last pixel of the texture stretches to the edge of the mesh.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const ClampToEdgeWrapping = 1001;
  494. /**
  495. * The texture will repeats to infinity, mirroring on each repeat.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const MirroredRepeatWrapping = 1002;
  501. /**
  502. * Returns the value of the texture element that is nearest (in Manhattan distance)
  503. * to the specified texture coordinates.
  504. *
  505. * @type {number}
  506. * @constant
  507. */
  508. const NearestFilter = 1003;
  509. /**
  510. * Chooses the mipmap that most closely matches the size of the pixel being textured
  511. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  512. * to produce a texture value.
  513. *
  514. * @type {number}
  515. * @constant
  516. */
  517. const NearestMipmapNearestFilter = 1004;
  518. const NearestMipMapNearestFilter = 1004; // legacy
  519. /**
  520. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  521. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  522. * The final texture value is a weighted average of those two values.
  523. *
  524. * @type {number}
  525. * @constant
  526. */
  527. const NearestMipmapLinearFilter = 1005;
  528. const NearestMipMapLinearFilter = 1005; // legacy
  529. /**
  530. * Returns the weighted average of the four texture elements that are closest to the specified
  531. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  532. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  533. *
  534. * @type {number}
  535. * @constant
  536. */
  537. const LinearFilter = 1006;
  538. /**
  539. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  540. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  541. * center of the pixel) to produce a texture value.
  542. *
  543. * @type {number}
  544. * @constant
  545. */
  546. const LinearMipmapNearestFilter = 1007;
  547. const LinearMipMapNearestFilter = 1007; // legacy
  548. /**
  549. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  550. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  551. * is a weighted average of those two values.
  552. *
  553. * @type {number}
  554. * @constant
  555. */
  556. const LinearMipmapLinearFilter = 1008;
  557. const LinearMipMapLinearFilter = 1008; // legacy
  558. /**
  559. * An unsigned byte data type for textures.
  560. *
  561. * @type {number}
  562. * @constant
  563. */
  564. const UnsignedByteType = 1009;
  565. /**
  566. * A byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const ByteType = 1010;
  572. /**
  573. * A short data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ShortType = 1011;
  579. /**
  580. * An unsigned short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const UnsignedShortType = 1012;
  586. /**
  587. * An int data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const IntType = 1013;
  593. /**
  594. * An unsigned int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const UnsignedIntType = 1014;
  600. /**
  601. * A float data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const FloatType = 1015;
  607. /**
  608. * A half float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const HalfFloatType = 1016;
  614. /**
  615. * An unsigned short 4_4_4_4 (packed) data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const UnsignedShort4444Type = 1017;
  621. /**
  622. * An unsigned short 5_5_5_1 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort5551Type = 1018;
  628. /**
  629. * An unsigned int 24_8 data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedInt248Type = 1020;
  635. /**
  636. * An unsigned int 5_9_9_9 (packed) data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt5999Type = 35902;
  642. /**
  643. * An unsigned int 10_11_11 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt101111Type = 35899;
  649. /**
  650. * Discards the red, green and blue components and reads just the alpha component.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const AlphaFormat = 1021;
  656. /**
  657. * Discards the alpha component and reads the red, green and blue component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const RGBFormat = 1022;
  663. /**
  664. * Reads the red, green, blue and alpha components.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBAFormat = 1023;
  670. /**
  671. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const DepthFormat = 1026;
  677. /**
  678. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  679. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  680. *
  681. * @type {number}
  682. * @constant
  683. */
  684. const DepthStencilFormat = 1027;
  685. /**
  686. * Discards the green, blue and alpha components and reads just the red component.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const RedFormat = 1028;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedIntegerFormat = 1029;
  699. /**
  700. * Discards the alpha, and blue components and reads the red, and green components.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RGFormat = 1030;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGIntegerFormat = 1031;
  713. /**
  714. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGBIntegerFormat = 1032;
  720. /**
  721. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBAIntegerFormat = 1033;
  727. /**
  728. * A DXT1-compressed image in an RGB image format.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGB_S3TC_DXT1_Format = 33776;
  734. /**
  735. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGBA_S3TC_DXT1_Format = 33777;
  741. /**
  742. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT3_Format = 33778;
  748. /**
  749. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  750. * compression in how the alpha compression is done.
  751. *
  752. * @type {number}
  753. * @constant
  754. */
  755. const RGBA_S3TC_DXT5_Format = 33779;
  756. /**
  757. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGB_PVRTC_4BPPV1_Format = 35840;
  763. /**
  764. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_2BPPV1_Format = 35841;
  770. /**
  771. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGBA_PVRTC_4BPPV1_Format = 35842;
  777. /**
  778. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_2BPPV1_Format = 35843;
  784. /**
  785. * ETC1 RGB format.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGB_ETC1_Format = 36196;
  791. /**
  792. * ETC2 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC2_Format = 37492;
  798. /**
  799. * ETC2 RGBA format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGBA_ETC2_EAC_Format = 37496;
  805. /**
  806. * ASTC RGBA 4x4 format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const RGBA_ASTC_4x4_Format = 37808;
  812. /**
  813. * ASTC RGBA 5x4 format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const RGBA_ASTC_5x4_Format = 37809;
  819. /**
  820. * ASTC RGBA 5x5 format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const RGBA_ASTC_5x5_Format = 37810;
  826. /**
  827. * ASTC RGBA 6x5 format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const RGBA_ASTC_6x5_Format = 37811;
  833. /**
  834. * ASTC RGBA 6x6 format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const RGBA_ASTC_6x6_Format = 37812;
  840. /**
  841. * ASTC RGBA 8x5 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_8x5_Format = 37813;
  847. /**
  848. * ASTC RGBA 8x6 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_8x6_Format = 37814;
  854. /**
  855. * ASTC RGBA 8x8 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_8x8_Format = 37815;
  861. /**
  862. * ASTC RGBA 10x5 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_10x5_Format = 37816;
  868. /**
  869. * ASTC RGBA 10x6 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_10x6_Format = 37817;
  875. /**
  876. * ASTC RGBA 10x8 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_10x8_Format = 37818;
  882. /**
  883. * ASTC RGBA 10x10 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_10x10_Format = 37819;
  889. /**
  890. * ASTC RGBA 12x10 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_12x10_Format = 37820;
  896. /**
  897. * ASTC RGBA 12x12 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_12x12_Format = 37821;
  903. /**
  904. * BPTC RGBA format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_BPTC_Format = 36492;
  910. /**
  911. * BPTC Signed RGB format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGB_BPTC_SIGNED_Format = 36494;
  917. /**
  918. * BPTC Unsigned RGB format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGB_BPTC_UNSIGNED_Format = 36495;
  924. /**
  925. * RGTC1 Red format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RED_RGTC1_Format = 36283;
  931. /**
  932. * RGTC1 Signed Red format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const SIGNED_RED_RGTC1_Format = 36284;
  938. /**
  939. * RGTC2 Red Green format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RED_GREEN_RGTC2_Format = 36285;
  945. /**
  946. * RGTC2 Signed Red Green format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  952. /**
  953. * Animations are played once.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const LoopOnce = 2200;
  959. /**
  960. * Animations are played with a chosen number of repetitions, each time jumping from
  961. * the end of the clip directly to its beginning.
  962. *
  963. * @type {number}
  964. * @constant
  965. */
  966. const LoopRepeat = 2201;
  967. /**
  968. * Animations are played with a chosen number of repetitions, alternately playing forward
  969. * and backward.
  970. *
  971. * @type {number}
  972. * @constant
  973. */
  974. const LoopPingPong = 2202;
  975. /**
  976. * Discrete interpolation mode for keyframe tracks.
  977. *
  978. * @type {number}
  979. * @constant
  980. */
  981. const InterpolateDiscrete = 2300;
  982. /**
  983. * Linear interpolation mode for keyframe tracks.
  984. *
  985. * @type {number}
  986. * @constant
  987. */
  988. const InterpolateLinear = 2301;
  989. /**
  990. * Smooth interpolation mode for keyframe tracks.
  991. *
  992. * @type {number}
  993. * @constant
  994. */
  995. const InterpolateSmooth = 2302;
  996. /**
  997. * Zero curvature ending for animations.
  998. *
  999. * @type {number}
  1000. * @constant
  1001. */
  1002. const ZeroCurvatureEnding = 2400;
  1003. /**
  1004. * Zero slope ending for animations.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const ZeroSlopeEnding = 2401;
  1010. /**
  1011. * Wrap around ending for animations.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const WrapAroundEnding = 2402;
  1017. /**
  1018. * Default animation blend mode.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const NormalAnimationBlendMode = 2500;
  1024. /**
  1025. * Additive animation blend mode. Can be used to layer motions on top of
  1026. * each other to build complex performances from smaller re-usable assets.
  1027. *
  1028. * @type {number}
  1029. * @constant
  1030. */
  1031. const AdditiveAnimationBlendMode = 2501;
  1032. /**
  1033. * For every three vertices draw a single triangle.
  1034. *
  1035. * @type {number}
  1036. * @constant
  1037. */
  1038. const TrianglesDrawMode = 0;
  1039. /**
  1040. * For each vertex draw a triangle from the last three vertices.
  1041. *
  1042. * @type {number}
  1043. * @constant
  1044. */
  1045. const TriangleStripDrawMode = 1;
  1046. /**
  1047. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1048. *
  1049. * @type {number}
  1050. * @constant
  1051. */
  1052. const TriangleFanDrawMode = 2;
  1053. /**
  1054. * Basic depth packing.
  1055. *
  1056. * @type {number}
  1057. * @constant
  1058. */
  1059. const BasicDepthPacking = 3200;
  1060. /**
  1061. * A depth value is packed into 32 bit RGBA.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const RGBADepthPacking = 3201;
  1067. /**
  1068. * A depth value is packed into 24 bit RGB.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const RGBDepthPacking = 3202;
  1074. /**
  1075. * A depth value is packed into 16 bit RG.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const RGDepthPacking = 3203;
  1081. /**
  1082. * Normal information is relative to the underlying surface.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const TangentSpaceNormalMap = 0;
  1088. /**
  1089. * Normal information is relative to the object orientation.
  1090. *
  1091. * @type {number}
  1092. * @constant
  1093. */
  1094. const ObjectSpaceNormalMap = 1;
  1095. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1096. /**
  1097. * No color space.
  1098. *
  1099. * @type {string}
  1100. * @constant
  1101. */
  1102. const NoColorSpace = '';
  1103. /**
  1104. * sRGB color space.
  1105. *
  1106. * @type {string}
  1107. * @constant
  1108. */
  1109. const SRGBColorSpace = 'srgb';
  1110. /**
  1111. * sRGB-linear color space.
  1112. *
  1113. * @type {string}
  1114. * @constant
  1115. */
  1116. const LinearSRGBColorSpace = 'srgb-linear';
  1117. /**
  1118. * Linear transfer function.
  1119. *
  1120. * @type {string}
  1121. * @constant
  1122. */
  1123. const LinearTransfer = 'linear';
  1124. /**
  1125. * sRGB transfer function.
  1126. *
  1127. * @type {string}
  1128. * @constant
  1129. */
  1130. const SRGBTransfer = 'srgb';
  1131. /**
  1132. * Sets the stencil buffer value to `0`.
  1133. *
  1134. * @type {number}
  1135. * @constant
  1136. */
  1137. const ZeroStencilOp = 0;
  1138. /**
  1139. * Keeps the current value.
  1140. *
  1141. * @type {number}
  1142. * @constant
  1143. */
  1144. const KeepStencilOp = 7680;
  1145. /**
  1146. * Sets the stencil buffer value to the specified reference value.
  1147. *
  1148. * @type {number}
  1149. * @constant
  1150. */
  1151. const ReplaceStencilOp = 7681;
  1152. /**
  1153. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1154. *
  1155. * @type {number}
  1156. * @constant
  1157. */
  1158. const IncrementStencilOp = 7682;
  1159. /**
  1160. * Decrements the current stencil buffer value. Clamps to `0`.
  1161. *
  1162. * @type {number}
  1163. * @constant
  1164. */
  1165. const DecrementStencilOp = 7683;
  1166. /**
  1167. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1168. * the maximum representable unsigned value.
  1169. *
  1170. * @type {number}
  1171. * @constant
  1172. */
  1173. const IncrementWrapStencilOp = 34055;
  1174. /**
  1175. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1176. * unsigned value when decrementing a stencil buffer value of `0`.
  1177. *
  1178. * @type {number}
  1179. * @constant
  1180. */
  1181. const DecrementWrapStencilOp = 34056;
  1182. /**
  1183. * Inverts the current stencil buffer value bitwise.
  1184. *
  1185. * @type {number}
  1186. * @constant
  1187. */
  1188. const InvertStencilOp = 5386;
  1189. /**
  1190. * Will never return true.
  1191. *
  1192. * @type {number}
  1193. * @constant
  1194. */
  1195. const NeverStencilFunc = 512;
  1196. /**
  1197. * Will return true if the stencil reference value is less than the current stencil value.
  1198. *
  1199. * @type {number}
  1200. * @constant
  1201. */
  1202. const LessStencilFunc = 513;
  1203. /**
  1204. * Will return true if the stencil reference value is equal to the current stencil value.
  1205. *
  1206. * @type {number}
  1207. * @constant
  1208. */
  1209. const EqualStencilFunc = 514;
  1210. /**
  1211. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1212. *
  1213. * @type {number}
  1214. * @constant
  1215. */
  1216. const LessEqualStencilFunc = 515;
  1217. /**
  1218. * Will return true if the stencil reference value is greater than the current stencil value.
  1219. *
  1220. * @type {number}
  1221. * @constant
  1222. */
  1223. const GreaterStencilFunc = 516;
  1224. /**
  1225. * Will return true if the stencil reference value is not equal to the current stencil value.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const NotEqualStencilFunc = 517;
  1231. /**
  1232. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const GreaterEqualStencilFunc = 518;
  1238. /**
  1239. * Will always return true.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const AlwaysStencilFunc = 519;
  1245. /**
  1246. * Never pass.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const NeverCompare = 512;
  1252. /**
  1253. * Pass if the incoming value is less than the texture value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const LessCompare = 513;
  1259. /**
  1260. * Pass if the incoming value equals the texture value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const EqualCompare = 514;
  1266. /**
  1267. * Pass if the incoming value is less than or equal to the texture value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const LessEqualCompare = 515;
  1273. /**
  1274. * Pass if the incoming value is greater than the texture value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const GreaterCompare = 516;
  1280. /**
  1281. * Pass if the incoming value is not equal to the texture value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const NotEqualCompare = 517;
  1287. /**
  1288. * Pass if the incoming value is greater than or equal to the texture value.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const GreaterEqualCompare = 518;
  1294. /**
  1295. * Always pass.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const AlwaysCompare = 519;
  1301. /**
  1302. * The contents are intended to be specified once by the application, and used many
  1303. * times as the source for drawing and image specification commands.
  1304. *
  1305. * @type {number}
  1306. * @constant
  1307. */
  1308. const StaticDrawUsage = 35044;
  1309. /**
  1310. * The contents are intended to be respecified repeatedly by the application, and
  1311. * used many times as the source for drawing and image specification commands.
  1312. *
  1313. * @type {number}
  1314. * @constant
  1315. */
  1316. const DynamicDrawUsage = 35048;
  1317. /**
  1318. * The contents are intended to be specified once by the application, and used at most
  1319. * a few times as the source for drawing and image specification commands.
  1320. *
  1321. * @type {number}
  1322. * @constant
  1323. */
  1324. const StreamDrawUsage = 35040;
  1325. /**
  1326. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1327. * many times by the application.
  1328. *
  1329. * @type {number}
  1330. * @constant
  1331. */
  1332. const StaticReadUsage = 35045;
  1333. /**
  1334. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1335. * many times by the application.
  1336. *
  1337. * @type {number}
  1338. * @constant
  1339. */
  1340. const DynamicReadUsage = 35049;
  1341. /**
  1342. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1343. * a few times by the application
  1344. *
  1345. * @type {number}
  1346. * @constant
  1347. */
  1348. const StreamReadUsage = 35041;
  1349. /**
  1350. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1351. * the source for WebGL drawing and image specification commands.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const StaticCopyUsage = 35046;
  1357. /**
  1358. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1359. * as the source for WebGL drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const DynamicCopyUsage = 35050;
  1365. /**
  1366. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1367. * as the source for WebGL drawing and image specification commands.
  1368. *
  1369. * @type {number}
  1370. * @constant
  1371. */
  1372. const StreamCopyUsage = 35042;
  1373. /**
  1374. * GLSL 1 shader code.
  1375. *
  1376. * @type {string}
  1377. * @constant
  1378. */
  1379. const GLSL1 = '100';
  1380. /**
  1381. * GLSL 3 shader code.
  1382. *
  1383. * @type {string}
  1384. * @constant
  1385. */
  1386. const GLSL3 = '300 es';
  1387. /**
  1388. * WebGL coordinate system.
  1389. *
  1390. * @type {number}
  1391. * @constant
  1392. */
  1393. const WebGLCoordinateSystem = 2000;
  1394. /**
  1395. * WebGPU coordinate system.
  1396. *
  1397. * @type {number}
  1398. * @constant
  1399. */
  1400. const WebGPUCoordinateSystem = 2001;
  1401. /**
  1402. * Represents the different timestamp query types.
  1403. *
  1404. * @type {ConstantsTimestampQuery}
  1405. * @constant
  1406. */
  1407. const TimestampQuery = {
  1408. COMPUTE: 'compute',
  1409. RENDER: 'render'
  1410. };
  1411. /**
  1412. * Represents mouse buttons and interaction types in context of controls.
  1413. *
  1414. * @type {ConstantsInterpolationSamplingType}
  1415. * @constant
  1416. */
  1417. const InterpolationSamplingType = {
  1418. PERSPECTIVE: 'perspective',
  1419. LINEAR: 'linear',
  1420. FLAT: 'flat'
  1421. };
  1422. /**
  1423. * Represents the different interpolation sampling modes.
  1424. *
  1425. * @type {ConstantsInterpolationSamplingMode}
  1426. * @constant
  1427. */
  1428. const InterpolationSamplingMode = {
  1429. NORMAL: 'normal',
  1430. CENTROID: 'centroid',
  1431. SAMPLE: 'sample',
  1432. FIRST: 'first',
  1433. EITHER: 'either'
  1434. };
  1435. /**
  1436. * This type represents mouse buttons and interaction types in context of controls.
  1437. *
  1438. * @typedef {Object} ConstantsMouse
  1439. * @property {number} MIDDLE - The left mouse button.
  1440. * @property {number} LEFT - The middle mouse button.
  1441. * @property {number} RIGHT - The right mouse button.
  1442. * @property {number} ROTATE - A rotate interaction.
  1443. * @property {number} DOLLY - A dolly interaction.
  1444. * @property {number} PAN - A pan interaction.
  1445. **/
  1446. /**
  1447. * This type represents touch interaction types in context of controls.
  1448. *
  1449. * @typedef {Object} ConstantsTouch
  1450. * @property {number} ROTATE - A rotate interaction.
  1451. * @property {number} PAN - A pan interaction.
  1452. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1453. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1454. **/
  1455. /**
  1456. * This type represents the different timestamp query types.
  1457. *
  1458. * @typedef {Object} ConstantsTimestampQuery
  1459. * @property {string} COMPUTE - A `compute` timestamp query.
  1460. * @property {string} RENDER - A `render` timestamp query.
  1461. **/
  1462. /**
  1463. * Represents the different interpolation sampling types.
  1464. *
  1465. * @typedef {Object} ConstantsInterpolationSamplingType
  1466. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1467. * @property {string} LINEAR - Linear interpolation.
  1468. * @property {string} FLAT - Flat interpolation.
  1469. */
  1470. /**
  1471. * Represents the different interpolation sampling modes.
  1472. *
  1473. * @typedef {Object} ConstantsInterpolationSamplingMode
  1474. * @property {string} NORMAL - Normal sampling mode.
  1475. * @property {string} CENTROID - Centroid sampling mode.
  1476. * @property {string} SAMPLE - Sample-specific sampling mode.
  1477. * @property {string} FIRST - Flat interpolation using the first vertex.
  1478. * @property {string} EITHER - Flat interpolation using either vertex.
  1479. */
  1480. function arrayNeedsUint32( array ) {
  1481. // assumes larger values usually on last
  1482. for ( let i = array.length - 1; i >= 0; -- i ) {
  1483. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1484. }
  1485. return false;
  1486. }
  1487. const TYPED_ARRAYS = {
  1488. Int8Array: Int8Array,
  1489. Uint8Array: Uint8Array,
  1490. Uint8ClampedArray: Uint8ClampedArray,
  1491. Int16Array: Int16Array,
  1492. Uint16Array: Uint16Array,
  1493. Int32Array: Int32Array,
  1494. Uint32Array: Uint32Array,
  1495. Float32Array: Float32Array,
  1496. Float64Array: Float64Array
  1497. };
  1498. function getTypedArray( type, buffer ) {
  1499. return new TYPED_ARRAYS[ type ]( buffer );
  1500. }
  1501. function createElementNS( name ) {
  1502. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1503. }
  1504. function createCanvasElement() {
  1505. const canvas = createElementNS( 'canvas' );
  1506. canvas.style.display = 'block';
  1507. return canvas;
  1508. }
  1509. const _cache = {};
  1510. let _setConsoleFunction = null;
  1511. function setConsoleFunction( fn ) {
  1512. _setConsoleFunction = fn;
  1513. }
  1514. function getConsoleFunction() {
  1515. return _setConsoleFunction;
  1516. }
  1517. function log( ...params ) {
  1518. const message = 'THREE.' + params.shift();
  1519. if ( _setConsoleFunction ) {
  1520. _setConsoleFunction( 'log', message, ...params );
  1521. } else {
  1522. console.log( message, ...params );
  1523. }
  1524. }
  1525. function warn( ...params ) {
  1526. const message = 'THREE.' + params.shift();
  1527. if ( _setConsoleFunction ) {
  1528. _setConsoleFunction( 'warn', message, ...params );
  1529. } else {
  1530. console.warn( message, ...params );
  1531. }
  1532. }
  1533. function error( ...params ) {
  1534. const message = 'THREE.' + params.shift();
  1535. if ( _setConsoleFunction ) {
  1536. _setConsoleFunction( 'error', message, ...params );
  1537. } else {
  1538. console.error( message, ...params );
  1539. }
  1540. }
  1541. function warnOnce( ...params ) {
  1542. const message = params.join( ' ' );
  1543. if ( message in _cache ) return;
  1544. _cache[ message ] = true;
  1545. warn( ...params );
  1546. }
  1547. function probeAsync( gl, sync, interval ) {
  1548. return new Promise( function ( resolve, reject ) {
  1549. function probe() {
  1550. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1551. case gl.WAIT_FAILED:
  1552. reject();
  1553. break;
  1554. case gl.TIMEOUT_EXPIRED:
  1555. setTimeout( probe, interval );
  1556. break;
  1557. default:
  1558. resolve();
  1559. }
  1560. }
  1561. setTimeout( probe, interval );
  1562. } );
  1563. }
  1564. /**
  1565. * This modules allows to dispatch event objects on custom JavaScript objects.
  1566. *
  1567. * Main repository: [eventdispatcher.js]{@link https://github.com/mrdoob/eventdispatcher.js/}
  1568. *
  1569. * Code Example:
  1570. * ```js
  1571. * class Car extends EventDispatcher {
  1572. * start() {
  1573. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1574. * }
  1575. *};
  1576. *
  1577. * // Using events with the custom object
  1578. * const car = new Car();
  1579. * car.addEventListener( 'start', function ( event ) {
  1580. * alert( event.message );
  1581. * } );
  1582. *
  1583. * car.start();
  1584. * ```
  1585. */
  1586. class EventDispatcher {
  1587. /**
  1588. * Adds the given event listener to the given event type.
  1589. *
  1590. * @param {string} type - The type of event to listen to.
  1591. * @param {Function} listener - The function that gets called when the event is fired.
  1592. */
  1593. addEventListener( type, listener ) {
  1594. if ( this._listeners === undefined ) this._listeners = {};
  1595. const listeners = this._listeners;
  1596. if ( listeners[ type ] === undefined ) {
  1597. listeners[ type ] = [];
  1598. }
  1599. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1600. listeners[ type ].push( listener );
  1601. }
  1602. }
  1603. /**
  1604. * Returns `true` if the given event listener has been added to the given event type.
  1605. *
  1606. * @param {string} type - The type of event.
  1607. * @param {Function} listener - The listener to check.
  1608. * @return {boolean} Whether the given event listener has been added to the given event type.
  1609. */
  1610. hasEventListener( type, listener ) {
  1611. const listeners = this._listeners;
  1612. if ( listeners === undefined ) return false;
  1613. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1614. }
  1615. /**
  1616. * Removes the given event listener from the given event type.
  1617. *
  1618. * @param {string} type - The type of event.
  1619. * @param {Function} listener - The listener to remove.
  1620. */
  1621. removeEventListener( type, listener ) {
  1622. const listeners = this._listeners;
  1623. if ( listeners === undefined ) return;
  1624. const listenerArray = listeners[ type ];
  1625. if ( listenerArray !== undefined ) {
  1626. const index = listenerArray.indexOf( listener );
  1627. if ( index !== -1 ) {
  1628. listenerArray.splice( index, 1 );
  1629. }
  1630. }
  1631. }
  1632. /**
  1633. * Dispatches an event object.
  1634. *
  1635. * @param {Object} event - The event that gets fired.
  1636. */
  1637. dispatchEvent( event ) {
  1638. const listeners = this._listeners;
  1639. if ( listeners === undefined ) return;
  1640. const listenerArray = listeners[ event.type ];
  1641. if ( listenerArray !== undefined ) {
  1642. event.target = this;
  1643. // Make a copy, in case listeners are removed while iterating.
  1644. const array = listenerArray.slice( 0 );
  1645. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1646. array[ i ].call( this, event );
  1647. }
  1648. event.target = null;
  1649. }
  1650. }
  1651. }
  1652. 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' ];
  1653. let _seed = 1234567;
  1654. const DEG2RAD = Math.PI / 180;
  1655. const RAD2DEG = 180 / Math.PI;
  1656. /**
  1657. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1658. * (universally unique identifier).
  1659. *
  1660. * @return {string} The UUID.
  1661. */
  1662. function generateUUID() {
  1663. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1664. const d0 = Math.random() * 0xffffffff | 0;
  1665. const d1 = Math.random() * 0xffffffff | 0;
  1666. const d2 = Math.random() * 0xffffffff | 0;
  1667. const d3 = Math.random() * 0xffffffff | 0;
  1668. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1669. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1670. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1671. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1672. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1673. return uuid.toLowerCase();
  1674. }
  1675. /**
  1676. * Clamps the given value between min and max.
  1677. *
  1678. * @param {number} value - The value to clamp.
  1679. * @param {number} min - The min value.
  1680. * @param {number} max - The max value.
  1681. * @return {number} The clamped value.
  1682. */
  1683. function clamp( value, min, max ) {
  1684. return Math.max( min, Math.min( max, value ) );
  1685. }
  1686. /**
  1687. * Computes the Euclidean modulo of the given parameters that
  1688. * is `( ( n % m ) + m ) % m`.
  1689. *
  1690. * @param {number} n - The first parameter.
  1691. * @param {number} m - The second parameter.
  1692. * @return {number} The Euclidean modulo.
  1693. */
  1694. function euclideanModulo( n, m ) {
  1695. // https://en.wikipedia.org/wiki/Modulo_operation
  1696. return ( ( n % m ) + m ) % m;
  1697. }
  1698. /**
  1699. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1700. * for the given value.
  1701. *
  1702. * @param {number} x - The value to be mapped.
  1703. * @param {number} a1 - Minimum value for range A.
  1704. * @param {number} a2 - Maximum value for range A.
  1705. * @param {number} b1 - Minimum value for range B.
  1706. * @param {number} b2 - Maximum value for range B.
  1707. * @return {number} The mapped value.
  1708. */
  1709. function mapLinear( x, a1, a2, b1, b2 ) {
  1710. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1711. }
  1712. /**
  1713. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1714. * between the start and end point.
  1715. *
  1716. * @param {number} x - The start point
  1717. * @param {number} y - The end point.
  1718. * @param {number} value - A value between start and end.
  1719. * @return {number} The interpolation factor.
  1720. */
  1721. function inverseLerp( x, y, value ) {
  1722. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1723. if ( x !== y ) {
  1724. return ( value - x ) / ( y - x );
  1725. } else {
  1726. return 0;
  1727. }
  1728. }
  1729. /**
  1730. * Returns a value linearly interpolated from two known points based on the given interval -
  1731. * `t = 0` will return `x` and `t = 1` will return `y`.
  1732. *
  1733. * @param {number} x - The start point
  1734. * @param {number} y - The end point.
  1735. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1736. * @return {number} The interpolated value.
  1737. */
  1738. function lerp( x, y, t ) {
  1739. return ( 1 - t ) * x + t * y;
  1740. }
  1741. /**
  1742. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1743. * time to maintain frame rate independent movement. For details, see
  1744. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  1745. *
  1746. * @param {number} x - The current point.
  1747. * @param {number} y - The target point.
  1748. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1749. * and a lower value will make the movement more gradual.
  1750. * @param {number} dt - Delta time in seconds.
  1751. * @return {number} The interpolated value.
  1752. */
  1753. function damp( x, y, lambda, dt ) {
  1754. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1755. }
  1756. /**
  1757. * Returns a value that alternates between `0` and the given `length` parameter.
  1758. *
  1759. * @param {number} x - The value to pingpong.
  1760. * @param {number} [length=1] - The positive value the function will pingpong to.
  1761. * @return {number} The alternated value.
  1762. */
  1763. function pingpong( x, length = 1 ) {
  1764. // https://www.desmos.com/calculator/vcsjnyz7x4
  1765. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1766. }
  1767. /**
  1768. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1769. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1770. * the `min` and `max`.
  1771. *
  1772. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  1773. *
  1774. * @param {number} x - The value to evaluate based on its position between min and max.
  1775. * @param {number} min - The min value. Any x value below min will be `0`.
  1776. * @param {number} max - The max value. Any x value above max will be `1`.
  1777. * @return {number} The alternated value.
  1778. */
  1779. function smoothstep( x, min, max ) {
  1780. if ( x <= min ) return 0;
  1781. if ( x >= max ) return 1;
  1782. x = ( x - min ) / ( max - min );
  1783. return x * x * ( 3 - 2 * x );
  1784. }
  1785. /**
  1786. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  1787. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1788. *
  1789. * @param {number} x - The value to evaluate based on its position between min and max.
  1790. * @param {number} min - The min value. Any x value below min will be `0`.
  1791. * @param {number} max - The max value. Any x value above max will be `1`.
  1792. * @return {number} The alternated value.
  1793. */
  1794. function smootherstep( x, min, max ) {
  1795. if ( x <= min ) return 0;
  1796. if ( x >= max ) return 1;
  1797. x = ( x - min ) / ( max - min );
  1798. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1799. }
  1800. /**
  1801. * Returns a random integer from `<low, high>` interval.
  1802. *
  1803. * @param {number} low - The lower value boundary.
  1804. * @param {number} high - The upper value boundary
  1805. * @return {number} A random integer.
  1806. */
  1807. function randInt( low, high ) {
  1808. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1809. }
  1810. /**
  1811. * Returns a random float from `<low, high>` interval.
  1812. *
  1813. * @param {number} low - The lower value boundary.
  1814. * @param {number} high - The upper value boundary
  1815. * @return {number} A random float.
  1816. */
  1817. function randFloat( low, high ) {
  1818. return low + Math.random() * ( high - low );
  1819. }
  1820. /**
  1821. * Returns a random integer from `<-range/2, range/2>` interval.
  1822. *
  1823. * @param {number} range - Defines the value range.
  1824. * @return {number} A random float.
  1825. */
  1826. function randFloatSpread( range ) {
  1827. return range * ( 0.5 - Math.random() );
  1828. }
  1829. /**
  1830. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1831. *
  1832. * @param {number} [s] - The integer seed.
  1833. * @return {number} A random float.
  1834. */
  1835. function seededRandom( s ) {
  1836. if ( s !== undefined ) _seed = s;
  1837. // Mulberry32 generator
  1838. let t = _seed += 0x6D2B79F5;
  1839. t = Math.imul( t ^ t >>> 15, t | 1 );
  1840. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1841. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1842. }
  1843. /**
  1844. * Converts degrees to radians.
  1845. *
  1846. * @param {number} degrees - A value in degrees.
  1847. * @return {number} The converted value in radians.
  1848. */
  1849. function degToRad( degrees ) {
  1850. return degrees * DEG2RAD;
  1851. }
  1852. /**
  1853. * Converts radians to degrees.
  1854. *
  1855. * @param {number} radians - A value in radians.
  1856. * @return {number} The converted value in degrees.
  1857. */
  1858. function radToDeg( radians ) {
  1859. return radians * RAD2DEG;
  1860. }
  1861. /**
  1862. * Returns `true` if the given number is a power of two.
  1863. *
  1864. * @param {number} value - The value to check.
  1865. * @return {boolean} Whether the given number is a power of two or not.
  1866. */
  1867. function isPowerOfTwo( value ) {
  1868. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1869. }
  1870. /**
  1871. * Returns the smallest power of two that is greater than or equal to the given number.
  1872. *
  1873. * @param {number} value - The value to find a POT for.
  1874. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1875. */
  1876. function ceilPowerOfTwo( value ) {
  1877. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1878. }
  1879. /**
  1880. * Returns the largest power of two that is less than or equal to the given number.
  1881. *
  1882. * @param {number} value - The value to find a POT for.
  1883. * @return {number} The largest power of two that is less than or equal to the given number.
  1884. */
  1885. function floorPowerOfTwo( value ) {
  1886. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1887. }
  1888. /**
  1889. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  1890. * defined by the given angles and order.
  1891. *
  1892. * Rotations are applied to the axes in the order specified by order:
  1893. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1894. *
  1895. * @param {Quaternion} q - The quaternion to set.
  1896. * @param {number} a - The rotation applied to the first axis, in radians.
  1897. * @param {number} b - The rotation applied to the second axis, in radians.
  1898. * @param {number} c - The rotation applied to the third axis, in radians.
  1899. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1900. */
  1901. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1902. const cos = Math.cos;
  1903. const sin = Math.sin;
  1904. const c2 = cos( b / 2 );
  1905. const s2 = sin( b / 2 );
  1906. const c13 = cos( ( a + c ) / 2 );
  1907. const s13 = sin( ( a + c ) / 2 );
  1908. const c1_3 = cos( ( a - c ) / 2 );
  1909. const s1_3 = sin( ( a - c ) / 2 );
  1910. const c3_1 = cos( ( c - a ) / 2 );
  1911. const s3_1 = sin( ( c - a ) / 2 );
  1912. switch ( order ) {
  1913. case 'XYX':
  1914. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1915. break;
  1916. case 'YZY':
  1917. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1918. break;
  1919. case 'ZXZ':
  1920. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1921. break;
  1922. case 'XZX':
  1923. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1924. break;
  1925. case 'YXY':
  1926. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1927. break;
  1928. case 'ZYZ':
  1929. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1930. break;
  1931. default:
  1932. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1933. }
  1934. }
  1935. /**
  1936. * Denormalizes the given value according to the given typed array.
  1937. *
  1938. * @param {number} value - The value to denormalize.
  1939. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1940. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1941. */
  1942. function denormalize( value, array ) {
  1943. switch ( array.constructor ) {
  1944. case Float32Array:
  1945. return value;
  1946. case Uint32Array:
  1947. return value / 4294967295.0;
  1948. case Uint16Array:
  1949. return value / 65535.0;
  1950. case Uint8Array:
  1951. return value / 255.0;
  1952. case Int32Array:
  1953. return Math.max( value / 2147483647.0, -1 );
  1954. case Int16Array:
  1955. return Math.max( value / 32767.0, -1 );
  1956. case Int8Array:
  1957. return Math.max( value / 127.0, -1 );
  1958. default:
  1959. throw new Error( 'Invalid component type.' );
  1960. }
  1961. }
  1962. /**
  1963. * Normalizes the given value according to the given typed array.
  1964. *
  1965. * @param {number} value - The float value in the range `[0,1]` to normalize.
  1966. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1967. * @return {number} The normalize value.
  1968. */
  1969. function normalize( value, array ) {
  1970. switch ( array.constructor ) {
  1971. case Float32Array:
  1972. return value;
  1973. case Uint32Array:
  1974. return Math.round( value * 4294967295.0 );
  1975. case Uint16Array:
  1976. return Math.round( value * 65535.0 );
  1977. case Uint8Array:
  1978. return Math.round( value * 255.0 );
  1979. case Int32Array:
  1980. return Math.round( value * 2147483647.0 );
  1981. case Int16Array:
  1982. return Math.round( value * 32767.0 );
  1983. case Int8Array:
  1984. return Math.round( value * 127.0 );
  1985. default:
  1986. throw new Error( 'Invalid component type.' );
  1987. }
  1988. }
  1989. /**
  1990. * @class
  1991. * @classdesc A collection of math utility functions.
  1992. * @hideconstructor
  1993. */
  1994. const MathUtils = {
  1995. DEG2RAD: DEG2RAD,
  1996. RAD2DEG: RAD2DEG,
  1997. /**
  1998. * Generate a [UUID]{@link https://en.wikipedia.org/wiki/Universally_unique_identifier}
  1999. * (universally unique identifier).
  2000. *
  2001. * @static
  2002. * @method
  2003. * @return {string} The UUID.
  2004. */
  2005. generateUUID: generateUUID,
  2006. /**
  2007. * Clamps the given value between min and max.
  2008. *
  2009. * @static
  2010. * @method
  2011. * @param {number} value - The value to clamp.
  2012. * @param {number} min - The min value.
  2013. * @param {number} max - The max value.
  2014. * @return {number} The clamped value.
  2015. */
  2016. clamp: clamp,
  2017. /**
  2018. * Computes the Euclidean modulo of the given parameters that
  2019. * is `( ( n % m ) + m ) % m`.
  2020. *
  2021. * @static
  2022. * @method
  2023. * @param {number} n - The first parameter.
  2024. * @param {number} m - The second parameter.
  2025. * @return {number} The Euclidean modulo.
  2026. */
  2027. euclideanModulo: euclideanModulo,
  2028. /**
  2029. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2030. * for the given value.
  2031. *
  2032. * @static
  2033. * @method
  2034. * @param {number} x - The value to be mapped.
  2035. * @param {number} a1 - Minimum value for range A.
  2036. * @param {number} a2 - Maximum value for range A.
  2037. * @param {number} b1 - Minimum value for range B.
  2038. * @param {number} b2 - Maximum value for range B.
  2039. * @return {number} The mapped value.
  2040. */
  2041. mapLinear: mapLinear,
  2042. /**
  2043. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2044. * between the start and end point.
  2045. *
  2046. * @static
  2047. * @method
  2048. * @param {number} x - The start point
  2049. * @param {number} y - The end point.
  2050. * @param {number} value - A value between start and end.
  2051. * @return {number} The interpolation factor.
  2052. */
  2053. inverseLerp: inverseLerp,
  2054. /**
  2055. * Returns a value linearly interpolated from two known points based on the given interval -
  2056. * `t = 0` will return `x` and `t = 1` will return `y`.
  2057. *
  2058. * @static
  2059. * @method
  2060. * @param {number} x - The start point
  2061. * @param {number} y - The end point.
  2062. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2063. * @return {number} The interpolated value.
  2064. */
  2065. lerp: lerp,
  2066. /**
  2067. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2068. * time to maintain frame rate independent movement. For details, see
  2069. * [Frame rate independent damping using lerp]{@link http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/}.
  2070. *
  2071. * @static
  2072. * @method
  2073. * @param {number} x - The current point.
  2074. * @param {number} y - The target point.
  2075. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2076. * and a lower value will make the movement more gradual.
  2077. * @param {number} dt - Delta time in seconds.
  2078. * @return {number} The interpolated value.
  2079. */
  2080. damp: damp,
  2081. /**
  2082. * Returns a value that alternates between `0` and the given `length` parameter.
  2083. *
  2084. * @static
  2085. * @method
  2086. * @param {number} x - The value to pingpong.
  2087. * @param {number} [length=1] - The positive value the function will pingpong to.
  2088. * @return {number} The alternated value.
  2089. */
  2090. pingpong: pingpong,
  2091. /**
  2092. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2093. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2094. * the `min` and `max`.
  2095. *
  2096. * See [Smoothstep]{@link http://en.wikipedia.org/wiki/Smoothstep} for more details.
  2097. *
  2098. * @static
  2099. * @method
  2100. * @param {number} x - The value to evaluate based on its position between min and max.
  2101. * @param {number} min - The min value. Any x value below min will be `0`.
  2102. * @param {number} max - The max value. Any x value above max will be `1`.
  2103. * @return {number} The alternated value.
  2104. */
  2105. smoothstep: smoothstep,
  2106. /**
  2107. * A [variation on smoothstep]{@link https://en.wikipedia.org/wiki/Smoothstep#Variations}
  2108. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2109. *
  2110. * @static
  2111. * @method
  2112. * @param {number} x - The value to evaluate based on its position between min and max.
  2113. * @param {number} min - The min value. Any x value below min will be `0`.
  2114. * @param {number} max - The max value. Any x value above max will be `1`.
  2115. * @return {number} The alternated value.
  2116. */
  2117. smootherstep: smootherstep,
  2118. /**
  2119. * Returns a random integer from `<low, high>` interval.
  2120. *
  2121. * @static
  2122. * @method
  2123. * @param {number} low - The lower value boundary.
  2124. * @param {number} high - The upper value boundary
  2125. * @return {number} A random integer.
  2126. */
  2127. randInt: randInt,
  2128. /**
  2129. * Returns a random float from `<low, high>` interval.
  2130. *
  2131. * @static
  2132. * @method
  2133. * @param {number} low - The lower value boundary.
  2134. * @param {number} high - The upper value boundary
  2135. * @return {number} A random float.
  2136. */
  2137. randFloat: randFloat,
  2138. /**
  2139. * Returns a random integer from `<-range/2, range/2>` interval.
  2140. *
  2141. * @static
  2142. * @method
  2143. * @param {number} range - Defines the value range.
  2144. * @return {number} A random float.
  2145. */
  2146. randFloatSpread: randFloatSpread,
  2147. /**
  2148. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2149. *
  2150. * @static
  2151. * @method
  2152. * @param {number} [s] - The integer seed.
  2153. * @return {number} A random float.
  2154. */
  2155. seededRandom: seededRandom,
  2156. /**
  2157. * Converts degrees to radians.
  2158. *
  2159. * @static
  2160. * @method
  2161. * @param {number} degrees - A value in degrees.
  2162. * @return {number} The converted value in radians.
  2163. */
  2164. degToRad: degToRad,
  2165. /**
  2166. * Converts radians to degrees.
  2167. *
  2168. * @static
  2169. * @method
  2170. * @param {number} radians - A value in radians.
  2171. * @return {number} The converted value in degrees.
  2172. */
  2173. radToDeg: radToDeg,
  2174. /**
  2175. * Returns `true` if the given number is a power of two.
  2176. *
  2177. * @static
  2178. * @method
  2179. * @param {number} value - The value to check.
  2180. * @return {boolean} Whether the given number is a power of two or not.
  2181. */
  2182. isPowerOfTwo: isPowerOfTwo,
  2183. /**
  2184. * Returns the smallest power of two that is greater than or equal to the given number.
  2185. *
  2186. * @static
  2187. * @method
  2188. * @param {number} value - The value to find a POT for.
  2189. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2190. */
  2191. ceilPowerOfTwo: ceilPowerOfTwo,
  2192. /**
  2193. * Returns the largest power of two that is less than or equal to the given number.
  2194. *
  2195. * @static
  2196. * @method
  2197. * @param {number} value - The value to find a POT for.
  2198. * @return {number} The largest power of two that is less than or equal to the given number.
  2199. */
  2200. floorPowerOfTwo: floorPowerOfTwo,
  2201. /**
  2202. * Sets the given quaternion from the [Intrinsic Proper Euler Angles]{@link https://en.wikipedia.org/wiki/Euler_angles}
  2203. * defined by the given angles and order.
  2204. *
  2205. * Rotations are applied to the axes in the order specified by order:
  2206. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2207. *
  2208. * @static
  2209. * @method
  2210. * @param {Quaternion} q - The quaternion to set.
  2211. * @param {number} a - The rotation applied to the first axis, in radians.
  2212. * @param {number} b - The rotation applied to the second axis, in radians.
  2213. * @param {number} c - The rotation applied to the third axis, in radians.
  2214. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2215. */
  2216. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2217. /**
  2218. * Normalizes the given value according to the given typed array.
  2219. *
  2220. * @static
  2221. * @method
  2222. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2223. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2224. * @return {number} The normalize value.
  2225. */
  2226. normalize: normalize,
  2227. /**
  2228. * Denormalizes the given value according to the given typed array.
  2229. *
  2230. * @static
  2231. * @method
  2232. * @param {number} value - The value to denormalize.
  2233. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2234. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2235. */
  2236. denormalize: denormalize
  2237. };
  2238. /**
  2239. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2240. * (labeled x and y), which can be used to represent a number of things, such as:
  2241. *
  2242. * - A point in 2D space (i.e. a position on a plane).
  2243. * - A direction and length across a plane. In three.js the length will
  2244. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2245. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2246. * - Any arbitrary ordered pair of numbers.
  2247. *
  2248. * There are other things a 2D vector can be used to represent, such as
  2249. * momentum vectors, complex numbers and so on, however these are the most
  2250. * common uses in three.js.
  2251. *
  2252. * Iterating through a vector instance will yield its components `(x, y)` in
  2253. * the corresponding order.
  2254. * ```js
  2255. * const a = new THREE.Vector2( 0, 1 );
  2256. *
  2257. * //no arguments; will be initialised to (0, 0)
  2258. * const b = new THREE.Vector2( );
  2259. *
  2260. * const d = a.distanceTo( b );
  2261. * ```
  2262. */
  2263. class Vector2 {
  2264. /**
  2265. * Constructs a new 2D vector.
  2266. *
  2267. * @param {number} [x=0] - The x value of this vector.
  2268. * @param {number} [y=0] - The y value of this vector.
  2269. */
  2270. constructor( x = 0, y = 0 ) {
  2271. /**
  2272. * This flag can be used for type testing.
  2273. *
  2274. * @type {boolean}
  2275. * @readonly
  2276. * @default true
  2277. */
  2278. Vector2.prototype.isVector2 = true;
  2279. /**
  2280. * The x value of this vector.
  2281. *
  2282. * @type {number}
  2283. */
  2284. this.x = x;
  2285. /**
  2286. * The y value of this vector.
  2287. *
  2288. * @type {number}
  2289. */
  2290. this.y = y;
  2291. }
  2292. /**
  2293. * Alias for {@link Vector2#x}.
  2294. *
  2295. * @type {number}
  2296. */
  2297. get width() {
  2298. return this.x;
  2299. }
  2300. set width( value ) {
  2301. this.x = value;
  2302. }
  2303. /**
  2304. * Alias for {@link Vector2#y}.
  2305. *
  2306. * @type {number}
  2307. */
  2308. get height() {
  2309. return this.y;
  2310. }
  2311. set height( value ) {
  2312. this.y = value;
  2313. }
  2314. /**
  2315. * Sets the vector components.
  2316. *
  2317. * @param {number} x - The value of the x component.
  2318. * @param {number} y - The value of the y component.
  2319. * @return {Vector2} A reference to this vector.
  2320. */
  2321. set( x, y ) {
  2322. this.x = x;
  2323. this.y = y;
  2324. return this;
  2325. }
  2326. /**
  2327. * Sets the vector components to the same value.
  2328. *
  2329. * @param {number} scalar - The value to set for all vector components.
  2330. * @return {Vector2} A reference to this vector.
  2331. */
  2332. setScalar( scalar ) {
  2333. this.x = scalar;
  2334. this.y = scalar;
  2335. return this;
  2336. }
  2337. /**
  2338. * Sets the vector's x component to the given value
  2339. *
  2340. * @param {number} x - The value to set.
  2341. * @return {Vector2} A reference to this vector.
  2342. */
  2343. setX( x ) {
  2344. this.x = x;
  2345. return this;
  2346. }
  2347. /**
  2348. * Sets the vector's y component to the given value
  2349. *
  2350. * @param {number} y - The value to set.
  2351. * @return {Vector2} A reference to this vector.
  2352. */
  2353. setY( y ) {
  2354. this.y = y;
  2355. return this;
  2356. }
  2357. /**
  2358. * Allows to set a vector component with an index.
  2359. *
  2360. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2361. * @param {number} value - The value to set.
  2362. * @return {Vector2} A reference to this vector.
  2363. */
  2364. setComponent( index, value ) {
  2365. switch ( index ) {
  2366. case 0: this.x = value; break;
  2367. case 1: this.y = value; break;
  2368. default: throw new Error( 'index is out of range: ' + index );
  2369. }
  2370. return this;
  2371. }
  2372. /**
  2373. * Returns the value of the vector component which matches the given index.
  2374. *
  2375. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2376. * @return {number} A vector component value.
  2377. */
  2378. getComponent( index ) {
  2379. switch ( index ) {
  2380. case 0: return this.x;
  2381. case 1: return this.y;
  2382. default: throw new Error( 'index is out of range: ' + index );
  2383. }
  2384. }
  2385. /**
  2386. * Returns a new vector with copied values from this instance.
  2387. *
  2388. * @return {Vector2} A clone of this instance.
  2389. */
  2390. clone() {
  2391. return new this.constructor( this.x, this.y );
  2392. }
  2393. /**
  2394. * Copies the values of the given vector to this instance.
  2395. *
  2396. * @param {Vector2} v - The vector to copy.
  2397. * @return {Vector2} A reference to this vector.
  2398. */
  2399. copy( v ) {
  2400. this.x = v.x;
  2401. this.y = v.y;
  2402. return this;
  2403. }
  2404. /**
  2405. * Adds the given vector to this instance.
  2406. *
  2407. * @param {Vector2} v - The vector to add.
  2408. * @return {Vector2} A reference to this vector.
  2409. */
  2410. add( v ) {
  2411. this.x += v.x;
  2412. this.y += v.y;
  2413. return this;
  2414. }
  2415. /**
  2416. * Adds the given scalar value to all components of this instance.
  2417. *
  2418. * @param {number} s - The scalar to add.
  2419. * @return {Vector2} A reference to this vector.
  2420. */
  2421. addScalar( s ) {
  2422. this.x += s;
  2423. this.y += s;
  2424. return this;
  2425. }
  2426. /**
  2427. * Adds the given vectors and stores the result in this instance.
  2428. *
  2429. * @param {Vector2} a - The first vector.
  2430. * @param {Vector2} b - The second vector.
  2431. * @return {Vector2} A reference to this vector.
  2432. */
  2433. addVectors( a, b ) {
  2434. this.x = a.x + b.x;
  2435. this.y = a.y + b.y;
  2436. return this;
  2437. }
  2438. /**
  2439. * Adds the given vector scaled by the given factor to this instance.
  2440. *
  2441. * @param {Vector2} v - The vector.
  2442. * @param {number} s - The factor that scales `v`.
  2443. * @return {Vector2} A reference to this vector.
  2444. */
  2445. addScaledVector( v, s ) {
  2446. this.x += v.x * s;
  2447. this.y += v.y * s;
  2448. return this;
  2449. }
  2450. /**
  2451. * Subtracts the given vector from this instance.
  2452. *
  2453. * @param {Vector2} v - The vector to subtract.
  2454. * @return {Vector2} A reference to this vector.
  2455. */
  2456. sub( v ) {
  2457. this.x -= v.x;
  2458. this.y -= v.y;
  2459. return this;
  2460. }
  2461. /**
  2462. * Subtracts the given scalar value from all components of this instance.
  2463. *
  2464. * @param {number} s - The scalar to subtract.
  2465. * @return {Vector2} A reference to this vector.
  2466. */
  2467. subScalar( s ) {
  2468. this.x -= s;
  2469. this.y -= s;
  2470. return this;
  2471. }
  2472. /**
  2473. * Subtracts the given vectors and stores the result in this instance.
  2474. *
  2475. * @param {Vector2} a - The first vector.
  2476. * @param {Vector2} b - The second vector.
  2477. * @return {Vector2} A reference to this vector.
  2478. */
  2479. subVectors( a, b ) {
  2480. this.x = a.x - b.x;
  2481. this.y = a.y - b.y;
  2482. return this;
  2483. }
  2484. /**
  2485. * Multiplies the given vector with this instance.
  2486. *
  2487. * @param {Vector2} v - The vector to multiply.
  2488. * @return {Vector2} A reference to this vector.
  2489. */
  2490. multiply( v ) {
  2491. this.x *= v.x;
  2492. this.y *= v.y;
  2493. return this;
  2494. }
  2495. /**
  2496. * Multiplies the given scalar value with all components of this instance.
  2497. *
  2498. * @param {number} scalar - The scalar to multiply.
  2499. * @return {Vector2} A reference to this vector.
  2500. */
  2501. multiplyScalar( scalar ) {
  2502. this.x *= scalar;
  2503. this.y *= scalar;
  2504. return this;
  2505. }
  2506. /**
  2507. * Divides this instance by the given vector.
  2508. *
  2509. * @param {Vector2} v - The vector to divide.
  2510. * @return {Vector2} A reference to this vector.
  2511. */
  2512. divide( v ) {
  2513. this.x /= v.x;
  2514. this.y /= v.y;
  2515. return this;
  2516. }
  2517. /**
  2518. * Divides this vector by the given scalar.
  2519. *
  2520. * @param {number} scalar - The scalar to divide.
  2521. * @return {Vector2} A reference to this vector.
  2522. */
  2523. divideScalar( scalar ) {
  2524. return this.multiplyScalar( 1 / scalar );
  2525. }
  2526. /**
  2527. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2528. * the given 3x3 matrix.
  2529. *
  2530. * @param {Matrix3} m - The matrix to apply.
  2531. * @return {Vector2} A reference to this vector.
  2532. */
  2533. applyMatrix3( m ) {
  2534. const x = this.x, y = this.y;
  2535. const e = m.elements;
  2536. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2537. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2538. return this;
  2539. }
  2540. /**
  2541. * If this vector's x or y value is greater than the given vector's x or y
  2542. * value, replace that value with the corresponding min value.
  2543. *
  2544. * @param {Vector2} v - The vector.
  2545. * @return {Vector2} A reference to this vector.
  2546. */
  2547. min( v ) {
  2548. this.x = Math.min( this.x, v.x );
  2549. this.y = Math.min( this.y, v.y );
  2550. return this;
  2551. }
  2552. /**
  2553. * If this vector's x or y value is less than the given vector's x or y
  2554. * value, replace that value with the corresponding max value.
  2555. *
  2556. * @param {Vector2} v - The vector.
  2557. * @return {Vector2} A reference to this vector.
  2558. */
  2559. max( v ) {
  2560. this.x = Math.max( this.x, v.x );
  2561. this.y = Math.max( this.y, v.y );
  2562. return this;
  2563. }
  2564. /**
  2565. * If this vector's x or y value is greater than the max vector's x or y
  2566. * value, it is replaced by the corresponding value.
  2567. * If this vector's x or y value is less than the min vector's x or y value,
  2568. * it is replaced by the corresponding value.
  2569. *
  2570. * @param {Vector2} min - The minimum x and y values.
  2571. * @param {Vector2} max - The maximum x and y values in the desired range.
  2572. * @return {Vector2} A reference to this vector.
  2573. */
  2574. clamp( min, max ) {
  2575. // assumes min < max, componentwise
  2576. this.x = clamp( this.x, min.x, max.x );
  2577. this.y = clamp( this.y, min.y, max.y );
  2578. return this;
  2579. }
  2580. /**
  2581. * If this vector's x or y values are greater than the max value, they are
  2582. * replaced by the max value.
  2583. * If this vector's x or y values are less than the min value, they are
  2584. * replaced by the min value.
  2585. *
  2586. * @param {number} minVal - The minimum value the components will be clamped to.
  2587. * @param {number} maxVal - The maximum value the components will be clamped to.
  2588. * @return {Vector2} A reference to this vector.
  2589. */
  2590. clampScalar( minVal, maxVal ) {
  2591. this.x = clamp( this.x, minVal, maxVal );
  2592. this.y = clamp( this.y, minVal, maxVal );
  2593. return this;
  2594. }
  2595. /**
  2596. * If this vector's length is greater than the max value, it is replaced by
  2597. * the max value.
  2598. * If this vector's length is less than the min value, it is replaced by the
  2599. * min value.
  2600. *
  2601. * @param {number} min - The minimum value the vector length will be clamped to.
  2602. * @param {number} max - The maximum value the vector length will be clamped to.
  2603. * @return {Vector2} A reference to this vector.
  2604. */
  2605. clampLength( min, max ) {
  2606. const length = this.length();
  2607. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2608. }
  2609. /**
  2610. * The components of this vector are rounded down to the nearest integer value.
  2611. *
  2612. * @return {Vector2} A reference to this vector.
  2613. */
  2614. floor() {
  2615. this.x = Math.floor( this.x );
  2616. this.y = Math.floor( this.y );
  2617. return this;
  2618. }
  2619. /**
  2620. * The components of this vector are rounded up to the nearest integer value.
  2621. *
  2622. * @return {Vector2} A reference to this vector.
  2623. */
  2624. ceil() {
  2625. this.x = Math.ceil( this.x );
  2626. this.y = Math.ceil( this.y );
  2627. return this;
  2628. }
  2629. /**
  2630. * The components of this vector are rounded to the nearest integer value
  2631. *
  2632. * @return {Vector2} A reference to this vector.
  2633. */
  2634. round() {
  2635. this.x = Math.round( this.x );
  2636. this.y = Math.round( this.y );
  2637. return this;
  2638. }
  2639. /**
  2640. * The components of this vector are rounded towards zero (up if negative,
  2641. * down if positive) to an integer value.
  2642. *
  2643. * @return {Vector2} A reference to this vector.
  2644. */
  2645. roundToZero() {
  2646. this.x = Math.trunc( this.x );
  2647. this.y = Math.trunc( this.y );
  2648. return this;
  2649. }
  2650. /**
  2651. * Inverts this vector - i.e. sets x = -x and y = -y.
  2652. *
  2653. * @return {Vector2} A reference to this vector.
  2654. */
  2655. negate() {
  2656. this.x = - this.x;
  2657. this.y = - this.y;
  2658. return this;
  2659. }
  2660. /**
  2661. * Calculates the dot product of the given vector with this instance.
  2662. *
  2663. * @param {Vector2} v - The vector to compute the dot product with.
  2664. * @return {number} The result of the dot product.
  2665. */
  2666. dot( v ) {
  2667. return this.x * v.x + this.y * v.y;
  2668. }
  2669. /**
  2670. * Calculates the cross product of the given vector with this instance.
  2671. *
  2672. * @param {Vector2} v - The vector to compute the cross product with.
  2673. * @return {number} The result of the cross product.
  2674. */
  2675. cross( v ) {
  2676. return this.x * v.y - this.y * v.x;
  2677. }
  2678. /**
  2679. * Computes the square of the Euclidean length (straight-line length) from
  2680. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2681. * compare the length squared instead as it is slightly more efficient to calculate.
  2682. *
  2683. * @return {number} The square length of this vector.
  2684. */
  2685. lengthSq() {
  2686. return this.x * this.x + this.y * this.y;
  2687. }
  2688. /**
  2689. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2690. *
  2691. * @return {number} The length of this vector.
  2692. */
  2693. length() {
  2694. return Math.sqrt( this.x * this.x + this.y * this.y );
  2695. }
  2696. /**
  2697. * Computes the Manhattan length of this vector.
  2698. *
  2699. * @return {number} The length of this vector.
  2700. */
  2701. manhattanLength() {
  2702. return Math.abs( this.x ) + Math.abs( this.y );
  2703. }
  2704. /**
  2705. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2706. * with the same direction as this one, but with a vector length of `1`.
  2707. *
  2708. * @return {Vector2} A reference to this vector.
  2709. */
  2710. normalize() {
  2711. return this.divideScalar( this.length() || 1 );
  2712. }
  2713. /**
  2714. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2715. *
  2716. * @return {number} The angle in radians.
  2717. */
  2718. angle() {
  2719. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2720. return angle;
  2721. }
  2722. /**
  2723. * Returns the angle between the given vector and this instance in radians.
  2724. *
  2725. * @param {Vector2} v - The vector to compute the angle with.
  2726. * @return {number} The angle in radians.
  2727. */
  2728. angleTo( v ) {
  2729. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2730. if ( denominator === 0 ) return Math.PI / 2;
  2731. const theta = this.dot( v ) / denominator;
  2732. // clamp, to handle numerical problems
  2733. return Math.acos( clamp( theta, -1, 1 ) );
  2734. }
  2735. /**
  2736. * Computes the distance from the given vector to this instance.
  2737. *
  2738. * @param {Vector2} v - The vector to compute the distance to.
  2739. * @return {number} The distance.
  2740. */
  2741. distanceTo( v ) {
  2742. return Math.sqrt( this.distanceToSquared( v ) );
  2743. }
  2744. /**
  2745. * Computes the squared distance from the given vector to this instance.
  2746. * If you are just comparing the distance with another distance, you should compare
  2747. * the distance squared instead as it is slightly more efficient to calculate.
  2748. *
  2749. * @param {Vector2} v - The vector to compute the squared distance to.
  2750. * @return {number} The squared distance.
  2751. */
  2752. distanceToSquared( v ) {
  2753. const dx = this.x - v.x, dy = this.y - v.y;
  2754. return dx * dx + dy * dy;
  2755. }
  2756. /**
  2757. * Computes the Manhattan distance from the given vector to this instance.
  2758. *
  2759. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2760. * @return {number} The Manhattan distance.
  2761. */
  2762. manhattanDistanceTo( v ) {
  2763. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2764. }
  2765. /**
  2766. * Sets this vector to a vector with the same direction as this one, but
  2767. * with the specified length.
  2768. *
  2769. * @param {number} length - The new length of this vector.
  2770. * @return {Vector2} A reference to this vector.
  2771. */
  2772. setLength( length ) {
  2773. return this.normalize().multiplyScalar( length );
  2774. }
  2775. /**
  2776. * Linearly interpolates between the given vector and this instance, where
  2777. * alpha is the percent distance along the line - alpha = 0 will be this
  2778. * vector, and alpha = 1 will be the given one.
  2779. *
  2780. * @param {Vector2} v - The vector to interpolate towards.
  2781. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2782. * @return {Vector2} A reference to this vector.
  2783. */
  2784. lerp( v, alpha ) {
  2785. this.x += ( v.x - this.x ) * alpha;
  2786. this.y += ( v.y - this.y ) * alpha;
  2787. return this;
  2788. }
  2789. /**
  2790. * Linearly interpolates between the given vectors, where alpha is the percent
  2791. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2792. * be the second one. The result is stored in this instance.
  2793. *
  2794. * @param {Vector2} v1 - The first vector.
  2795. * @param {Vector2} v2 - The second vector.
  2796. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2797. * @return {Vector2} A reference to this vector.
  2798. */
  2799. lerpVectors( v1, v2, alpha ) {
  2800. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2801. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2802. return this;
  2803. }
  2804. /**
  2805. * Returns `true` if this vector is equal with the given one.
  2806. *
  2807. * @param {Vector2} v - The vector to test for equality.
  2808. * @return {boolean} Whether this vector is equal with the given one.
  2809. */
  2810. equals( v ) {
  2811. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2812. }
  2813. /**
  2814. * Sets this vector's x value to be `array[ offset ]` and y
  2815. * value to be `array[ offset + 1 ]`.
  2816. *
  2817. * @param {Array<number>} array - An array holding the vector component values.
  2818. * @param {number} [offset=0] - The offset into the array.
  2819. * @return {Vector2} A reference to this vector.
  2820. */
  2821. fromArray( array, offset = 0 ) {
  2822. this.x = array[ offset ];
  2823. this.y = array[ offset + 1 ];
  2824. return this;
  2825. }
  2826. /**
  2827. * Writes the components of this vector to the given array. If no array is provided,
  2828. * the method returns a new instance.
  2829. *
  2830. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2831. * @param {number} [offset=0] - Index of the first element in the array.
  2832. * @return {Array<number>} The vector components.
  2833. */
  2834. toArray( array = [], offset = 0 ) {
  2835. array[ offset ] = this.x;
  2836. array[ offset + 1 ] = this.y;
  2837. return array;
  2838. }
  2839. /**
  2840. * Sets the components of this vector from the given buffer attribute.
  2841. *
  2842. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2843. * @param {number} index - The index into the attribute.
  2844. * @return {Vector2} A reference to this vector.
  2845. */
  2846. fromBufferAttribute( attribute, index ) {
  2847. this.x = attribute.getX( index );
  2848. this.y = attribute.getY( index );
  2849. return this;
  2850. }
  2851. /**
  2852. * Rotates this vector around the given center by the given angle.
  2853. *
  2854. * @param {Vector2} center - The point around which to rotate.
  2855. * @param {number} angle - The angle to rotate, in radians.
  2856. * @return {Vector2} A reference to this vector.
  2857. */
  2858. rotateAround( center, angle ) {
  2859. const c = Math.cos( angle ), s = Math.sin( angle );
  2860. const x = this.x - center.x;
  2861. const y = this.y - center.y;
  2862. this.x = x * c - y * s + center.x;
  2863. this.y = x * s + y * c + center.y;
  2864. return this;
  2865. }
  2866. /**
  2867. * Sets each component of this vector to a pseudo-random value between `0` and
  2868. * `1`, excluding `1`.
  2869. *
  2870. * @return {Vector2} A reference to this vector.
  2871. */
  2872. random() {
  2873. this.x = Math.random();
  2874. this.y = Math.random();
  2875. return this;
  2876. }
  2877. *[ Symbol.iterator ]() {
  2878. yield this.x;
  2879. yield this.y;
  2880. }
  2881. }
  2882. /**
  2883. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2884. *
  2885. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2886. * the corresponding order.
  2887. *
  2888. * Note that three.js expects Quaternions to be normalized.
  2889. * ```js
  2890. * const quaternion = new THREE.Quaternion();
  2891. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2892. *
  2893. * const vector = new THREE.Vector3( 1, 0, 0 );
  2894. * vector.applyQuaternion( quaternion );
  2895. * ```
  2896. */
  2897. class Quaternion {
  2898. /**
  2899. * Constructs a new quaternion.
  2900. *
  2901. * @param {number} [x=0] - The x value of this quaternion.
  2902. * @param {number} [y=0] - The y value of this quaternion.
  2903. * @param {number} [z=0] - The z value of this quaternion.
  2904. * @param {number} [w=1] - The w value of this quaternion.
  2905. */
  2906. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2907. /**
  2908. * This flag can be used for type testing.
  2909. *
  2910. * @type {boolean}
  2911. * @readonly
  2912. * @default true
  2913. */
  2914. this.isQuaternion = true;
  2915. this._x = x;
  2916. this._y = y;
  2917. this._z = z;
  2918. this._w = w;
  2919. }
  2920. /**
  2921. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2922. * quaternion data are managed in flat arrays.
  2923. *
  2924. * @param {Array<number>} dst - The destination array.
  2925. * @param {number} dstOffset - An offset into the destination array.
  2926. * @param {Array<number>} src0 - The source array of the first quaternion.
  2927. * @param {number} srcOffset0 - An offset into the first source array.
  2928. * @param {Array<number>} src1 - The source array of the second quaternion.
  2929. * @param {number} srcOffset1 - An offset into the second source array.
  2930. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2931. * @see {@link Quaternion#slerp}
  2932. */
  2933. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2934. // fuzz-free, array-based Quaternion SLERP operation
  2935. let x0 = src0[ srcOffset0 + 0 ],
  2936. y0 = src0[ srcOffset0 + 1 ],
  2937. z0 = src0[ srcOffset0 + 2 ],
  2938. w0 = src0[ srcOffset0 + 3 ];
  2939. const x1 = src1[ srcOffset1 + 0 ],
  2940. y1 = src1[ srcOffset1 + 1 ],
  2941. z1 = src1[ srcOffset1 + 2 ],
  2942. w1 = src1[ srcOffset1 + 3 ];
  2943. if ( t === 0 ) {
  2944. dst[ dstOffset + 0 ] = x0;
  2945. dst[ dstOffset + 1 ] = y0;
  2946. dst[ dstOffset + 2 ] = z0;
  2947. dst[ dstOffset + 3 ] = w0;
  2948. return;
  2949. }
  2950. if ( t === 1 ) {
  2951. dst[ dstOffset + 0 ] = x1;
  2952. dst[ dstOffset + 1 ] = y1;
  2953. dst[ dstOffset + 2 ] = z1;
  2954. dst[ dstOffset + 3 ] = w1;
  2955. return;
  2956. }
  2957. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2958. let s = 1 - t;
  2959. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2960. dir = ( cos >= 0 ? 1 : -1 ),
  2961. sqrSin = 1 - cos * cos;
  2962. // Skip the Slerp for tiny steps to avoid numeric problems:
  2963. if ( sqrSin > Number.EPSILON ) {
  2964. const sin = Math.sqrt( sqrSin ),
  2965. len = Math.atan2( sin, cos * dir );
  2966. s = Math.sin( s * len ) / sin;
  2967. t = Math.sin( t * len ) / sin;
  2968. }
  2969. const tDir = t * dir;
  2970. x0 = x0 * s + x1 * tDir;
  2971. y0 = y0 * s + y1 * tDir;
  2972. z0 = z0 * s + z1 * tDir;
  2973. w0 = w0 * s + w1 * tDir;
  2974. // Normalize in case we just did a lerp:
  2975. if ( s === 1 - t ) {
  2976. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2977. x0 *= f;
  2978. y0 *= f;
  2979. z0 *= f;
  2980. w0 *= f;
  2981. }
  2982. }
  2983. dst[ dstOffset ] = x0;
  2984. dst[ dstOffset + 1 ] = y0;
  2985. dst[ dstOffset + 2 ] = z0;
  2986. dst[ dstOffset + 3 ] = w0;
  2987. }
  2988. /**
  2989. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  2990. * in flat arrays.
  2991. *
  2992. * @param {Array<number>} dst - The destination array.
  2993. * @param {number} dstOffset - An offset into the destination array.
  2994. * @param {Array<number>} src0 - The source array of the first quaternion.
  2995. * @param {number} srcOffset0 - An offset into the first source array.
  2996. * @param {Array<number>} src1 - The source array of the second quaternion.
  2997. * @param {number} srcOffset1 - An offset into the second source array.
  2998. * @return {Array<number>} The destination array.
  2999. * @see {@link Quaternion#multiplyQuaternions}.
  3000. */
  3001. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3002. const x0 = src0[ srcOffset0 ];
  3003. const y0 = src0[ srcOffset0 + 1 ];
  3004. const z0 = src0[ srcOffset0 + 2 ];
  3005. const w0 = src0[ srcOffset0 + 3 ];
  3006. const x1 = src1[ srcOffset1 ];
  3007. const y1 = src1[ srcOffset1 + 1 ];
  3008. const z1 = src1[ srcOffset1 + 2 ];
  3009. const w1 = src1[ srcOffset1 + 3 ];
  3010. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3011. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3012. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3013. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3014. return dst;
  3015. }
  3016. /**
  3017. * The x value of this quaternion.
  3018. *
  3019. * @type {number}
  3020. * @default 0
  3021. */
  3022. get x() {
  3023. return this._x;
  3024. }
  3025. set x( value ) {
  3026. this._x = value;
  3027. this._onChangeCallback();
  3028. }
  3029. /**
  3030. * The y value of this quaternion.
  3031. *
  3032. * @type {number}
  3033. * @default 0
  3034. */
  3035. get y() {
  3036. return this._y;
  3037. }
  3038. set y( value ) {
  3039. this._y = value;
  3040. this._onChangeCallback();
  3041. }
  3042. /**
  3043. * The z value of this quaternion.
  3044. *
  3045. * @type {number}
  3046. * @default 0
  3047. */
  3048. get z() {
  3049. return this._z;
  3050. }
  3051. set z( value ) {
  3052. this._z = value;
  3053. this._onChangeCallback();
  3054. }
  3055. /**
  3056. * The w value of this quaternion.
  3057. *
  3058. * @type {number}
  3059. * @default 1
  3060. */
  3061. get w() {
  3062. return this._w;
  3063. }
  3064. set w( value ) {
  3065. this._w = value;
  3066. this._onChangeCallback();
  3067. }
  3068. /**
  3069. * Sets the quaternion components.
  3070. *
  3071. * @param {number} x - The x value of this quaternion.
  3072. * @param {number} y - The y value of this quaternion.
  3073. * @param {number} z - The z value of this quaternion.
  3074. * @param {number} w - The w value of this quaternion.
  3075. * @return {Quaternion} A reference to this quaternion.
  3076. */
  3077. set( x, y, z, w ) {
  3078. this._x = x;
  3079. this._y = y;
  3080. this._z = z;
  3081. this._w = w;
  3082. this._onChangeCallback();
  3083. return this;
  3084. }
  3085. /**
  3086. * Returns a new quaternion with copied values from this instance.
  3087. *
  3088. * @return {Quaternion} A clone of this instance.
  3089. */
  3090. clone() {
  3091. return new this.constructor( this._x, this._y, this._z, this._w );
  3092. }
  3093. /**
  3094. * Copies the values of the given quaternion to this instance.
  3095. *
  3096. * @param {Quaternion} quaternion - The quaternion to copy.
  3097. * @return {Quaternion} A reference to this quaternion.
  3098. */
  3099. copy( quaternion ) {
  3100. this._x = quaternion.x;
  3101. this._y = quaternion.y;
  3102. this._z = quaternion.z;
  3103. this._w = quaternion.w;
  3104. this._onChangeCallback();
  3105. return this;
  3106. }
  3107. /**
  3108. * Sets this quaternion from the rotation specified by the given
  3109. * Euler angles.
  3110. *
  3111. * @param {Euler} euler - The Euler angles.
  3112. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3113. * @return {Quaternion} A reference to this quaternion.
  3114. */
  3115. setFromEuler( euler, update = true ) {
  3116. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3117. // http://www.mathworks.com/matlabcentral/fileexchange/
  3118. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3119. // content/SpinCalc.m
  3120. const cos = Math.cos;
  3121. const sin = Math.sin;
  3122. const c1 = cos( x / 2 );
  3123. const c2 = cos( y / 2 );
  3124. const c3 = cos( z / 2 );
  3125. const s1 = sin( x / 2 );
  3126. const s2 = sin( y / 2 );
  3127. const s3 = sin( z / 2 );
  3128. switch ( order ) {
  3129. case 'XYZ':
  3130. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3131. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3132. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3133. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3134. break;
  3135. case 'YXZ':
  3136. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3137. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3138. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3139. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3140. break;
  3141. case 'ZXY':
  3142. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3143. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3144. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3145. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3146. break;
  3147. case 'ZYX':
  3148. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3149. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3150. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3151. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3152. break;
  3153. case 'YZX':
  3154. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3155. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3156. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3157. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3158. break;
  3159. case 'XZY':
  3160. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3161. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3162. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3163. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3164. break;
  3165. default:
  3166. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3167. }
  3168. if ( update === true ) this._onChangeCallback();
  3169. return this;
  3170. }
  3171. /**
  3172. * Sets this quaternion from the given axis and angle.
  3173. *
  3174. * @param {Vector3} axis - The normalized axis.
  3175. * @param {number} angle - The angle in radians.
  3176. * @return {Quaternion} A reference to this quaternion.
  3177. */
  3178. setFromAxisAngle( axis, angle ) {
  3179. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3180. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3181. this._x = axis.x * s;
  3182. this._y = axis.y * s;
  3183. this._z = axis.z * s;
  3184. this._w = Math.cos( halfAngle );
  3185. this._onChangeCallback();
  3186. return this;
  3187. }
  3188. /**
  3189. * Sets this quaternion from the given rotation matrix.
  3190. *
  3191. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3192. * @return {Quaternion} A reference to this quaternion.
  3193. */
  3194. setFromRotationMatrix( m ) {
  3195. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3196. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3197. const te = m.elements,
  3198. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3199. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3200. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3201. trace = m11 + m22 + m33;
  3202. if ( trace > 0 ) {
  3203. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3204. this._w = 0.25 / s;
  3205. this._x = ( m32 - m23 ) * s;
  3206. this._y = ( m13 - m31 ) * s;
  3207. this._z = ( m21 - m12 ) * s;
  3208. } else if ( m11 > m22 && m11 > m33 ) {
  3209. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3210. this._w = ( m32 - m23 ) / s;
  3211. this._x = 0.25 * s;
  3212. this._y = ( m12 + m21 ) / s;
  3213. this._z = ( m13 + m31 ) / s;
  3214. } else if ( m22 > m33 ) {
  3215. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3216. this._w = ( m13 - m31 ) / s;
  3217. this._x = ( m12 + m21 ) / s;
  3218. this._y = 0.25 * s;
  3219. this._z = ( m23 + m32 ) / s;
  3220. } else {
  3221. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3222. this._w = ( m21 - m12 ) / s;
  3223. this._x = ( m13 + m31 ) / s;
  3224. this._y = ( m23 + m32 ) / s;
  3225. this._z = 0.25 * s;
  3226. }
  3227. this._onChangeCallback();
  3228. return this;
  3229. }
  3230. /**
  3231. * Sets this quaternion to the rotation required to rotate the direction vector
  3232. * `vFrom` to the direction vector `vTo`.
  3233. *
  3234. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3235. * @param {Vector3} vTo - The second (normalized) direction vector.
  3236. * @return {Quaternion} A reference to this quaternion.
  3237. */
  3238. setFromUnitVectors( vFrom, vTo ) {
  3239. // assumes direction vectors vFrom and vTo are normalized
  3240. let r = vFrom.dot( vTo ) + 1;
  3241. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3242. // vFrom and vTo point in opposite directions
  3243. r = 0;
  3244. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3245. this._x = - vFrom.y;
  3246. this._y = vFrom.x;
  3247. this._z = 0;
  3248. this._w = r;
  3249. } else {
  3250. this._x = 0;
  3251. this._y = - vFrom.z;
  3252. this._z = vFrom.y;
  3253. this._w = r;
  3254. }
  3255. } else {
  3256. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3257. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3258. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3259. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3260. this._w = r;
  3261. }
  3262. return this.normalize();
  3263. }
  3264. /**
  3265. * Returns the angle between this quaternion and the given one in radians.
  3266. *
  3267. * @param {Quaternion} q - The quaternion to compute the angle with.
  3268. * @return {number} The angle in radians.
  3269. */
  3270. angleTo( q ) {
  3271. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3272. }
  3273. /**
  3274. * Rotates this quaternion by a given angular step to the given quaternion.
  3275. * The method ensures that the final quaternion will not overshoot `q`.
  3276. *
  3277. * @param {Quaternion} q - The target quaternion.
  3278. * @param {number} step - The angular step in radians.
  3279. * @return {Quaternion} A reference to this quaternion.
  3280. */
  3281. rotateTowards( q, step ) {
  3282. const angle = this.angleTo( q );
  3283. if ( angle === 0 ) return this;
  3284. const t = Math.min( 1, step / angle );
  3285. this.slerp( q, t );
  3286. return this;
  3287. }
  3288. /**
  3289. * Sets this quaternion to the identity quaternion; that is, to the
  3290. * quaternion that represents "no rotation".
  3291. *
  3292. * @return {Quaternion} A reference to this quaternion.
  3293. */
  3294. identity() {
  3295. return this.set( 0, 0, 0, 1 );
  3296. }
  3297. /**
  3298. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3299. * quaternion is assumed to have unit length.
  3300. *
  3301. * @return {Quaternion} A reference to this quaternion.
  3302. */
  3303. invert() {
  3304. return this.conjugate();
  3305. }
  3306. /**
  3307. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3308. * quaternion represents the same rotation in the opposite direction about
  3309. * the rotational axis.
  3310. *
  3311. * @return {Quaternion} A reference to this quaternion.
  3312. */
  3313. conjugate() {
  3314. this._x *= -1;
  3315. this._y *= -1;
  3316. this._z *= -1;
  3317. this._onChangeCallback();
  3318. return this;
  3319. }
  3320. /**
  3321. * Calculates the dot product of this quaternion and the given one.
  3322. *
  3323. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3324. * @return {number} The result of the dot product.
  3325. */
  3326. dot( v ) {
  3327. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3328. }
  3329. /**
  3330. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3331. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3332. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3333. * {@link Quaternion#length}.
  3334. *
  3335. * @return {number} The squared Euclidean length.
  3336. */
  3337. lengthSq() {
  3338. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3339. }
  3340. /**
  3341. * Computes the Euclidean length (straight-line length) of this quaternion,
  3342. * considered as a 4 dimensional vector.
  3343. *
  3344. * @return {number} The Euclidean length.
  3345. */
  3346. length() {
  3347. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3348. }
  3349. /**
  3350. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3351. * the same rotation as this one, but has a length equal to `1`.
  3352. *
  3353. * @return {Quaternion} A reference to this quaternion.
  3354. */
  3355. normalize() {
  3356. let l = this.length();
  3357. if ( l === 0 ) {
  3358. this._x = 0;
  3359. this._y = 0;
  3360. this._z = 0;
  3361. this._w = 1;
  3362. } else {
  3363. l = 1 / l;
  3364. this._x = this._x * l;
  3365. this._y = this._y * l;
  3366. this._z = this._z * l;
  3367. this._w = this._w * l;
  3368. }
  3369. this._onChangeCallback();
  3370. return this;
  3371. }
  3372. /**
  3373. * Multiplies this quaternion by the given one.
  3374. *
  3375. * @param {Quaternion} q - The quaternion.
  3376. * @return {Quaternion} A reference to this quaternion.
  3377. */
  3378. multiply( q ) {
  3379. return this.multiplyQuaternions( this, q );
  3380. }
  3381. /**
  3382. * Pre-multiplies this quaternion by the given one.
  3383. *
  3384. * @param {Quaternion} q - The quaternion.
  3385. * @return {Quaternion} A reference to this quaternion.
  3386. */
  3387. premultiply( q ) {
  3388. return this.multiplyQuaternions( q, this );
  3389. }
  3390. /**
  3391. * Multiplies the given quaternions and stores the result in this instance.
  3392. *
  3393. * @param {Quaternion} a - The first quaternion.
  3394. * @param {Quaternion} b - The second quaternion.
  3395. * @return {Quaternion} A reference to this quaternion.
  3396. */
  3397. multiplyQuaternions( a, b ) {
  3398. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3399. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3400. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3401. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3402. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3403. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3404. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3405. this._onChangeCallback();
  3406. return this;
  3407. }
  3408. /**
  3409. * Performs a spherical linear interpolation between quaternions.
  3410. *
  3411. * @param {Quaternion} qb - The target quaternion.
  3412. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3413. * @return {Quaternion} A reference to this quaternion.
  3414. */
  3415. slerp( qb, t ) {
  3416. if ( t === 0 ) return this;
  3417. if ( t === 1 ) return this.copy( qb );
  3418. const x = this._x, y = this._y, z = this._z, w = this._w;
  3419. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3420. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  3421. if ( cosHalfTheta < 0 ) {
  3422. this._w = - qb._w;
  3423. this._x = - qb._x;
  3424. this._y = - qb._y;
  3425. this._z = - qb._z;
  3426. cosHalfTheta = - cosHalfTheta;
  3427. } else {
  3428. this.copy( qb );
  3429. }
  3430. if ( cosHalfTheta >= 1.0 ) {
  3431. this._w = w;
  3432. this._x = x;
  3433. this._y = y;
  3434. this._z = z;
  3435. return this;
  3436. }
  3437. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  3438. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  3439. const s = 1 - t;
  3440. this._w = s * w + t * this._w;
  3441. this._x = s * x + t * this._x;
  3442. this._y = s * y + t * this._y;
  3443. this._z = s * z + t * this._z;
  3444. this.normalize(); // normalize calls _onChangeCallback()
  3445. return this;
  3446. }
  3447. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  3448. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  3449. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3450. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3451. this._w = ( w * ratioA + this._w * ratioB );
  3452. this._x = ( x * ratioA + this._x * ratioB );
  3453. this._y = ( y * ratioA + this._y * ratioB );
  3454. this._z = ( z * ratioA + this._z * ratioB );
  3455. this._onChangeCallback();
  3456. return this;
  3457. }
  3458. /**
  3459. * Performs a spherical linear interpolation between the given quaternions
  3460. * and stores the result in this quaternion.
  3461. *
  3462. * @param {Quaternion} qa - The source quaternion.
  3463. * @param {Quaternion} qb - The target quaternion.
  3464. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3465. * @return {Quaternion} A reference to this quaternion.
  3466. */
  3467. slerpQuaternions( qa, qb, t ) {
  3468. return this.copy( qa ).slerp( qb, t );
  3469. }
  3470. /**
  3471. * Sets this quaternion to a uniformly random, normalized quaternion.
  3472. *
  3473. * @return {Quaternion} A reference to this quaternion.
  3474. */
  3475. random() {
  3476. // Ken Shoemake
  3477. // Uniform random rotations
  3478. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3479. const theta1 = 2 * Math.PI * Math.random();
  3480. const theta2 = 2 * Math.PI * Math.random();
  3481. const x0 = Math.random();
  3482. const r1 = Math.sqrt( 1 - x0 );
  3483. const r2 = Math.sqrt( x0 );
  3484. return this.set(
  3485. r1 * Math.sin( theta1 ),
  3486. r1 * Math.cos( theta1 ),
  3487. r2 * Math.sin( theta2 ),
  3488. r2 * Math.cos( theta2 ),
  3489. );
  3490. }
  3491. /**
  3492. * Returns `true` if this quaternion is equal with the given one.
  3493. *
  3494. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3495. * @return {boolean} Whether this quaternion is equal with the given one.
  3496. */
  3497. equals( quaternion ) {
  3498. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3499. }
  3500. /**
  3501. * Sets this quaternion's components from the given array.
  3502. *
  3503. * @param {Array<number>} array - An array holding the quaternion component values.
  3504. * @param {number} [offset=0] - The offset into the array.
  3505. * @return {Quaternion} A reference to this quaternion.
  3506. */
  3507. fromArray( array, offset = 0 ) {
  3508. this._x = array[ offset ];
  3509. this._y = array[ offset + 1 ];
  3510. this._z = array[ offset + 2 ];
  3511. this._w = array[ offset + 3 ];
  3512. this._onChangeCallback();
  3513. return this;
  3514. }
  3515. /**
  3516. * Writes the components of this quaternion to the given array. If no array is provided,
  3517. * the method returns a new instance.
  3518. *
  3519. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3520. * @param {number} [offset=0] - Index of the first element in the array.
  3521. * @return {Array<number>} The quaternion components.
  3522. */
  3523. toArray( array = [], offset = 0 ) {
  3524. array[ offset ] = this._x;
  3525. array[ offset + 1 ] = this._y;
  3526. array[ offset + 2 ] = this._z;
  3527. array[ offset + 3 ] = this._w;
  3528. return array;
  3529. }
  3530. /**
  3531. * Sets the components of this quaternion from the given buffer attribute.
  3532. *
  3533. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3534. * @param {number} index - The index into the attribute.
  3535. * @return {Quaternion} A reference to this quaternion.
  3536. */
  3537. fromBufferAttribute( attribute, index ) {
  3538. this._x = attribute.getX( index );
  3539. this._y = attribute.getY( index );
  3540. this._z = attribute.getZ( index );
  3541. this._w = attribute.getW( index );
  3542. this._onChangeCallback();
  3543. return this;
  3544. }
  3545. /**
  3546. * This methods defines the serialization result of this class. Returns the
  3547. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3548. *
  3549. * @return {Array<number>} The serialized quaternion.
  3550. */
  3551. toJSON() {
  3552. return this.toArray();
  3553. }
  3554. _onChange( callback ) {
  3555. this._onChangeCallback = callback;
  3556. return this;
  3557. }
  3558. _onChangeCallback() {}
  3559. *[ Symbol.iterator ]() {
  3560. yield this._x;
  3561. yield this._y;
  3562. yield this._z;
  3563. yield this._w;
  3564. }
  3565. }
  3566. /**
  3567. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3568. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3569. *
  3570. * - A point in 3D space.
  3571. * - A direction and length in 3D space. In three.js the length will
  3572. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3573. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3574. * - Any arbitrary ordered triplet of numbers.
  3575. *
  3576. * There are other things a 3D vector can be used to represent, such as
  3577. * momentum vectors and so on, however these are the most
  3578. * common uses in three.js.
  3579. *
  3580. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3581. * the corresponding order.
  3582. * ```js
  3583. * const a = new THREE.Vector3( 0, 1, 0 );
  3584. *
  3585. * //no arguments; will be initialised to (0, 0, 0)
  3586. * const b = new THREE.Vector3( );
  3587. *
  3588. * const d = a.distanceTo( b );
  3589. * ```
  3590. */
  3591. class Vector3 {
  3592. /**
  3593. * Constructs a new 3D vector.
  3594. *
  3595. * @param {number} [x=0] - The x value of this vector.
  3596. * @param {number} [y=0] - The y value of this vector.
  3597. * @param {number} [z=0] - The z value of this vector.
  3598. */
  3599. constructor( x = 0, y = 0, z = 0 ) {
  3600. /**
  3601. * This flag can be used for type testing.
  3602. *
  3603. * @type {boolean}
  3604. * @readonly
  3605. * @default true
  3606. */
  3607. Vector3.prototype.isVector3 = true;
  3608. /**
  3609. * The x value of this vector.
  3610. *
  3611. * @type {number}
  3612. */
  3613. this.x = x;
  3614. /**
  3615. * The y value of this vector.
  3616. *
  3617. * @type {number}
  3618. */
  3619. this.y = y;
  3620. /**
  3621. * The z value of this vector.
  3622. *
  3623. * @type {number}
  3624. */
  3625. this.z = z;
  3626. }
  3627. /**
  3628. * Sets the vector components.
  3629. *
  3630. * @param {number} x - The value of the x component.
  3631. * @param {number} y - The value of the y component.
  3632. * @param {number} z - The value of the z component.
  3633. * @return {Vector3} A reference to this vector.
  3634. */
  3635. set( x, y, z ) {
  3636. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3637. this.x = x;
  3638. this.y = y;
  3639. this.z = z;
  3640. return this;
  3641. }
  3642. /**
  3643. * Sets the vector components to the same value.
  3644. *
  3645. * @param {number} scalar - The value to set for all vector components.
  3646. * @return {Vector3} A reference to this vector.
  3647. */
  3648. setScalar( scalar ) {
  3649. this.x = scalar;
  3650. this.y = scalar;
  3651. this.z = scalar;
  3652. return this;
  3653. }
  3654. /**
  3655. * Sets the vector's x component to the given value
  3656. *
  3657. * @param {number} x - The value to set.
  3658. * @return {Vector3} A reference to this vector.
  3659. */
  3660. setX( x ) {
  3661. this.x = x;
  3662. return this;
  3663. }
  3664. /**
  3665. * Sets the vector's y component to the given value
  3666. *
  3667. * @param {number} y - The value to set.
  3668. * @return {Vector3} A reference to this vector.
  3669. */
  3670. setY( y ) {
  3671. this.y = y;
  3672. return this;
  3673. }
  3674. /**
  3675. * Sets the vector's z component to the given value
  3676. *
  3677. * @param {number} z - The value to set.
  3678. * @return {Vector3} A reference to this vector.
  3679. */
  3680. setZ( z ) {
  3681. this.z = z;
  3682. return this;
  3683. }
  3684. /**
  3685. * Allows to set a vector component with an index.
  3686. *
  3687. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3688. * @param {number} value - The value to set.
  3689. * @return {Vector3} A reference to this vector.
  3690. */
  3691. setComponent( index, value ) {
  3692. switch ( index ) {
  3693. case 0: this.x = value; break;
  3694. case 1: this.y = value; break;
  3695. case 2: this.z = value; break;
  3696. default: throw new Error( 'index is out of range: ' + index );
  3697. }
  3698. return this;
  3699. }
  3700. /**
  3701. * Returns the value of the vector component which matches the given index.
  3702. *
  3703. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3704. * @return {number} A vector component value.
  3705. */
  3706. getComponent( index ) {
  3707. switch ( index ) {
  3708. case 0: return this.x;
  3709. case 1: return this.y;
  3710. case 2: return this.z;
  3711. default: throw new Error( 'index is out of range: ' + index );
  3712. }
  3713. }
  3714. /**
  3715. * Returns a new vector with copied values from this instance.
  3716. *
  3717. * @return {Vector3} A clone of this instance.
  3718. */
  3719. clone() {
  3720. return new this.constructor( this.x, this.y, this.z );
  3721. }
  3722. /**
  3723. * Copies the values of the given vector to this instance.
  3724. *
  3725. * @param {Vector3} v - The vector to copy.
  3726. * @return {Vector3} A reference to this vector.
  3727. */
  3728. copy( v ) {
  3729. this.x = v.x;
  3730. this.y = v.y;
  3731. this.z = v.z;
  3732. return this;
  3733. }
  3734. /**
  3735. * Adds the given vector to this instance.
  3736. *
  3737. * @param {Vector3} v - The vector to add.
  3738. * @return {Vector3} A reference to this vector.
  3739. */
  3740. add( v ) {
  3741. this.x += v.x;
  3742. this.y += v.y;
  3743. this.z += v.z;
  3744. return this;
  3745. }
  3746. /**
  3747. * Adds the given scalar value to all components of this instance.
  3748. *
  3749. * @param {number} s - The scalar to add.
  3750. * @return {Vector3} A reference to this vector.
  3751. */
  3752. addScalar( s ) {
  3753. this.x += s;
  3754. this.y += s;
  3755. this.z += s;
  3756. return this;
  3757. }
  3758. /**
  3759. * Adds the given vectors and stores the result in this instance.
  3760. *
  3761. * @param {Vector3} a - The first vector.
  3762. * @param {Vector3} b - The second vector.
  3763. * @return {Vector3} A reference to this vector.
  3764. */
  3765. addVectors( a, b ) {
  3766. this.x = a.x + b.x;
  3767. this.y = a.y + b.y;
  3768. this.z = a.z + b.z;
  3769. return this;
  3770. }
  3771. /**
  3772. * Adds the given vector scaled by the given factor to this instance.
  3773. *
  3774. * @param {Vector3|Vector4} v - The vector.
  3775. * @param {number} s - The factor that scales `v`.
  3776. * @return {Vector3} A reference to this vector.
  3777. */
  3778. addScaledVector( v, s ) {
  3779. this.x += v.x * s;
  3780. this.y += v.y * s;
  3781. this.z += v.z * s;
  3782. return this;
  3783. }
  3784. /**
  3785. * Subtracts the given vector from this instance.
  3786. *
  3787. * @param {Vector3} v - The vector to subtract.
  3788. * @return {Vector3} A reference to this vector.
  3789. */
  3790. sub( v ) {
  3791. this.x -= v.x;
  3792. this.y -= v.y;
  3793. this.z -= v.z;
  3794. return this;
  3795. }
  3796. /**
  3797. * Subtracts the given scalar value from all components of this instance.
  3798. *
  3799. * @param {number} s - The scalar to subtract.
  3800. * @return {Vector3} A reference to this vector.
  3801. */
  3802. subScalar( s ) {
  3803. this.x -= s;
  3804. this.y -= s;
  3805. this.z -= s;
  3806. return this;
  3807. }
  3808. /**
  3809. * Subtracts the given vectors and stores the result in this instance.
  3810. *
  3811. * @param {Vector3} a - The first vector.
  3812. * @param {Vector3} b - The second vector.
  3813. * @return {Vector3} A reference to this vector.
  3814. */
  3815. subVectors( a, b ) {
  3816. this.x = a.x - b.x;
  3817. this.y = a.y - b.y;
  3818. this.z = a.z - b.z;
  3819. return this;
  3820. }
  3821. /**
  3822. * Multiplies the given vector with this instance.
  3823. *
  3824. * @param {Vector3} v - The vector to multiply.
  3825. * @return {Vector3} A reference to this vector.
  3826. */
  3827. multiply( v ) {
  3828. this.x *= v.x;
  3829. this.y *= v.y;
  3830. this.z *= v.z;
  3831. return this;
  3832. }
  3833. /**
  3834. * Multiplies the given scalar value with all components of this instance.
  3835. *
  3836. * @param {number} scalar - The scalar to multiply.
  3837. * @return {Vector3} A reference to this vector.
  3838. */
  3839. multiplyScalar( scalar ) {
  3840. this.x *= scalar;
  3841. this.y *= scalar;
  3842. this.z *= scalar;
  3843. return this;
  3844. }
  3845. /**
  3846. * Multiplies the given vectors and stores the result in this instance.
  3847. *
  3848. * @param {Vector3} a - The first vector.
  3849. * @param {Vector3} b - The second vector.
  3850. * @return {Vector3} A reference to this vector.
  3851. */
  3852. multiplyVectors( a, b ) {
  3853. this.x = a.x * b.x;
  3854. this.y = a.y * b.y;
  3855. this.z = a.z * b.z;
  3856. return this;
  3857. }
  3858. /**
  3859. * Applies the given Euler rotation to this vector.
  3860. *
  3861. * @param {Euler} euler - The Euler angles.
  3862. * @return {Vector3} A reference to this vector.
  3863. */
  3864. applyEuler( euler ) {
  3865. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3866. }
  3867. /**
  3868. * Applies a rotation specified by an axis and an angle to this vector.
  3869. *
  3870. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3871. * @param {number} angle - The angle in radians.
  3872. * @return {Vector3} A reference to this vector.
  3873. */
  3874. applyAxisAngle( axis, angle ) {
  3875. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3876. }
  3877. /**
  3878. * Multiplies this vector with the given 3x3 matrix.
  3879. *
  3880. * @param {Matrix3} m - The 3x3 matrix.
  3881. * @return {Vector3} A reference to this vector.
  3882. */
  3883. applyMatrix3( m ) {
  3884. const x = this.x, y = this.y, z = this.z;
  3885. const e = m.elements;
  3886. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3887. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3888. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3889. return this;
  3890. }
  3891. /**
  3892. * Multiplies this vector by the given normal matrix and normalizes
  3893. * the result.
  3894. *
  3895. * @param {Matrix3} m - The normal matrix.
  3896. * @return {Vector3} A reference to this vector.
  3897. */
  3898. applyNormalMatrix( m ) {
  3899. return this.applyMatrix3( m ).normalize();
  3900. }
  3901. /**
  3902. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3903. * divides by perspective.
  3904. *
  3905. * @param {Matrix4} m - The matrix to apply.
  3906. * @return {Vector3} A reference to this vector.
  3907. */
  3908. applyMatrix4( m ) {
  3909. const x = this.x, y = this.y, z = this.z;
  3910. const e = m.elements;
  3911. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3912. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3913. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3914. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3915. return this;
  3916. }
  3917. /**
  3918. * Applies the given Quaternion to this vector.
  3919. *
  3920. * @param {Quaternion} q - The Quaternion.
  3921. * @return {Vector3} A reference to this vector.
  3922. */
  3923. applyQuaternion( q ) {
  3924. // quaternion q is assumed to have unit length
  3925. const vx = this.x, vy = this.y, vz = this.z;
  3926. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3927. // t = 2 * cross( q.xyz, v );
  3928. const tx = 2 * ( qy * vz - qz * vy );
  3929. const ty = 2 * ( qz * vx - qx * vz );
  3930. const tz = 2 * ( qx * vy - qy * vx );
  3931. // v + q.w * t + cross( q.xyz, t );
  3932. this.x = vx + qw * tx + qy * tz - qz * ty;
  3933. this.y = vy + qw * ty + qz * tx - qx * tz;
  3934. this.z = vz + qw * tz + qx * ty - qy * tx;
  3935. return this;
  3936. }
  3937. /**
  3938. * Projects this vector from world space into the camera's normalized
  3939. * device coordinate (NDC) space.
  3940. *
  3941. * @param {Camera} camera - The camera.
  3942. * @return {Vector3} A reference to this vector.
  3943. */
  3944. project( camera ) {
  3945. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3946. }
  3947. /**
  3948. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3949. * space into world space.
  3950. *
  3951. * @param {Camera} camera - The camera.
  3952. * @return {Vector3} A reference to this vector.
  3953. */
  3954. unproject( camera ) {
  3955. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3956. }
  3957. /**
  3958. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3959. * subset of the given 4x4 matrix and then normalizes the result.
  3960. *
  3961. * @param {Matrix4} m - The matrix.
  3962. * @return {Vector3} A reference to this vector.
  3963. */
  3964. transformDirection( m ) {
  3965. // input: THREE.Matrix4 affine matrix
  3966. // vector interpreted as a direction
  3967. const x = this.x, y = this.y, z = this.z;
  3968. const e = m.elements;
  3969. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  3970. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  3971. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  3972. return this.normalize();
  3973. }
  3974. /**
  3975. * Divides this instance by the given vector.
  3976. *
  3977. * @param {Vector3} v - The vector to divide.
  3978. * @return {Vector3} A reference to this vector.
  3979. */
  3980. divide( v ) {
  3981. this.x /= v.x;
  3982. this.y /= v.y;
  3983. this.z /= v.z;
  3984. return this;
  3985. }
  3986. /**
  3987. * Divides this vector by the given scalar.
  3988. *
  3989. * @param {number} scalar - The scalar to divide.
  3990. * @return {Vector3} A reference to this vector.
  3991. */
  3992. divideScalar( scalar ) {
  3993. return this.multiplyScalar( 1 / scalar );
  3994. }
  3995. /**
  3996. * If this vector's x, y or z value is greater than the given vector's x, y or z
  3997. * value, replace that value with the corresponding min value.
  3998. *
  3999. * @param {Vector3} v - The vector.
  4000. * @return {Vector3} A reference to this vector.
  4001. */
  4002. min( v ) {
  4003. this.x = Math.min( this.x, v.x );
  4004. this.y = Math.min( this.y, v.y );
  4005. this.z = Math.min( this.z, v.z );
  4006. return this;
  4007. }
  4008. /**
  4009. * If this vector's x, y or z value is less than the given vector's x, y or z
  4010. * value, replace that value with the corresponding max value.
  4011. *
  4012. * @param {Vector3} v - The vector.
  4013. * @return {Vector3} A reference to this vector.
  4014. */
  4015. max( v ) {
  4016. this.x = Math.max( this.x, v.x );
  4017. this.y = Math.max( this.y, v.y );
  4018. this.z = Math.max( this.z, v.z );
  4019. return this;
  4020. }
  4021. /**
  4022. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4023. * value, it is replaced by the corresponding value.
  4024. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4025. * it is replaced by the corresponding value.
  4026. *
  4027. * @param {Vector3} min - The minimum x, y and z values.
  4028. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4029. * @return {Vector3} A reference to this vector.
  4030. */
  4031. clamp( min, max ) {
  4032. // assumes min < max, componentwise
  4033. this.x = clamp( this.x, min.x, max.x );
  4034. this.y = clamp( this.y, min.y, max.y );
  4035. this.z = clamp( this.z, min.z, max.z );
  4036. return this;
  4037. }
  4038. /**
  4039. * If this vector's x, y or z values are greater than the max value, they are
  4040. * replaced by the max value.
  4041. * If this vector's x, y or z values are less than the min value, they are
  4042. * replaced by the min value.
  4043. *
  4044. * @param {number} minVal - The minimum value the components will be clamped to.
  4045. * @param {number} maxVal - The maximum value the components will be clamped to.
  4046. * @return {Vector3} A reference to this vector.
  4047. */
  4048. clampScalar( minVal, maxVal ) {
  4049. this.x = clamp( this.x, minVal, maxVal );
  4050. this.y = clamp( this.y, minVal, maxVal );
  4051. this.z = clamp( this.z, minVal, maxVal );
  4052. return this;
  4053. }
  4054. /**
  4055. * If this vector's length is greater than the max value, it is replaced by
  4056. * the max value.
  4057. * If this vector's length is less than the min value, it is replaced by the
  4058. * min value.
  4059. *
  4060. * @param {number} min - The minimum value the vector length will be clamped to.
  4061. * @param {number} max - The maximum value the vector length will be clamped to.
  4062. * @return {Vector3} A reference to this vector.
  4063. */
  4064. clampLength( min, max ) {
  4065. const length = this.length();
  4066. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4067. }
  4068. /**
  4069. * The components of this vector are rounded down to the nearest integer value.
  4070. *
  4071. * @return {Vector3} A reference to this vector.
  4072. */
  4073. floor() {
  4074. this.x = Math.floor( this.x );
  4075. this.y = Math.floor( this.y );
  4076. this.z = Math.floor( this.z );
  4077. return this;
  4078. }
  4079. /**
  4080. * The components of this vector are rounded up to the nearest integer value.
  4081. *
  4082. * @return {Vector3} A reference to this vector.
  4083. */
  4084. ceil() {
  4085. this.x = Math.ceil( this.x );
  4086. this.y = Math.ceil( this.y );
  4087. this.z = Math.ceil( this.z );
  4088. return this;
  4089. }
  4090. /**
  4091. * The components of this vector are rounded to the nearest integer value
  4092. *
  4093. * @return {Vector3} A reference to this vector.
  4094. */
  4095. round() {
  4096. this.x = Math.round( this.x );
  4097. this.y = Math.round( this.y );
  4098. this.z = Math.round( this.z );
  4099. return this;
  4100. }
  4101. /**
  4102. * The components of this vector are rounded towards zero (up if negative,
  4103. * down if positive) to an integer value.
  4104. *
  4105. * @return {Vector3} A reference to this vector.
  4106. */
  4107. roundToZero() {
  4108. this.x = Math.trunc( this.x );
  4109. this.y = Math.trunc( this.y );
  4110. this.z = Math.trunc( this.z );
  4111. return this;
  4112. }
  4113. /**
  4114. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4115. *
  4116. * @return {Vector3} A reference to this vector.
  4117. */
  4118. negate() {
  4119. this.x = - this.x;
  4120. this.y = - this.y;
  4121. this.z = - this.z;
  4122. return this;
  4123. }
  4124. /**
  4125. * Calculates the dot product of the given vector with this instance.
  4126. *
  4127. * @param {Vector3} v - The vector to compute the dot product with.
  4128. * @return {number} The result of the dot product.
  4129. */
  4130. dot( v ) {
  4131. return this.x * v.x + this.y * v.y + this.z * v.z;
  4132. }
  4133. // TODO lengthSquared?
  4134. /**
  4135. * Computes the square of the Euclidean length (straight-line length) from
  4136. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4137. * compare the length squared instead as it is slightly more efficient to calculate.
  4138. *
  4139. * @return {number} The square length of this vector.
  4140. */
  4141. lengthSq() {
  4142. return this.x * this.x + this.y * this.y + this.z * this.z;
  4143. }
  4144. /**
  4145. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4146. *
  4147. * @return {number} The length of this vector.
  4148. */
  4149. length() {
  4150. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4151. }
  4152. /**
  4153. * Computes the Manhattan length of this vector.
  4154. *
  4155. * @return {number} The length of this vector.
  4156. */
  4157. manhattanLength() {
  4158. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4159. }
  4160. /**
  4161. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4162. * with the same direction as this one, but with a vector length of `1`.
  4163. *
  4164. * @return {Vector3} A reference to this vector.
  4165. */
  4166. normalize() {
  4167. return this.divideScalar( this.length() || 1 );
  4168. }
  4169. /**
  4170. * Sets this vector to a vector with the same direction as this one, but
  4171. * with the specified length.
  4172. *
  4173. * @param {number} length - The new length of this vector.
  4174. * @return {Vector3} A reference to this vector.
  4175. */
  4176. setLength( length ) {
  4177. return this.normalize().multiplyScalar( length );
  4178. }
  4179. /**
  4180. * Linearly interpolates between the given vector and this instance, where
  4181. * alpha is the percent distance along the line - alpha = 0 will be this
  4182. * vector, and alpha = 1 will be the given one.
  4183. *
  4184. * @param {Vector3} v - The vector to interpolate towards.
  4185. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4186. * @return {Vector3} A reference to this vector.
  4187. */
  4188. lerp( v, alpha ) {
  4189. this.x += ( v.x - this.x ) * alpha;
  4190. this.y += ( v.y - this.y ) * alpha;
  4191. this.z += ( v.z - this.z ) * alpha;
  4192. return this;
  4193. }
  4194. /**
  4195. * Linearly interpolates between the given vectors, where alpha is the percent
  4196. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4197. * be the second one. The result is stored in this instance.
  4198. *
  4199. * @param {Vector3} v1 - The first vector.
  4200. * @param {Vector3} v2 - The second vector.
  4201. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4202. * @return {Vector3} A reference to this vector.
  4203. */
  4204. lerpVectors( v1, v2, alpha ) {
  4205. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4206. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4207. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4208. return this;
  4209. }
  4210. /**
  4211. * Calculates the cross product of the given vector with this instance.
  4212. *
  4213. * @param {Vector3} v - The vector to compute the cross product with.
  4214. * @return {Vector3} The result of the cross product.
  4215. */
  4216. cross( v ) {
  4217. return this.crossVectors( this, v );
  4218. }
  4219. /**
  4220. * Calculates the cross product of the given vectors and stores the result
  4221. * in this instance.
  4222. *
  4223. * @param {Vector3} a - The first vector.
  4224. * @param {Vector3} b - The second vector.
  4225. * @return {Vector3} A reference to this vector.
  4226. */
  4227. crossVectors( a, b ) {
  4228. const ax = a.x, ay = a.y, az = a.z;
  4229. const bx = b.x, by = b.y, bz = b.z;
  4230. this.x = ay * bz - az * by;
  4231. this.y = az * bx - ax * bz;
  4232. this.z = ax * by - ay * bx;
  4233. return this;
  4234. }
  4235. /**
  4236. * Projects this vector onto the given one.
  4237. *
  4238. * @param {Vector3} v - The vector to project to.
  4239. * @return {Vector3} A reference to this vector.
  4240. */
  4241. projectOnVector( v ) {
  4242. const denominator = v.lengthSq();
  4243. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4244. const scalar = v.dot( this ) / denominator;
  4245. return this.copy( v ).multiplyScalar( scalar );
  4246. }
  4247. /**
  4248. * Projects this vector onto a plane by subtracting this
  4249. * vector projected onto the plane's normal from this vector.
  4250. *
  4251. * @param {Vector3} planeNormal - The plane normal.
  4252. * @return {Vector3} A reference to this vector.
  4253. */
  4254. projectOnPlane( planeNormal ) {
  4255. _vector$c.copy( this ).projectOnVector( planeNormal );
  4256. return this.sub( _vector$c );
  4257. }
  4258. /**
  4259. * Reflects this vector off a plane orthogonal to the given normal vector.
  4260. *
  4261. * @param {Vector3} normal - The (normalized) normal vector.
  4262. * @return {Vector3} A reference to this vector.
  4263. */
  4264. reflect( normal ) {
  4265. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4266. }
  4267. /**
  4268. * Returns the angle between the given vector and this instance in radians.
  4269. *
  4270. * @param {Vector3} v - The vector to compute the angle with.
  4271. * @return {number} The angle in radians.
  4272. */
  4273. angleTo( v ) {
  4274. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4275. if ( denominator === 0 ) return Math.PI / 2;
  4276. const theta = this.dot( v ) / denominator;
  4277. // clamp, to handle numerical problems
  4278. return Math.acos( clamp( theta, -1, 1 ) );
  4279. }
  4280. /**
  4281. * Computes the distance from the given vector to this instance.
  4282. *
  4283. * @param {Vector3} v - The vector to compute the distance to.
  4284. * @return {number} The distance.
  4285. */
  4286. distanceTo( v ) {
  4287. return Math.sqrt( this.distanceToSquared( v ) );
  4288. }
  4289. /**
  4290. * Computes the squared distance from the given vector to this instance.
  4291. * If you are just comparing the distance with another distance, you should compare
  4292. * the distance squared instead as it is slightly more efficient to calculate.
  4293. *
  4294. * @param {Vector3} v - The vector to compute the squared distance to.
  4295. * @return {number} The squared distance.
  4296. */
  4297. distanceToSquared( v ) {
  4298. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4299. return dx * dx + dy * dy + dz * dz;
  4300. }
  4301. /**
  4302. * Computes the Manhattan distance from the given vector to this instance.
  4303. *
  4304. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4305. * @return {number} The Manhattan distance.
  4306. */
  4307. manhattanDistanceTo( v ) {
  4308. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4309. }
  4310. /**
  4311. * Sets the vector components from the given spherical coordinates.
  4312. *
  4313. * @param {Spherical} s - The spherical coordinates.
  4314. * @return {Vector3} A reference to this vector.
  4315. */
  4316. setFromSpherical( s ) {
  4317. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4318. }
  4319. /**
  4320. * Sets the vector components from the given spherical coordinates.
  4321. *
  4322. * @param {number} radius - The radius.
  4323. * @param {number} phi - The phi angle in radians.
  4324. * @param {number} theta - The theta angle in radians.
  4325. * @return {Vector3} A reference to this vector.
  4326. */
  4327. setFromSphericalCoords( radius, phi, theta ) {
  4328. const sinPhiRadius = Math.sin( phi ) * radius;
  4329. this.x = sinPhiRadius * Math.sin( theta );
  4330. this.y = Math.cos( phi ) * radius;
  4331. this.z = sinPhiRadius * Math.cos( theta );
  4332. return this;
  4333. }
  4334. /**
  4335. * Sets the vector components from the given cylindrical coordinates.
  4336. *
  4337. * @param {Cylindrical} c - The cylindrical coordinates.
  4338. * @return {Vector3} A reference to this vector.
  4339. */
  4340. setFromCylindrical( c ) {
  4341. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4342. }
  4343. /**
  4344. * Sets the vector components from the given cylindrical coordinates.
  4345. *
  4346. * @param {number} radius - The radius.
  4347. * @param {number} theta - The theta angle in radians.
  4348. * @param {number} y - The y value.
  4349. * @return {Vector3} A reference to this vector.
  4350. */
  4351. setFromCylindricalCoords( radius, theta, y ) {
  4352. this.x = radius * Math.sin( theta );
  4353. this.y = y;
  4354. this.z = radius * Math.cos( theta );
  4355. return this;
  4356. }
  4357. /**
  4358. * Sets the vector components to the position elements of the
  4359. * given transformation matrix.
  4360. *
  4361. * @param {Matrix4} m - The 4x4 matrix.
  4362. * @return {Vector3} A reference to this vector.
  4363. */
  4364. setFromMatrixPosition( m ) {
  4365. const e = m.elements;
  4366. this.x = e[ 12 ];
  4367. this.y = e[ 13 ];
  4368. this.z = e[ 14 ];
  4369. return this;
  4370. }
  4371. /**
  4372. * Sets the vector components to the scale elements of the
  4373. * given transformation matrix.
  4374. *
  4375. * @param {Matrix4} m - The 4x4 matrix.
  4376. * @return {Vector3} A reference to this vector.
  4377. */
  4378. setFromMatrixScale( m ) {
  4379. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4380. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4381. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4382. this.x = sx;
  4383. this.y = sy;
  4384. this.z = sz;
  4385. return this;
  4386. }
  4387. /**
  4388. * Sets the vector components from the specified matrix column.
  4389. *
  4390. * @param {Matrix4} m - The 4x4 matrix.
  4391. * @param {number} index - The column index.
  4392. * @return {Vector3} A reference to this vector.
  4393. */
  4394. setFromMatrixColumn( m, index ) {
  4395. return this.fromArray( m.elements, index * 4 );
  4396. }
  4397. /**
  4398. * Sets the vector components from the specified matrix column.
  4399. *
  4400. * @param {Matrix3} m - The 3x3 matrix.
  4401. * @param {number} index - The column index.
  4402. * @return {Vector3} A reference to this vector.
  4403. */
  4404. setFromMatrix3Column( m, index ) {
  4405. return this.fromArray( m.elements, index * 3 );
  4406. }
  4407. /**
  4408. * Sets the vector components from the given Euler angles.
  4409. *
  4410. * @param {Euler} e - The Euler angles to set.
  4411. * @return {Vector3} A reference to this vector.
  4412. */
  4413. setFromEuler( e ) {
  4414. this.x = e._x;
  4415. this.y = e._y;
  4416. this.z = e._z;
  4417. return this;
  4418. }
  4419. /**
  4420. * Sets the vector components from the RGB components of the
  4421. * given color.
  4422. *
  4423. * @param {Color} c - The color to set.
  4424. * @return {Vector3} A reference to this vector.
  4425. */
  4426. setFromColor( c ) {
  4427. this.x = c.r;
  4428. this.y = c.g;
  4429. this.z = c.b;
  4430. return this;
  4431. }
  4432. /**
  4433. * Returns `true` if this vector is equal with the given one.
  4434. *
  4435. * @param {Vector3} v - The vector to test for equality.
  4436. * @return {boolean} Whether this vector is equal with the given one.
  4437. */
  4438. equals( v ) {
  4439. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4440. }
  4441. /**
  4442. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4443. * and z value to be `array[ offset + 2 ]`.
  4444. *
  4445. * @param {Array<number>} array - An array holding the vector component values.
  4446. * @param {number} [offset=0] - The offset into the array.
  4447. * @return {Vector3} A reference to this vector.
  4448. */
  4449. fromArray( array, offset = 0 ) {
  4450. this.x = array[ offset ];
  4451. this.y = array[ offset + 1 ];
  4452. this.z = array[ offset + 2 ];
  4453. return this;
  4454. }
  4455. /**
  4456. * Writes the components of this vector to the given array. If no array is provided,
  4457. * the method returns a new instance.
  4458. *
  4459. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4460. * @param {number} [offset=0] - Index of the first element in the array.
  4461. * @return {Array<number>} The vector components.
  4462. */
  4463. toArray( array = [], offset = 0 ) {
  4464. array[ offset ] = this.x;
  4465. array[ offset + 1 ] = this.y;
  4466. array[ offset + 2 ] = this.z;
  4467. return array;
  4468. }
  4469. /**
  4470. * Sets the components of this vector from the given buffer attribute.
  4471. *
  4472. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4473. * @param {number} index - The index into the attribute.
  4474. * @return {Vector3} A reference to this vector.
  4475. */
  4476. fromBufferAttribute( attribute, index ) {
  4477. this.x = attribute.getX( index );
  4478. this.y = attribute.getY( index );
  4479. this.z = attribute.getZ( index );
  4480. return this;
  4481. }
  4482. /**
  4483. * Sets each component of this vector to a pseudo-random value between `0` and
  4484. * `1`, excluding `1`.
  4485. *
  4486. * @return {Vector3} A reference to this vector.
  4487. */
  4488. random() {
  4489. this.x = Math.random();
  4490. this.y = Math.random();
  4491. this.z = Math.random();
  4492. return this;
  4493. }
  4494. /**
  4495. * Sets this vector to a uniformly random point on a unit sphere.
  4496. *
  4497. * @return {Vector3} A reference to this vector.
  4498. */
  4499. randomDirection() {
  4500. // https://mathworld.wolfram.com/SpherePointPicking.html
  4501. const theta = Math.random() * Math.PI * 2;
  4502. const u = Math.random() * 2 - 1;
  4503. const c = Math.sqrt( 1 - u * u );
  4504. this.x = c * Math.cos( theta );
  4505. this.y = u;
  4506. this.z = c * Math.sin( theta );
  4507. return this;
  4508. }
  4509. *[ Symbol.iterator ]() {
  4510. yield this.x;
  4511. yield this.y;
  4512. yield this.z;
  4513. }
  4514. }
  4515. const _vector$c = /*@__PURE__*/ new Vector3();
  4516. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4517. /**
  4518. * Represents a 3x3 matrix.
  4519. *
  4520. * A Note on Row-Major and Column-Major Ordering:
  4521. *
  4522. * The constructor and {@link Matrix3#set} method take arguments in
  4523. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  4524. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4525. * This means that calling:
  4526. * ```js
  4527. * const m = new THREE.Matrix();
  4528. * m.set( 11, 12, 13,
  4529. * 21, 22, 23,
  4530. * 31, 32, 33 );
  4531. * ```
  4532. * will result in the elements array containing:
  4533. * ```js
  4534. * m.elements = [ 11, 21, 31,
  4535. * 12, 22, 32,
  4536. * 13, 23, 33 ];
  4537. * ```
  4538. * and internally all calculations are performed using column-major ordering.
  4539. * However, as the actual ordering makes no difference mathematically and
  4540. * most people are used to thinking about matrices in row-major order, the
  4541. * three.js documentation shows matrices in row-major order. Just bear in
  4542. * mind that if you are reading the source code, you'll have to take the
  4543. * transpose of any matrices outlined here to make sense of the calculations.
  4544. */
  4545. class Matrix3 {
  4546. /**
  4547. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4548. * in row-major order. If no arguments are provided, the constructor
  4549. * initializes the matrix as an identity matrix.
  4550. *
  4551. * @param {number} [n11] - 1-1 matrix element.
  4552. * @param {number} [n12] - 1-2 matrix element.
  4553. * @param {number} [n13] - 1-3 matrix element.
  4554. * @param {number} [n21] - 2-1 matrix element.
  4555. * @param {number} [n22] - 2-2 matrix element.
  4556. * @param {number} [n23] - 2-3 matrix element.
  4557. * @param {number} [n31] - 3-1 matrix element.
  4558. * @param {number} [n32] - 3-2 matrix element.
  4559. * @param {number} [n33] - 3-3 matrix element.
  4560. */
  4561. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4562. /**
  4563. * This flag can be used for type testing.
  4564. *
  4565. * @type {boolean}
  4566. * @readonly
  4567. * @default true
  4568. */
  4569. Matrix3.prototype.isMatrix3 = true;
  4570. /**
  4571. * A column-major list of matrix values.
  4572. *
  4573. * @type {Array<number>}
  4574. */
  4575. this.elements = [
  4576. 1, 0, 0,
  4577. 0, 1, 0,
  4578. 0, 0, 1
  4579. ];
  4580. if ( n11 !== undefined ) {
  4581. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4582. }
  4583. }
  4584. /**
  4585. * Sets the elements of the matrix.The arguments are supposed to be
  4586. * in row-major order.
  4587. *
  4588. * @param {number} [n11] - 1-1 matrix element.
  4589. * @param {number} [n12] - 1-2 matrix element.
  4590. * @param {number} [n13] - 1-3 matrix element.
  4591. * @param {number} [n21] - 2-1 matrix element.
  4592. * @param {number} [n22] - 2-2 matrix element.
  4593. * @param {number} [n23] - 2-3 matrix element.
  4594. * @param {number} [n31] - 3-1 matrix element.
  4595. * @param {number} [n32] - 3-2 matrix element.
  4596. * @param {number} [n33] - 3-3 matrix element.
  4597. * @return {Matrix3} A reference to this matrix.
  4598. */
  4599. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4600. const te = this.elements;
  4601. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4602. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4603. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4604. return this;
  4605. }
  4606. /**
  4607. * Sets this matrix to the 3x3 identity matrix.
  4608. *
  4609. * @return {Matrix3} A reference to this matrix.
  4610. */
  4611. identity() {
  4612. this.set(
  4613. 1, 0, 0,
  4614. 0, 1, 0,
  4615. 0, 0, 1
  4616. );
  4617. return this;
  4618. }
  4619. /**
  4620. * Copies the values of the given matrix to this instance.
  4621. *
  4622. * @param {Matrix3} m - The matrix to copy.
  4623. * @return {Matrix3} A reference to this matrix.
  4624. */
  4625. copy( m ) {
  4626. const te = this.elements;
  4627. const me = m.elements;
  4628. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4629. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4630. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4631. return this;
  4632. }
  4633. /**
  4634. * Extracts the basis of this matrix into the three axis vectors provided.
  4635. *
  4636. * @param {Vector3} xAxis - The basis's x axis.
  4637. * @param {Vector3} yAxis - The basis's y axis.
  4638. * @param {Vector3} zAxis - The basis's z axis.
  4639. * @return {Matrix3} A reference to this matrix.
  4640. */
  4641. extractBasis( xAxis, yAxis, zAxis ) {
  4642. xAxis.setFromMatrix3Column( this, 0 );
  4643. yAxis.setFromMatrix3Column( this, 1 );
  4644. zAxis.setFromMatrix3Column( this, 2 );
  4645. return this;
  4646. }
  4647. /**
  4648. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4649. *
  4650. * @param {Matrix4} m - The 4x4 matrix.
  4651. * @return {Matrix3} A reference to this matrix.
  4652. */
  4653. setFromMatrix4( m ) {
  4654. const me = m.elements;
  4655. this.set(
  4656. me[ 0 ], me[ 4 ], me[ 8 ],
  4657. me[ 1 ], me[ 5 ], me[ 9 ],
  4658. me[ 2 ], me[ 6 ], me[ 10 ]
  4659. );
  4660. return this;
  4661. }
  4662. /**
  4663. * Post-multiplies this matrix by the given 3x3 matrix.
  4664. *
  4665. * @param {Matrix3} m - The matrix to multiply with.
  4666. * @return {Matrix3} A reference to this matrix.
  4667. */
  4668. multiply( m ) {
  4669. return this.multiplyMatrices( this, m );
  4670. }
  4671. /**
  4672. * Pre-multiplies this matrix by the given 3x3 matrix.
  4673. *
  4674. * @param {Matrix3} m - The matrix to multiply with.
  4675. * @return {Matrix3} A reference to this matrix.
  4676. */
  4677. premultiply( m ) {
  4678. return this.multiplyMatrices( m, this );
  4679. }
  4680. /**
  4681. * Multiples the given 3x3 matrices and stores the result
  4682. * in this matrix.
  4683. *
  4684. * @param {Matrix3} a - The first matrix.
  4685. * @param {Matrix3} b - The second matrix.
  4686. * @return {Matrix3} A reference to this matrix.
  4687. */
  4688. multiplyMatrices( a, b ) {
  4689. const ae = a.elements;
  4690. const be = b.elements;
  4691. const te = this.elements;
  4692. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4693. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4694. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4695. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4696. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4697. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4698. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4699. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4700. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4701. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4702. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4703. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4704. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4705. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4706. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4707. return this;
  4708. }
  4709. /**
  4710. * Multiplies every component of the matrix by the given scalar.
  4711. *
  4712. * @param {number} s - The scalar.
  4713. * @return {Matrix3} A reference to this matrix.
  4714. */
  4715. multiplyScalar( s ) {
  4716. const te = this.elements;
  4717. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4718. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4719. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4720. return this;
  4721. }
  4722. /**
  4723. * Computes and returns the determinant of this matrix.
  4724. *
  4725. * @return {number} The determinant.
  4726. */
  4727. determinant() {
  4728. const te = this.elements;
  4729. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4730. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4731. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4732. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4733. }
  4734. /**
  4735. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  4736. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4737. * a zero matrix instead.
  4738. *
  4739. * @return {Matrix3} A reference to this matrix.
  4740. */
  4741. invert() {
  4742. const te = this.elements,
  4743. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4744. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4745. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4746. t11 = n33 * n22 - n32 * n23,
  4747. t12 = n32 * n13 - n33 * n12,
  4748. t13 = n23 * n12 - n22 * n13,
  4749. det = n11 * t11 + n21 * t12 + n31 * t13;
  4750. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4751. const detInv = 1 / det;
  4752. te[ 0 ] = t11 * detInv;
  4753. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4754. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4755. te[ 3 ] = t12 * detInv;
  4756. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4757. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4758. te[ 6 ] = t13 * detInv;
  4759. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4760. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4761. return this;
  4762. }
  4763. /**
  4764. * Transposes this matrix in place.
  4765. *
  4766. * @return {Matrix3} A reference to this matrix.
  4767. */
  4768. transpose() {
  4769. let tmp;
  4770. const m = this.elements;
  4771. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4772. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4773. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4774. return this;
  4775. }
  4776. /**
  4777. * Computes the normal matrix which is the inverse transpose of the upper
  4778. * left 3x3 portion of the given 4x4 matrix.
  4779. *
  4780. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4781. * @return {Matrix3} A reference to this matrix.
  4782. */
  4783. getNormalMatrix( matrix4 ) {
  4784. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4785. }
  4786. /**
  4787. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4788. *
  4789. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4790. * @return {Matrix3} A reference to this matrix.
  4791. */
  4792. transposeIntoArray( r ) {
  4793. const m = this.elements;
  4794. r[ 0 ] = m[ 0 ];
  4795. r[ 1 ] = m[ 3 ];
  4796. r[ 2 ] = m[ 6 ];
  4797. r[ 3 ] = m[ 1 ];
  4798. r[ 4 ] = m[ 4 ];
  4799. r[ 5 ] = m[ 7 ];
  4800. r[ 6 ] = m[ 2 ];
  4801. r[ 7 ] = m[ 5 ];
  4802. r[ 8 ] = m[ 8 ];
  4803. return this;
  4804. }
  4805. /**
  4806. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4807. *
  4808. * @param {number} tx - Offset x.
  4809. * @param {number} ty - Offset y.
  4810. * @param {number} sx - Repeat x.
  4811. * @param {number} sy - Repeat y.
  4812. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4813. * @param {number} cx - Center x of rotation.
  4814. * @param {number} cy - Center y of rotation
  4815. * @return {Matrix3} A reference to this matrix.
  4816. */
  4817. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4818. const c = Math.cos( rotation );
  4819. const s = Math.sin( rotation );
  4820. this.set(
  4821. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4822. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4823. 0, 0, 1
  4824. );
  4825. return this;
  4826. }
  4827. /**
  4828. * Scales this matrix with the given scalar values.
  4829. *
  4830. * @param {number} sx - The amount to scale in the X axis.
  4831. * @param {number} sy - The amount to scale in the Y axis.
  4832. * @return {Matrix3} A reference to this matrix.
  4833. */
  4834. scale( sx, sy ) {
  4835. this.premultiply( _m3.makeScale( sx, sy ) );
  4836. return this;
  4837. }
  4838. /**
  4839. * Rotates this matrix by the given angle.
  4840. *
  4841. * @param {number} theta - The rotation in radians.
  4842. * @return {Matrix3} A reference to this matrix.
  4843. */
  4844. rotate( theta ) {
  4845. this.premultiply( _m3.makeRotation( - theta ) );
  4846. return this;
  4847. }
  4848. /**
  4849. * Translates this matrix by the given scalar values.
  4850. *
  4851. * @param {number} tx - The amount to translate in the X axis.
  4852. * @param {number} ty - The amount to translate in the Y axis.
  4853. * @return {Matrix3} A reference to this matrix.
  4854. */
  4855. translate( tx, ty ) {
  4856. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4857. return this;
  4858. }
  4859. // for 2D Transforms
  4860. /**
  4861. * Sets this matrix as a 2D translation transform.
  4862. *
  4863. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4864. * @param {number} y - The amount to translate in the Y axis.
  4865. * @return {Matrix3} A reference to this matrix.
  4866. */
  4867. makeTranslation( x, y ) {
  4868. if ( x.isVector2 ) {
  4869. this.set(
  4870. 1, 0, x.x,
  4871. 0, 1, x.y,
  4872. 0, 0, 1
  4873. );
  4874. } else {
  4875. this.set(
  4876. 1, 0, x,
  4877. 0, 1, y,
  4878. 0, 0, 1
  4879. );
  4880. }
  4881. return this;
  4882. }
  4883. /**
  4884. * Sets this matrix as a 2D rotational transformation.
  4885. *
  4886. * @param {number} theta - The rotation in radians.
  4887. * @return {Matrix3} A reference to this matrix.
  4888. */
  4889. makeRotation( theta ) {
  4890. // counterclockwise
  4891. const c = Math.cos( theta );
  4892. const s = Math.sin( theta );
  4893. this.set(
  4894. c, - s, 0,
  4895. s, c, 0,
  4896. 0, 0, 1
  4897. );
  4898. return this;
  4899. }
  4900. /**
  4901. * Sets this matrix as a 2D scale transform.
  4902. *
  4903. * @param {number} x - The amount to scale in the X axis.
  4904. * @param {number} y - The amount to scale in the Y axis.
  4905. * @return {Matrix3} A reference to this matrix.
  4906. */
  4907. makeScale( x, y ) {
  4908. this.set(
  4909. x, 0, 0,
  4910. 0, y, 0,
  4911. 0, 0, 1
  4912. );
  4913. return this;
  4914. }
  4915. /**
  4916. * Returns `true` if this matrix is equal with the given one.
  4917. *
  4918. * @param {Matrix3} matrix - The matrix to test for equality.
  4919. * @return {boolean} Whether this matrix is equal with the given one.
  4920. */
  4921. equals( matrix ) {
  4922. const te = this.elements;
  4923. const me = matrix.elements;
  4924. for ( let i = 0; i < 9; i ++ ) {
  4925. if ( te[ i ] !== me[ i ] ) return false;
  4926. }
  4927. return true;
  4928. }
  4929. /**
  4930. * Sets the elements of the matrix from the given array.
  4931. *
  4932. * @param {Array<number>} array - The matrix elements in column-major order.
  4933. * @param {number} [offset=0] - Index of the first element in the array.
  4934. * @return {Matrix3} A reference to this matrix.
  4935. */
  4936. fromArray( array, offset = 0 ) {
  4937. for ( let i = 0; i < 9; i ++ ) {
  4938. this.elements[ i ] = array[ i + offset ];
  4939. }
  4940. return this;
  4941. }
  4942. /**
  4943. * Writes the elements of this matrix to the given array. If no array is provided,
  4944. * the method returns a new instance.
  4945. *
  4946. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4947. * @param {number} [offset=0] - Index of the first element in the array.
  4948. * @return {Array<number>} The matrix elements in column-major order.
  4949. */
  4950. toArray( array = [], offset = 0 ) {
  4951. const te = this.elements;
  4952. array[ offset ] = te[ 0 ];
  4953. array[ offset + 1 ] = te[ 1 ];
  4954. array[ offset + 2 ] = te[ 2 ];
  4955. array[ offset + 3 ] = te[ 3 ];
  4956. array[ offset + 4 ] = te[ 4 ];
  4957. array[ offset + 5 ] = te[ 5 ];
  4958. array[ offset + 6 ] = te[ 6 ];
  4959. array[ offset + 7 ] = te[ 7 ];
  4960. array[ offset + 8 ] = te[ 8 ];
  4961. return array;
  4962. }
  4963. /**
  4964. * Returns a matrix with copied values from this instance.
  4965. *
  4966. * @return {Matrix3} A clone of this instance.
  4967. */
  4968. clone() {
  4969. return new this.constructor().fromArray( this.elements );
  4970. }
  4971. }
  4972. const _m3 = /*@__PURE__*/ new Matrix3();
  4973. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  4974. 0.4123908, 0.3575843, 0.1804808,
  4975. 0.2126390, 0.7151687, 0.0721923,
  4976. 0.0193308, 0.1191948, 0.9505322
  4977. );
  4978. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  4979. 3.2409699, -1.5373832, -0.4986108,
  4980. -0.9692436, 1.8759675, 0.0415551,
  4981. 0.0556301, -0.203977, 1.0569715
  4982. );
  4983. function createColorManagement() {
  4984. const ColorManagement = {
  4985. enabled: true,
  4986. workingColorSpace: LinearSRGBColorSpace,
  4987. /**
  4988. * Implementations of supported color spaces.
  4989. *
  4990. * Required:
  4991. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  4992. * - whitePoint: reference white [ x y ]
  4993. * - transfer: transfer function (pre-defined)
  4994. * - toXYZ: Matrix3 RGB to XYZ transform
  4995. * - fromXYZ: Matrix3 XYZ to RGB transform
  4996. * - luminanceCoefficients: RGB luminance coefficients
  4997. *
  4998. * Optional:
  4999. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5000. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5001. *
  5002. * Reference:
  5003. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5004. */
  5005. spaces: {},
  5006. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5007. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5008. return color;
  5009. }
  5010. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5011. color.r = SRGBToLinear( color.r );
  5012. color.g = SRGBToLinear( color.g );
  5013. color.b = SRGBToLinear( color.b );
  5014. }
  5015. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5016. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5017. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5018. }
  5019. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5020. color.r = LinearToSRGB( color.r );
  5021. color.g = LinearToSRGB( color.g );
  5022. color.b = LinearToSRGB( color.b );
  5023. }
  5024. return color;
  5025. },
  5026. workingToColorSpace: function ( color, targetColorSpace ) {
  5027. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5028. },
  5029. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5030. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5031. },
  5032. getPrimaries: function ( colorSpace ) {
  5033. return this.spaces[ colorSpace ].primaries;
  5034. },
  5035. getTransfer: function ( colorSpace ) {
  5036. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5037. return this.spaces[ colorSpace ].transfer;
  5038. },
  5039. getToneMappingMode: function ( colorSpace ) {
  5040. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5041. },
  5042. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5043. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5044. },
  5045. define: function ( colorSpaces ) {
  5046. Object.assign( this.spaces, colorSpaces );
  5047. },
  5048. // Internal APIs
  5049. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5050. return targetMatrix
  5051. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5052. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5053. },
  5054. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5055. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5056. },
  5057. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5058. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5059. },
  5060. // Deprecated
  5061. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5062. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5063. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5064. },
  5065. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5066. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5067. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5068. },
  5069. };
  5070. /******************************************************************************
  5071. * sRGB definitions
  5072. */
  5073. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5074. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5075. const D65 = [ 0.3127, 0.3290 ];
  5076. ColorManagement.define( {
  5077. [ LinearSRGBColorSpace ]: {
  5078. primaries: REC709_PRIMARIES,
  5079. whitePoint: D65,
  5080. transfer: LinearTransfer,
  5081. toXYZ: LINEAR_REC709_TO_XYZ,
  5082. fromXYZ: XYZ_TO_LINEAR_REC709,
  5083. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5084. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5085. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5086. },
  5087. [ SRGBColorSpace ]: {
  5088. primaries: REC709_PRIMARIES,
  5089. whitePoint: D65,
  5090. transfer: SRGBTransfer,
  5091. toXYZ: LINEAR_REC709_TO_XYZ,
  5092. fromXYZ: XYZ_TO_LINEAR_REC709,
  5093. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5094. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5095. },
  5096. } );
  5097. return ColorManagement;
  5098. }
  5099. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5100. function SRGBToLinear( c ) {
  5101. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5102. }
  5103. function LinearToSRGB( c ) {
  5104. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5105. }
  5106. let _canvas;
  5107. /**
  5108. * A class containing utility functions for images.
  5109. *
  5110. * @hideconstructor
  5111. */
  5112. class ImageUtils {
  5113. /**
  5114. * Returns a data URI containing a representation of the given image.
  5115. *
  5116. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5117. * @param {string} [type='image/png'] - Indicates the image format.
  5118. * @return {string} The data URI.
  5119. */
  5120. static getDataURL( image, type = 'image/png' ) {
  5121. if ( /^data:/i.test( image.src ) ) {
  5122. return image.src;
  5123. }
  5124. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5125. return image.src;
  5126. }
  5127. let canvas;
  5128. if ( image instanceof HTMLCanvasElement ) {
  5129. canvas = image;
  5130. } else {
  5131. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5132. _canvas.width = image.width;
  5133. _canvas.height = image.height;
  5134. const context = _canvas.getContext( '2d' );
  5135. if ( image instanceof ImageData ) {
  5136. context.putImageData( image, 0, 0 );
  5137. } else {
  5138. context.drawImage( image, 0, 0, image.width, image.height );
  5139. }
  5140. canvas = _canvas;
  5141. }
  5142. return canvas.toDataURL( type );
  5143. }
  5144. /**
  5145. * Converts the given sRGB image data to linear color space.
  5146. *
  5147. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5148. * @return {HTMLCanvasElement|Object} The converted image.
  5149. */
  5150. static sRGBToLinear( image ) {
  5151. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5152. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5153. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5154. const canvas = createElementNS( 'canvas' );
  5155. canvas.width = image.width;
  5156. canvas.height = image.height;
  5157. const context = canvas.getContext( '2d' );
  5158. context.drawImage( image, 0, 0, image.width, image.height );
  5159. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5160. const data = imageData.data;
  5161. for ( let i = 0; i < data.length; i ++ ) {
  5162. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5163. }
  5164. context.putImageData( imageData, 0, 0 );
  5165. return canvas;
  5166. } else if ( image.data ) {
  5167. const data = image.data.slice( 0 );
  5168. for ( let i = 0; i < data.length; i ++ ) {
  5169. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5170. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5171. } else {
  5172. // assuming float
  5173. data[ i ] = SRGBToLinear( data[ i ] );
  5174. }
  5175. }
  5176. return {
  5177. data: data,
  5178. width: image.width,
  5179. height: image.height
  5180. };
  5181. } else {
  5182. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5183. return image;
  5184. }
  5185. }
  5186. }
  5187. let _sourceId = 0;
  5188. /**
  5189. * Represents the data source of a texture.
  5190. *
  5191. * The main purpose of this class is to decouple the data definition from the texture
  5192. * definition so the same data can be used with multiple texture instances.
  5193. */
  5194. class Source {
  5195. /**
  5196. * Constructs a new video texture.
  5197. *
  5198. * @param {any} [data=null] - The data definition of a texture.
  5199. */
  5200. constructor( data = null ) {
  5201. /**
  5202. * This flag can be used for type testing.
  5203. *
  5204. * @type {boolean}
  5205. * @readonly
  5206. * @default true
  5207. */
  5208. this.isSource = true;
  5209. /**
  5210. * The ID of the source.
  5211. *
  5212. * @name Source#id
  5213. * @type {number}
  5214. * @readonly
  5215. */
  5216. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5217. /**
  5218. * The UUID of the source.
  5219. *
  5220. * @type {string}
  5221. * @readonly
  5222. */
  5223. this.uuid = generateUUID();
  5224. /**
  5225. * The data definition of a texture.
  5226. *
  5227. * @type {any}
  5228. */
  5229. this.data = data;
  5230. /**
  5231. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5232. * provides more control on how texture data should be processed. When `dataReady` is set
  5233. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5234. * the data into the GPU memory.
  5235. *
  5236. * @type {boolean}
  5237. * @default true
  5238. */
  5239. this.dataReady = true;
  5240. /**
  5241. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5242. *
  5243. * @type {number}
  5244. * @readonly
  5245. * @default 0
  5246. */
  5247. this.version = 0;
  5248. }
  5249. /**
  5250. * Returns the dimensions of the source into the given target vector.
  5251. *
  5252. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5253. * @return {(Vector2|Vector3)} The dimensions of the source.
  5254. */
  5255. getSize( target ) {
  5256. const data = this.data;
  5257. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5258. target.set( data.videoWidth, data.videoHeight, 0 );
  5259. } else if ( data instanceof VideoFrame ) {
  5260. target.set( data.displayHeight, data.displayWidth, 0 );
  5261. } else if ( data !== null ) {
  5262. target.set( data.width, data.height, data.depth || 0 );
  5263. } else {
  5264. target.set( 0, 0, 0 );
  5265. }
  5266. return target;
  5267. }
  5268. /**
  5269. * When the property is set to `true`, the engine allocates the memory
  5270. * for the texture (if necessary) and triggers the actual texture upload
  5271. * to the GPU next time the source is used.
  5272. *
  5273. * @type {boolean}
  5274. * @default false
  5275. * @param {boolean} value
  5276. */
  5277. set needsUpdate( value ) {
  5278. if ( value === true ) this.version ++;
  5279. }
  5280. /**
  5281. * Serializes the source into JSON.
  5282. *
  5283. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5284. * @return {Object} A JSON object representing the serialized source.
  5285. * @see {@link ObjectLoader#parse}
  5286. */
  5287. toJSON( meta ) {
  5288. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5289. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5290. return meta.images[ this.uuid ];
  5291. }
  5292. const output = {
  5293. uuid: this.uuid,
  5294. url: ''
  5295. };
  5296. const data = this.data;
  5297. if ( data !== null ) {
  5298. let url;
  5299. if ( Array.isArray( data ) ) {
  5300. // cube texture
  5301. url = [];
  5302. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5303. if ( data[ i ].isDataTexture ) {
  5304. url.push( serializeImage( data[ i ].image ) );
  5305. } else {
  5306. url.push( serializeImage( data[ i ] ) );
  5307. }
  5308. }
  5309. } else {
  5310. // texture
  5311. url = serializeImage( data );
  5312. }
  5313. output.url = url;
  5314. }
  5315. if ( ! isRootObject ) {
  5316. meta.images[ this.uuid ] = output;
  5317. }
  5318. return output;
  5319. }
  5320. }
  5321. function serializeImage( image ) {
  5322. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5323. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5324. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5325. // default images
  5326. return ImageUtils.getDataURL( image );
  5327. } else {
  5328. if ( image.data ) {
  5329. // images of DataTexture
  5330. return {
  5331. data: Array.from( image.data ),
  5332. width: image.width,
  5333. height: image.height,
  5334. type: image.data.constructor.name
  5335. };
  5336. } else {
  5337. warn( 'Texture: Unable to serialize Texture.' );
  5338. return {};
  5339. }
  5340. }
  5341. }
  5342. let _textureId = 0;
  5343. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5344. /**
  5345. * Base class for all textures.
  5346. *
  5347. * Note: After the initial use of a texture, its dimensions, format, and type
  5348. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5349. *
  5350. * @augments EventDispatcher
  5351. */
  5352. class Texture extends EventDispatcher {
  5353. /**
  5354. * Constructs a new texture.
  5355. *
  5356. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5357. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5358. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5359. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5360. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5361. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5362. * @param {number} [format=RGBAFormat] - The texture format.
  5363. * @param {number} [type=UnsignedByteType] - The texture type.
  5364. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5365. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5366. */
  5367. 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 ) {
  5368. super();
  5369. /**
  5370. * This flag can be used for type testing.
  5371. *
  5372. * @type {boolean}
  5373. * @readonly
  5374. * @default true
  5375. */
  5376. this.isTexture = true;
  5377. /**
  5378. * The ID of the texture.
  5379. *
  5380. * @name Texture#id
  5381. * @type {number}
  5382. * @readonly
  5383. */
  5384. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5385. /**
  5386. * The UUID of the material.
  5387. *
  5388. * @type {string}
  5389. * @readonly
  5390. */
  5391. this.uuid = generateUUID();
  5392. /**
  5393. * The name of the material.
  5394. *
  5395. * @type {string}
  5396. */
  5397. this.name = '';
  5398. /**
  5399. * The data definition of a texture. A reference to the data source can be
  5400. * shared across textures. This is often useful in context of spritesheets
  5401. * where multiple textures render the same data but with different texture
  5402. * transformations.
  5403. *
  5404. * @type {Source}
  5405. */
  5406. this.source = new Source( image );
  5407. /**
  5408. * An array holding user-defined mipmaps.
  5409. *
  5410. * @type {Array<Object>}
  5411. */
  5412. this.mipmaps = [];
  5413. /**
  5414. * How the texture is applied to the object. The value `UVMapping`
  5415. * is the default, where texture or uv coordinates are used to apply the map.
  5416. *
  5417. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5418. * @default UVMapping
  5419. */
  5420. this.mapping = mapping;
  5421. /**
  5422. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5423. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5424. *
  5425. * @type {number}
  5426. * @default 0
  5427. */
  5428. this.channel = 0;
  5429. /**
  5430. * This defines how the texture is wrapped horizontally and corresponds to
  5431. * *U* in UV mapping.
  5432. *
  5433. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5434. * @default ClampToEdgeWrapping
  5435. */
  5436. this.wrapS = wrapS;
  5437. /**
  5438. * This defines how the texture is wrapped horizontally and corresponds to
  5439. * *V* in UV mapping.
  5440. *
  5441. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5442. * @default ClampToEdgeWrapping
  5443. */
  5444. this.wrapT = wrapT;
  5445. /**
  5446. * How the texture is sampled when a texel covers more than one pixel.
  5447. *
  5448. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5449. * @default LinearFilter
  5450. */
  5451. this.magFilter = magFilter;
  5452. /**
  5453. * How the texture is sampled when a texel covers less than one pixel.
  5454. *
  5455. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5456. * @default LinearMipmapLinearFilter
  5457. */
  5458. this.minFilter = minFilter;
  5459. /**
  5460. * The number of samples taken along the axis through the pixel that has the
  5461. * highest density of texels. By default, this value is `1`. A higher value
  5462. * gives a less blurry result than a basic mipmap, at the cost of more
  5463. * texture samples being used.
  5464. *
  5465. * @type {number}
  5466. * @default 0
  5467. */
  5468. this.anisotropy = anisotropy;
  5469. /**
  5470. * The format of the texture.
  5471. *
  5472. * @type {number}
  5473. * @default RGBAFormat
  5474. */
  5475. this.format = format;
  5476. /**
  5477. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5478. * defines how the texture data is going to be stored on the GPU.
  5479. *
  5480. * This property allows to overwrite the default format.
  5481. *
  5482. * @type {?string}
  5483. * @default null
  5484. */
  5485. this.internalFormat = null;
  5486. /**
  5487. * The data type of the texture.
  5488. *
  5489. * @type {number}
  5490. * @default UnsignedByteType
  5491. */
  5492. this.type = type;
  5493. /**
  5494. * How much a single repetition of the texture is offset from the beginning,
  5495. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5496. *
  5497. * @type {Vector2}
  5498. * @default (0,0)
  5499. */
  5500. this.offset = new Vector2( 0, 0 );
  5501. /**
  5502. * How many times the texture is repeated across the surface, in each
  5503. * direction U and V. If repeat is set greater than `1` in either direction,
  5504. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5505. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5506. *
  5507. * @type {Vector2}
  5508. * @default (1,1)
  5509. */
  5510. this.repeat = new Vector2( 1, 1 );
  5511. /**
  5512. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5513. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5514. *
  5515. * @type {Vector2}
  5516. * @default (0,0)
  5517. */
  5518. this.center = new Vector2( 0, 0 );
  5519. /**
  5520. * How much the texture is rotated around the center point, in radians.
  5521. * Positive values are counter-clockwise.
  5522. *
  5523. * @type {number}
  5524. * @default 0
  5525. */
  5526. this.rotation = 0;
  5527. /**
  5528. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5529. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5530. * {@link Texture#rotation}, and {@link Texture#center}.
  5531. *
  5532. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5533. *
  5534. * @type {boolean}
  5535. * @default true
  5536. */
  5537. this.matrixAutoUpdate = true;
  5538. /**
  5539. * The uv-transformation matrix of the texture.
  5540. *
  5541. * @type {Matrix3}
  5542. */
  5543. this.matrix = new Matrix3();
  5544. /**
  5545. * Whether to generate mipmaps (if possible) for a texture.
  5546. *
  5547. * Set this to `false` if you are creating mipmaps manually.
  5548. *
  5549. * @type {boolean}
  5550. * @default true
  5551. */
  5552. this.generateMipmaps = true;
  5553. /**
  5554. * If set to `true`, the alpha channel, if present, is multiplied into the
  5555. * color channels when the texture is uploaded to the GPU.
  5556. *
  5557. * Note that this property has no effect when using `ImageBitmap`. You need to
  5558. * configure premultiply alpha on bitmap creation instead.
  5559. *
  5560. * @type {boolean}
  5561. * @default false
  5562. */
  5563. this.premultiplyAlpha = false;
  5564. /**
  5565. * If set to `true`, the texture is flipped along the vertical axis when
  5566. * uploaded to the GPU.
  5567. *
  5568. * Note that this property has no effect when using `ImageBitmap`. You need to
  5569. * configure the flip on bitmap creation instead.
  5570. *
  5571. * @type {boolean}
  5572. * @default true
  5573. */
  5574. this.flipY = true;
  5575. /**
  5576. * Specifies the alignment requirements for the start of each pixel row in memory.
  5577. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5578. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5579. *
  5580. * @type {number}
  5581. * @default 4
  5582. */
  5583. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5584. /**
  5585. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5586. *
  5587. * @type {string}
  5588. * @default NoColorSpace
  5589. */
  5590. this.colorSpace = colorSpace;
  5591. /**
  5592. * An object that can be used to store custom data about the texture. It
  5593. * should not hold references to functions as these will not be cloned.
  5594. *
  5595. * @type {Object}
  5596. */
  5597. this.userData = {};
  5598. /**
  5599. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5600. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5601. *
  5602. * @type {Array<Object>}
  5603. */
  5604. this.updateRanges = [];
  5605. /**
  5606. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5607. *
  5608. * @type {number}
  5609. * @readonly
  5610. * @default 0
  5611. */
  5612. this.version = 0;
  5613. /**
  5614. * A callback function, called when the texture is updated (e.g., when
  5615. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5616. *
  5617. * @type {?Function}
  5618. * @default null
  5619. */
  5620. this.onUpdate = null;
  5621. /**
  5622. * An optional back reference to the textures render target.
  5623. *
  5624. * @type {?(RenderTarget|WebGLRenderTarget)}
  5625. * @default null
  5626. */
  5627. this.renderTarget = null;
  5628. /**
  5629. * Indicates whether a texture belongs to a render target or not.
  5630. *
  5631. * @type {boolean}
  5632. * @readonly
  5633. * @default false
  5634. */
  5635. this.isRenderTargetTexture = false;
  5636. /**
  5637. * Indicates if a texture should be handled like a texture array.
  5638. *
  5639. * @type {boolean}
  5640. * @readonly
  5641. * @default false
  5642. */
  5643. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5644. /**
  5645. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5646. * (only relevant for render target textures).
  5647. *
  5648. * @type {number}
  5649. * @readonly
  5650. * @default 0
  5651. */
  5652. this.pmremVersion = 0;
  5653. }
  5654. /**
  5655. * The width of the texture in pixels.
  5656. */
  5657. get width() {
  5658. return this.source.getSize( _tempVec3 ).x;
  5659. }
  5660. /**
  5661. * The height of the texture in pixels.
  5662. */
  5663. get height() {
  5664. return this.source.getSize( _tempVec3 ).y;
  5665. }
  5666. /**
  5667. * The depth of the texture in pixels.
  5668. */
  5669. get depth() {
  5670. return this.source.getSize( _tempVec3 ).z;
  5671. }
  5672. /**
  5673. * The image object holding the texture data.
  5674. *
  5675. * @type {?Object}
  5676. */
  5677. get image() {
  5678. return this.source.data;
  5679. }
  5680. set image( value = null ) {
  5681. this.source.data = value;
  5682. }
  5683. /**
  5684. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5685. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5686. */
  5687. updateMatrix() {
  5688. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5689. }
  5690. /**
  5691. * Adds a range of data in the data texture to be updated on the GPU.
  5692. *
  5693. * @param {number} start - Position at which to start update.
  5694. * @param {number} count - The number of components to update.
  5695. */
  5696. addUpdateRange( start, count ) {
  5697. this.updateRanges.push( { start, count } );
  5698. }
  5699. /**
  5700. * Clears the update ranges.
  5701. */
  5702. clearUpdateRanges() {
  5703. this.updateRanges.length = 0;
  5704. }
  5705. /**
  5706. * Returns a new texture with copied values from this instance.
  5707. *
  5708. * @return {Texture} A clone of this instance.
  5709. */
  5710. clone() {
  5711. return new this.constructor().copy( this );
  5712. }
  5713. /**
  5714. * Copies the values of the given texture to this instance.
  5715. *
  5716. * @param {Texture} source - The texture to copy.
  5717. * @return {Texture} A reference to this instance.
  5718. */
  5719. copy( source ) {
  5720. this.name = source.name;
  5721. this.source = source.source;
  5722. this.mipmaps = source.mipmaps.slice( 0 );
  5723. this.mapping = source.mapping;
  5724. this.channel = source.channel;
  5725. this.wrapS = source.wrapS;
  5726. this.wrapT = source.wrapT;
  5727. this.magFilter = source.magFilter;
  5728. this.minFilter = source.minFilter;
  5729. this.anisotropy = source.anisotropy;
  5730. this.format = source.format;
  5731. this.internalFormat = source.internalFormat;
  5732. this.type = source.type;
  5733. this.offset.copy( source.offset );
  5734. this.repeat.copy( source.repeat );
  5735. this.center.copy( source.center );
  5736. this.rotation = source.rotation;
  5737. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5738. this.matrix.copy( source.matrix );
  5739. this.generateMipmaps = source.generateMipmaps;
  5740. this.premultiplyAlpha = source.premultiplyAlpha;
  5741. this.flipY = source.flipY;
  5742. this.unpackAlignment = source.unpackAlignment;
  5743. this.colorSpace = source.colorSpace;
  5744. this.renderTarget = source.renderTarget;
  5745. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5746. this.isArrayTexture = source.isArrayTexture;
  5747. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5748. this.needsUpdate = true;
  5749. return this;
  5750. }
  5751. /**
  5752. * Sets this texture's properties based on `values`.
  5753. * @param {Object} values - A container with texture parameters.
  5754. */
  5755. setValues( values ) {
  5756. for ( const key in values ) {
  5757. const newValue = values[ key ];
  5758. if ( newValue === undefined ) {
  5759. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5760. continue;
  5761. }
  5762. const currentValue = this[ key ];
  5763. if ( currentValue === undefined ) {
  5764. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5765. continue;
  5766. }
  5767. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5768. currentValue.copy( newValue );
  5769. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5770. currentValue.copy( newValue );
  5771. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5772. currentValue.copy( newValue );
  5773. } else {
  5774. this[ key ] = newValue;
  5775. }
  5776. }
  5777. }
  5778. /**
  5779. * Serializes the texture into JSON.
  5780. *
  5781. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5782. * @return {Object} A JSON object representing the serialized texture.
  5783. * @see {@link ObjectLoader#parse}
  5784. */
  5785. toJSON( meta ) {
  5786. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5787. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5788. return meta.textures[ this.uuid ];
  5789. }
  5790. const output = {
  5791. metadata: {
  5792. version: 4.7,
  5793. type: 'Texture',
  5794. generator: 'Texture.toJSON'
  5795. },
  5796. uuid: this.uuid,
  5797. name: this.name,
  5798. image: this.source.toJSON( meta ).uuid,
  5799. mapping: this.mapping,
  5800. channel: this.channel,
  5801. repeat: [ this.repeat.x, this.repeat.y ],
  5802. offset: [ this.offset.x, this.offset.y ],
  5803. center: [ this.center.x, this.center.y ],
  5804. rotation: this.rotation,
  5805. wrap: [ this.wrapS, this.wrapT ],
  5806. format: this.format,
  5807. internalFormat: this.internalFormat,
  5808. type: this.type,
  5809. colorSpace: this.colorSpace,
  5810. minFilter: this.minFilter,
  5811. magFilter: this.magFilter,
  5812. anisotropy: this.anisotropy,
  5813. flipY: this.flipY,
  5814. generateMipmaps: this.generateMipmaps,
  5815. premultiplyAlpha: this.premultiplyAlpha,
  5816. unpackAlignment: this.unpackAlignment
  5817. };
  5818. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5819. if ( ! isRootObject ) {
  5820. meta.textures[ this.uuid ] = output;
  5821. }
  5822. return output;
  5823. }
  5824. /**
  5825. * Frees the GPU-related resources allocated by this instance. Call this
  5826. * method whenever this instance is no longer used in your app.
  5827. *
  5828. * @fires Texture#dispose
  5829. */
  5830. dispose() {
  5831. /**
  5832. * Fires when the texture has been disposed of.
  5833. *
  5834. * @event Texture#dispose
  5835. * @type {Object}
  5836. */
  5837. this.dispatchEvent( { type: 'dispose' } );
  5838. }
  5839. /**
  5840. * Transforms the given uv vector with the textures uv transformation matrix.
  5841. *
  5842. * @param {Vector2} uv - The uv vector.
  5843. * @return {Vector2} The transformed uv vector.
  5844. */
  5845. transformUv( uv ) {
  5846. if ( this.mapping !== UVMapping ) return uv;
  5847. uv.applyMatrix3( this.matrix );
  5848. if ( uv.x < 0 || uv.x > 1 ) {
  5849. switch ( this.wrapS ) {
  5850. case RepeatWrapping:
  5851. uv.x = uv.x - Math.floor( uv.x );
  5852. break;
  5853. case ClampToEdgeWrapping:
  5854. uv.x = uv.x < 0 ? 0 : 1;
  5855. break;
  5856. case MirroredRepeatWrapping:
  5857. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5858. uv.x = Math.ceil( uv.x ) - uv.x;
  5859. } else {
  5860. uv.x = uv.x - Math.floor( uv.x );
  5861. }
  5862. break;
  5863. }
  5864. }
  5865. if ( uv.y < 0 || uv.y > 1 ) {
  5866. switch ( this.wrapT ) {
  5867. case RepeatWrapping:
  5868. uv.y = uv.y - Math.floor( uv.y );
  5869. break;
  5870. case ClampToEdgeWrapping:
  5871. uv.y = uv.y < 0 ? 0 : 1;
  5872. break;
  5873. case MirroredRepeatWrapping:
  5874. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5875. uv.y = Math.ceil( uv.y ) - uv.y;
  5876. } else {
  5877. uv.y = uv.y - Math.floor( uv.y );
  5878. }
  5879. break;
  5880. }
  5881. }
  5882. if ( this.flipY ) {
  5883. uv.y = 1 - uv.y;
  5884. }
  5885. return uv;
  5886. }
  5887. /**
  5888. * Setting this property to `true` indicates the engine the texture
  5889. * must be updated in the next render. This triggers a texture upload
  5890. * to the GPU and ensures correct texture parameter configuration.
  5891. *
  5892. * @type {boolean}
  5893. * @default false
  5894. * @param {boolean} value
  5895. */
  5896. set needsUpdate( value ) {
  5897. if ( value === true ) {
  5898. this.version ++;
  5899. this.source.needsUpdate = true;
  5900. }
  5901. }
  5902. /**
  5903. * Setting this property to `true` indicates the engine the PMREM
  5904. * must be regenerated.
  5905. *
  5906. * @type {boolean}
  5907. * @default false
  5908. * @param {boolean} value
  5909. */
  5910. set needsPMREMUpdate( value ) {
  5911. if ( value === true ) {
  5912. this.pmremVersion ++;
  5913. }
  5914. }
  5915. }
  5916. /**
  5917. * The default image for all textures.
  5918. *
  5919. * @static
  5920. * @type {?Image}
  5921. * @default null
  5922. */
  5923. Texture.DEFAULT_IMAGE = null;
  5924. /**
  5925. * The default mapping for all textures.
  5926. *
  5927. * @static
  5928. * @type {number}
  5929. * @default UVMapping
  5930. */
  5931. Texture.DEFAULT_MAPPING = UVMapping;
  5932. /**
  5933. * The default anisotropy value for all textures.
  5934. *
  5935. * @static
  5936. * @type {number}
  5937. * @default 1
  5938. */
  5939. Texture.DEFAULT_ANISOTROPY = 1;
  5940. /**
  5941. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5942. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5943. *
  5944. * - A point in 4D space.
  5945. * - A direction and length in 4D space. In three.js the length will
  5946. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5947. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5948. * - Any arbitrary ordered quadruplet of numbers.
  5949. *
  5950. * There are other things a 4D vector can be used to represent, however these
  5951. * are the most common uses in *three.js*.
  5952. *
  5953. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5954. * the corresponding order.
  5955. * ```js
  5956. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5957. *
  5958. * //no arguments; will be initialised to (0, 0, 0, 1)
  5959. * const b = new THREE.Vector4( );
  5960. *
  5961. * const d = a.dot( b );
  5962. * ```
  5963. */
  5964. class Vector4 {
  5965. /**
  5966. * Constructs a new 4D vector.
  5967. *
  5968. * @param {number} [x=0] - The x value of this vector.
  5969. * @param {number} [y=0] - The y value of this vector.
  5970. * @param {number} [z=0] - The z value of this vector.
  5971. * @param {number} [w=1] - The w value of this vector.
  5972. */
  5973. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  5974. /**
  5975. * This flag can be used for type testing.
  5976. *
  5977. * @type {boolean}
  5978. * @readonly
  5979. * @default true
  5980. */
  5981. Vector4.prototype.isVector4 = true;
  5982. /**
  5983. * The x value of this vector.
  5984. *
  5985. * @type {number}
  5986. */
  5987. this.x = x;
  5988. /**
  5989. * The y value of this vector.
  5990. *
  5991. * @type {number}
  5992. */
  5993. this.y = y;
  5994. /**
  5995. * The z value of this vector.
  5996. *
  5997. * @type {number}
  5998. */
  5999. this.z = z;
  6000. /**
  6001. * The w value of this vector.
  6002. *
  6003. * @type {number}
  6004. */
  6005. this.w = w;
  6006. }
  6007. /**
  6008. * Alias for {@link Vector4#z}.
  6009. *
  6010. * @type {number}
  6011. */
  6012. get width() {
  6013. return this.z;
  6014. }
  6015. set width( value ) {
  6016. this.z = value;
  6017. }
  6018. /**
  6019. * Alias for {@link Vector4#w}.
  6020. *
  6021. * @type {number}
  6022. */
  6023. get height() {
  6024. return this.w;
  6025. }
  6026. set height( value ) {
  6027. this.w = value;
  6028. }
  6029. /**
  6030. * Sets the vector components.
  6031. *
  6032. * @param {number} x - The value of the x component.
  6033. * @param {number} y - The value of the y component.
  6034. * @param {number} z - The value of the z component.
  6035. * @param {number} w - The value of the w component.
  6036. * @return {Vector4} A reference to this vector.
  6037. */
  6038. set( x, y, z, w ) {
  6039. this.x = x;
  6040. this.y = y;
  6041. this.z = z;
  6042. this.w = w;
  6043. return this;
  6044. }
  6045. /**
  6046. * Sets the vector components to the same value.
  6047. *
  6048. * @param {number} scalar - The value to set for all vector components.
  6049. * @return {Vector4} A reference to this vector.
  6050. */
  6051. setScalar( scalar ) {
  6052. this.x = scalar;
  6053. this.y = scalar;
  6054. this.z = scalar;
  6055. this.w = scalar;
  6056. return this;
  6057. }
  6058. /**
  6059. * Sets the vector's x component to the given value
  6060. *
  6061. * @param {number} x - The value to set.
  6062. * @return {Vector4} A reference to this vector.
  6063. */
  6064. setX( x ) {
  6065. this.x = x;
  6066. return this;
  6067. }
  6068. /**
  6069. * Sets the vector's y component to the given value
  6070. *
  6071. * @param {number} y - The value to set.
  6072. * @return {Vector4} A reference to this vector.
  6073. */
  6074. setY( y ) {
  6075. this.y = y;
  6076. return this;
  6077. }
  6078. /**
  6079. * Sets the vector's z component to the given value
  6080. *
  6081. * @param {number} z - The value to set.
  6082. * @return {Vector4} A reference to this vector.
  6083. */
  6084. setZ( z ) {
  6085. this.z = z;
  6086. return this;
  6087. }
  6088. /**
  6089. * Sets the vector's w component to the given value
  6090. *
  6091. * @param {number} w - The value to set.
  6092. * @return {Vector4} A reference to this vector.
  6093. */
  6094. setW( w ) {
  6095. this.w = w;
  6096. return this;
  6097. }
  6098. /**
  6099. * Allows to set a vector component with an index.
  6100. *
  6101. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6102. * `2` equals to z, `3` equals to w.
  6103. * @param {number} value - The value to set.
  6104. * @return {Vector4} A reference to this vector.
  6105. */
  6106. setComponent( index, value ) {
  6107. switch ( index ) {
  6108. case 0: this.x = value; break;
  6109. case 1: this.y = value; break;
  6110. case 2: this.z = value; break;
  6111. case 3: this.w = value; break;
  6112. default: throw new Error( 'index is out of range: ' + index );
  6113. }
  6114. return this;
  6115. }
  6116. /**
  6117. * Returns the value of the vector component which matches the given index.
  6118. *
  6119. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6120. * `2` equals to z, `3` equals to w.
  6121. * @return {number} A vector component value.
  6122. */
  6123. getComponent( index ) {
  6124. switch ( index ) {
  6125. case 0: return this.x;
  6126. case 1: return this.y;
  6127. case 2: return this.z;
  6128. case 3: return this.w;
  6129. default: throw new Error( 'index is out of range: ' + index );
  6130. }
  6131. }
  6132. /**
  6133. * Returns a new vector with copied values from this instance.
  6134. *
  6135. * @return {Vector4} A clone of this instance.
  6136. */
  6137. clone() {
  6138. return new this.constructor( this.x, this.y, this.z, this.w );
  6139. }
  6140. /**
  6141. * Copies the values of the given vector to this instance.
  6142. *
  6143. * @param {Vector3|Vector4} v - The vector to copy.
  6144. * @return {Vector4} A reference to this vector.
  6145. */
  6146. copy( v ) {
  6147. this.x = v.x;
  6148. this.y = v.y;
  6149. this.z = v.z;
  6150. this.w = ( v.w !== undefined ) ? v.w : 1;
  6151. return this;
  6152. }
  6153. /**
  6154. * Adds the given vector to this instance.
  6155. *
  6156. * @param {Vector4} v - The vector to add.
  6157. * @return {Vector4} A reference to this vector.
  6158. */
  6159. add( v ) {
  6160. this.x += v.x;
  6161. this.y += v.y;
  6162. this.z += v.z;
  6163. this.w += v.w;
  6164. return this;
  6165. }
  6166. /**
  6167. * Adds the given scalar value to all components of this instance.
  6168. *
  6169. * @param {number} s - The scalar to add.
  6170. * @return {Vector4} A reference to this vector.
  6171. */
  6172. addScalar( s ) {
  6173. this.x += s;
  6174. this.y += s;
  6175. this.z += s;
  6176. this.w += s;
  6177. return this;
  6178. }
  6179. /**
  6180. * Adds the given vectors and stores the result in this instance.
  6181. *
  6182. * @param {Vector4} a - The first vector.
  6183. * @param {Vector4} b - The second vector.
  6184. * @return {Vector4} A reference to this vector.
  6185. */
  6186. addVectors( a, b ) {
  6187. this.x = a.x + b.x;
  6188. this.y = a.y + b.y;
  6189. this.z = a.z + b.z;
  6190. this.w = a.w + b.w;
  6191. return this;
  6192. }
  6193. /**
  6194. * Adds the given vector scaled by the given factor to this instance.
  6195. *
  6196. * @param {Vector4} v - The vector.
  6197. * @param {number} s - The factor that scales `v`.
  6198. * @return {Vector4} A reference to this vector.
  6199. */
  6200. addScaledVector( v, s ) {
  6201. this.x += v.x * s;
  6202. this.y += v.y * s;
  6203. this.z += v.z * s;
  6204. this.w += v.w * s;
  6205. return this;
  6206. }
  6207. /**
  6208. * Subtracts the given vector from this instance.
  6209. *
  6210. * @param {Vector4} v - The vector to subtract.
  6211. * @return {Vector4} A reference to this vector.
  6212. */
  6213. sub( v ) {
  6214. this.x -= v.x;
  6215. this.y -= v.y;
  6216. this.z -= v.z;
  6217. this.w -= v.w;
  6218. return this;
  6219. }
  6220. /**
  6221. * Subtracts the given scalar value from all components of this instance.
  6222. *
  6223. * @param {number} s - The scalar to subtract.
  6224. * @return {Vector4} A reference to this vector.
  6225. */
  6226. subScalar( s ) {
  6227. this.x -= s;
  6228. this.y -= s;
  6229. this.z -= s;
  6230. this.w -= s;
  6231. return this;
  6232. }
  6233. /**
  6234. * Subtracts the given vectors and stores the result in this instance.
  6235. *
  6236. * @param {Vector4} a - The first vector.
  6237. * @param {Vector4} b - The second vector.
  6238. * @return {Vector4} A reference to this vector.
  6239. */
  6240. subVectors( a, b ) {
  6241. this.x = a.x - b.x;
  6242. this.y = a.y - b.y;
  6243. this.z = a.z - b.z;
  6244. this.w = a.w - b.w;
  6245. return this;
  6246. }
  6247. /**
  6248. * Multiplies the given vector with this instance.
  6249. *
  6250. * @param {Vector4} v - The vector to multiply.
  6251. * @return {Vector4} A reference to this vector.
  6252. */
  6253. multiply( v ) {
  6254. this.x *= v.x;
  6255. this.y *= v.y;
  6256. this.z *= v.z;
  6257. this.w *= v.w;
  6258. return this;
  6259. }
  6260. /**
  6261. * Multiplies the given scalar value with all components of this instance.
  6262. *
  6263. * @param {number} scalar - The scalar to multiply.
  6264. * @return {Vector4} A reference to this vector.
  6265. */
  6266. multiplyScalar( scalar ) {
  6267. this.x *= scalar;
  6268. this.y *= scalar;
  6269. this.z *= scalar;
  6270. this.w *= scalar;
  6271. return this;
  6272. }
  6273. /**
  6274. * Multiplies this vector with the given 4x4 matrix.
  6275. *
  6276. * @param {Matrix4} m - The 4x4 matrix.
  6277. * @return {Vector4} A reference to this vector.
  6278. */
  6279. applyMatrix4( m ) {
  6280. const x = this.x, y = this.y, z = this.z, w = this.w;
  6281. const e = m.elements;
  6282. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6283. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6284. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6285. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6286. return this;
  6287. }
  6288. /**
  6289. * Divides this instance by the given vector.
  6290. *
  6291. * @param {Vector4} v - The vector to divide.
  6292. * @return {Vector4} A reference to this vector.
  6293. */
  6294. divide( v ) {
  6295. this.x /= v.x;
  6296. this.y /= v.y;
  6297. this.z /= v.z;
  6298. this.w /= v.w;
  6299. return this;
  6300. }
  6301. /**
  6302. * Divides this vector by the given scalar.
  6303. *
  6304. * @param {number} scalar - The scalar to divide.
  6305. * @return {Vector4} A reference to this vector.
  6306. */
  6307. divideScalar( scalar ) {
  6308. return this.multiplyScalar( 1 / scalar );
  6309. }
  6310. /**
  6311. * Sets the x, y and z components of this
  6312. * vector to the quaternion's axis and w to the angle.
  6313. *
  6314. * @param {Quaternion} q - The Quaternion to set.
  6315. * @return {Vector4} A reference to this vector.
  6316. */
  6317. setAxisAngleFromQuaternion( q ) {
  6318. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6319. // q is assumed to be normalized
  6320. this.w = 2 * Math.acos( q.w );
  6321. const s = Math.sqrt( 1 - q.w * q.w );
  6322. if ( s < 0.0001 ) {
  6323. this.x = 1;
  6324. this.y = 0;
  6325. this.z = 0;
  6326. } else {
  6327. this.x = q.x / s;
  6328. this.y = q.y / s;
  6329. this.z = q.z / s;
  6330. }
  6331. return this;
  6332. }
  6333. /**
  6334. * Sets the x, y and z components of this
  6335. * vector to the axis of rotation and w to the angle.
  6336. *
  6337. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6338. * @return {Vector4} A reference to this vector.
  6339. */
  6340. setAxisAngleFromRotationMatrix( m ) {
  6341. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6342. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6343. let angle, x, y, z; // variables for result
  6344. const epsilon = 0.01, // margin to allow for rounding errors
  6345. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6346. te = m.elements,
  6347. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6348. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6349. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6350. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6351. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6352. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6353. // singularity found
  6354. // first check for identity matrix which must have +1 for all terms
  6355. // in leading diagonal and zero in other terms
  6356. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6357. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6358. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6359. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6360. // this singularity is identity matrix so angle = 0
  6361. this.set( 1, 0, 0, 0 );
  6362. return this; // zero angle, arbitrary axis
  6363. }
  6364. // otherwise this singularity is angle = 180
  6365. angle = Math.PI;
  6366. const xx = ( m11 + 1 ) / 2;
  6367. const yy = ( m22 + 1 ) / 2;
  6368. const zz = ( m33 + 1 ) / 2;
  6369. const xy = ( m12 + m21 ) / 4;
  6370. const xz = ( m13 + m31 ) / 4;
  6371. const yz = ( m23 + m32 ) / 4;
  6372. if ( ( xx > yy ) && ( xx > zz ) ) {
  6373. // m11 is the largest diagonal term
  6374. if ( xx < epsilon ) {
  6375. x = 0;
  6376. y = 0.707106781;
  6377. z = 0.707106781;
  6378. } else {
  6379. x = Math.sqrt( xx );
  6380. y = xy / x;
  6381. z = xz / x;
  6382. }
  6383. } else if ( yy > zz ) {
  6384. // m22 is the largest diagonal term
  6385. if ( yy < epsilon ) {
  6386. x = 0.707106781;
  6387. y = 0;
  6388. z = 0.707106781;
  6389. } else {
  6390. y = Math.sqrt( yy );
  6391. x = xy / y;
  6392. z = yz / y;
  6393. }
  6394. } else {
  6395. // m33 is the largest diagonal term so base result on this
  6396. if ( zz < epsilon ) {
  6397. x = 0.707106781;
  6398. y = 0.707106781;
  6399. z = 0;
  6400. } else {
  6401. z = Math.sqrt( zz );
  6402. x = xz / z;
  6403. y = yz / z;
  6404. }
  6405. }
  6406. this.set( x, y, z, angle );
  6407. return this; // return 180 deg rotation
  6408. }
  6409. // as we have reached here there are no singularities so we can handle normally
  6410. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6411. ( m13 - m31 ) * ( m13 - m31 ) +
  6412. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6413. if ( Math.abs( s ) < 0.001 ) s = 1;
  6414. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6415. // caught by singularity test above, but I've left it in just in case
  6416. this.x = ( m32 - m23 ) / s;
  6417. this.y = ( m13 - m31 ) / s;
  6418. this.z = ( m21 - m12 ) / s;
  6419. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6420. return this;
  6421. }
  6422. /**
  6423. * Sets the vector components to the position elements of the
  6424. * given transformation matrix.
  6425. *
  6426. * @param {Matrix4} m - The 4x4 matrix.
  6427. * @return {Vector4} A reference to this vector.
  6428. */
  6429. setFromMatrixPosition( m ) {
  6430. const e = m.elements;
  6431. this.x = e[ 12 ];
  6432. this.y = e[ 13 ];
  6433. this.z = e[ 14 ];
  6434. this.w = e[ 15 ];
  6435. return this;
  6436. }
  6437. /**
  6438. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6439. * value, replace that value with the corresponding min value.
  6440. *
  6441. * @param {Vector4} v - The vector.
  6442. * @return {Vector4} A reference to this vector.
  6443. */
  6444. min( v ) {
  6445. this.x = Math.min( this.x, v.x );
  6446. this.y = Math.min( this.y, v.y );
  6447. this.z = Math.min( this.z, v.z );
  6448. this.w = Math.min( this.w, v.w );
  6449. return this;
  6450. }
  6451. /**
  6452. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6453. * value, replace that value with the corresponding max value.
  6454. *
  6455. * @param {Vector4} v - The vector.
  6456. * @return {Vector4} A reference to this vector.
  6457. */
  6458. max( v ) {
  6459. this.x = Math.max( this.x, v.x );
  6460. this.y = Math.max( this.y, v.y );
  6461. this.z = Math.max( this.z, v.z );
  6462. this.w = Math.max( this.w, v.w );
  6463. return this;
  6464. }
  6465. /**
  6466. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6467. * value, it is replaced by the corresponding value.
  6468. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6469. * it is replaced by the corresponding value.
  6470. *
  6471. * @param {Vector4} min - The minimum x, y and z values.
  6472. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6473. * @return {Vector4} A reference to this vector.
  6474. */
  6475. clamp( min, max ) {
  6476. // assumes min < max, componentwise
  6477. this.x = clamp( this.x, min.x, max.x );
  6478. this.y = clamp( this.y, min.y, max.y );
  6479. this.z = clamp( this.z, min.z, max.z );
  6480. this.w = clamp( this.w, min.w, max.w );
  6481. return this;
  6482. }
  6483. /**
  6484. * If this vector's x, y, z or w values are greater than the max value, they are
  6485. * replaced by the max value.
  6486. * If this vector's x, y, z or w values are less than the min value, they are
  6487. * replaced by the min value.
  6488. *
  6489. * @param {number} minVal - The minimum value the components will be clamped to.
  6490. * @param {number} maxVal - The maximum value the components will be clamped to.
  6491. * @return {Vector4} A reference to this vector.
  6492. */
  6493. clampScalar( minVal, maxVal ) {
  6494. this.x = clamp( this.x, minVal, maxVal );
  6495. this.y = clamp( this.y, minVal, maxVal );
  6496. this.z = clamp( this.z, minVal, maxVal );
  6497. this.w = clamp( this.w, minVal, maxVal );
  6498. return this;
  6499. }
  6500. /**
  6501. * If this vector's length is greater than the max value, it is replaced by
  6502. * the max value.
  6503. * If this vector's length is less than the min value, it is replaced by the
  6504. * min value.
  6505. *
  6506. * @param {number} min - The minimum value the vector length will be clamped to.
  6507. * @param {number} max - The maximum value the vector length will be clamped to.
  6508. * @return {Vector4} A reference to this vector.
  6509. */
  6510. clampLength( min, max ) {
  6511. const length = this.length();
  6512. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6513. }
  6514. /**
  6515. * The components of this vector are rounded down to the nearest integer value.
  6516. *
  6517. * @return {Vector4} A reference to this vector.
  6518. */
  6519. floor() {
  6520. this.x = Math.floor( this.x );
  6521. this.y = Math.floor( this.y );
  6522. this.z = Math.floor( this.z );
  6523. this.w = Math.floor( this.w );
  6524. return this;
  6525. }
  6526. /**
  6527. * The components of this vector are rounded up to the nearest integer value.
  6528. *
  6529. * @return {Vector4} A reference to this vector.
  6530. */
  6531. ceil() {
  6532. this.x = Math.ceil( this.x );
  6533. this.y = Math.ceil( this.y );
  6534. this.z = Math.ceil( this.z );
  6535. this.w = Math.ceil( this.w );
  6536. return this;
  6537. }
  6538. /**
  6539. * The components of this vector are rounded to the nearest integer value
  6540. *
  6541. * @return {Vector4} A reference to this vector.
  6542. */
  6543. round() {
  6544. this.x = Math.round( this.x );
  6545. this.y = Math.round( this.y );
  6546. this.z = Math.round( this.z );
  6547. this.w = Math.round( this.w );
  6548. return this;
  6549. }
  6550. /**
  6551. * The components of this vector are rounded towards zero (up if negative,
  6552. * down if positive) to an integer value.
  6553. *
  6554. * @return {Vector4} A reference to this vector.
  6555. */
  6556. roundToZero() {
  6557. this.x = Math.trunc( this.x );
  6558. this.y = Math.trunc( this.y );
  6559. this.z = Math.trunc( this.z );
  6560. this.w = Math.trunc( this.w );
  6561. return this;
  6562. }
  6563. /**
  6564. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6565. *
  6566. * @return {Vector4} A reference to this vector.
  6567. */
  6568. negate() {
  6569. this.x = - this.x;
  6570. this.y = - this.y;
  6571. this.z = - this.z;
  6572. this.w = - this.w;
  6573. return this;
  6574. }
  6575. /**
  6576. * Calculates the dot product of the given vector with this instance.
  6577. *
  6578. * @param {Vector4} v - The vector to compute the dot product with.
  6579. * @return {number} The result of the dot product.
  6580. */
  6581. dot( v ) {
  6582. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6583. }
  6584. /**
  6585. * Computes the square of the Euclidean length (straight-line length) from
  6586. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6587. * compare the length squared instead as it is slightly more efficient to calculate.
  6588. *
  6589. * @return {number} The square length of this vector.
  6590. */
  6591. lengthSq() {
  6592. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6593. }
  6594. /**
  6595. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6596. *
  6597. * @return {number} The length of this vector.
  6598. */
  6599. length() {
  6600. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6601. }
  6602. /**
  6603. * Computes the Manhattan length of this vector.
  6604. *
  6605. * @return {number} The length of this vector.
  6606. */
  6607. manhattanLength() {
  6608. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6609. }
  6610. /**
  6611. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6612. * with the same direction as this one, but with a vector length of `1`.
  6613. *
  6614. * @return {Vector4} A reference to this vector.
  6615. */
  6616. normalize() {
  6617. return this.divideScalar( this.length() || 1 );
  6618. }
  6619. /**
  6620. * Sets this vector to a vector with the same direction as this one, but
  6621. * with the specified length.
  6622. *
  6623. * @param {number} length - The new length of this vector.
  6624. * @return {Vector4} A reference to this vector.
  6625. */
  6626. setLength( length ) {
  6627. return this.normalize().multiplyScalar( length );
  6628. }
  6629. /**
  6630. * Linearly interpolates between the given vector and this instance, where
  6631. * alpha is the percent distance along the line - alpha = 0 will be this
  6632. * vector, and alpha = 1 will be the given one.
  6633. *
  6634. * @param {Vector4} v - The vector to interpolate towards.
  6635. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6636. * @return {Vector4} A reference to this vector.
  6637. */
  6638. lerp( v, alpha ) {
  6639. this.x += ( v.x - this.x ) * alpha;
  6640. this.y += ( v.y - this.y ) * alpha;
  6641. this.z += ( v.z - this.z ) * alpha;
  6642. this.w += ( v.w - this.w ) * alpha;
  6643. return this;
  6644. }
  6645. /**
  6646. * Linearly interpolates between the given vectors, where alpha is the percent
  6647. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6648. * be the second one. The result is stored in this instance.
  6649. *
  6650. * @param {Vector4} v1 - The first vector.
  6651. * @param {Vector4} v2 - The second vector.
  6652. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6653. * @return {Vector4} A reference to this vector.
  6654. */
  6655. lerpVectors( v1, v2, alpha ) {
  6656. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6657. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6658. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6659. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6660. return this;
  6661. }
  6662. /**
  6663. * Returns `true` if this vector is equal with the given one.
  6664. *
  6665. * @param {Vector4} v - The vector to test for equality.
  6666. * @return {boolean} Whether this vector is equal with the given one.
  6667. */
  6668. equals( v ) {
  6669. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6670. }
  6671. /**
  6672. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6673. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6674. *
  6675. * @param {Array<number>} array - An array holding the vector component values.
  6676. * @param {number} [offset=0] - The offset into the array.
  6677. * @return {Vector4} A reference to this vector.
  6678. */
  6679. fromArray( array, offset = 0 ) {
  6680. this.x = array[ offset ];
  6681. this.y = array[ offset + 1 ];
  6682. this.z = array[ offset + 2 ];
  6683. this.w = array[ offset + 3 ];
  6684. return this;
  6685. }
  6686. /**
  6687. * Writes the components of this vector to the given array. If no array is provided,
  6688. * the method returns a new instance.
  6689. *
  6690. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6691. * @param {number} [offset=0] - Index of the first element in the array.
  6692. * @return {Array<number>} The vector components.
  6693. */
  6694. toArray( array = [], offset = 0 ) {
  6695. array[ offset ] = this.x;
  6696. array[ offset + 1 ] = this.y;
  6697. array[ offset + 2 ] = this.z;
  6698. array[ offset + 3 ] = this.w;
  6699. return array;
  6700. }
  6701. /**
  6702. * Sets the components of this vector from the given buffer attribute.
  6703. *
  6704. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6705. * @param {number} index - The index into the attribute.
  6706. * @return {Vector4} A reference to this vector.
  6707. */
  6708. fromBufferAttribute( attribute, index ) {
  6709. this.x = attribute.getX( index );
  6710. this.y = attribute.getY( index );
  6711. this.z = attribute.getZ( index );
  6712. this.w = attribute.getW( index );
  6713. return this;
  6714. }
  6715. /**
  6716. * Sets each component of this vector to a pseudo-random value between `0` and
  6717. * `1`, excluding `1`.
  6718. *
  6719. * @return {Vector4} A reference to this vector.
  6720. */
  6721. random() {
  6722. this.x = Math.random();
  6723. this.y = Math.random();
  6724. this.z = Math.random();
  6725. this.w = Math.random();
  6726. return this;
  6727. }
  6728. *[ Symbol.iterator ]() {
  6729. yield this.x;
  6730. yield this.y;
  6731. yield this.z;
  6732. yield this.w;
  6733. }
  6734. }
  6735. /**
  6736. * A render target is a buffer where the video card draws pixels for a scene
  6737. * that is being rendered in the background. It is used in different effects,
  6738. * such as applying postprocessing to a rendered image before displaying it
  6739. * on the screen.
  6740. *
  6741. * @augments EventDispatcher
  6742. */
  6743. class RenderTarget extends EventDispatcher {
  6744. /**
  6745. * Render target options.
  6746. *
  6747. * @typedef {Object} RenderTarget~Options
  6748. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6749. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6750. * @property {number} [minFilter=LinearFilter] - The min filter.
  6751. * @property {number} [format=RGBAFormat] - The texture format.
  6752. * @property {number} [type=UnsignedByteType] - The texture type.
  6753. * @property {?string} [internalFormat=null] - The texture's internal format.
  6754. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6755. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6756. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6757. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6758. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6759. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6760. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6761. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6762. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6763. * @property {number} [samples=0] - The MSAA samples count.
  6764. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6765. * @property {number} [depth=1] - The texture depth.
  6766. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6767. */
  6768. /**
  6769. * Constructs a new render target.
  6770. *
  6771. * @param {number} [width=1] - The width of the render target.
  6772. * @param {number} [height=1] - The height of the render target.
  6773. * @param {RenderTarget~Options} [options] - The configuration object.
  6774. */
  6775. constructor( width = 1, height = 1, options = {} ) {
  6776. super();
  6777. options = Object.assign( {
  6778. generateMipmaps: false,
  6779. internalFormat: null,
  6780. minFilter: LinearFilter,
  6781. depthBuffer: true,
  6782. stencilBuffer: false,
  6783. resolveDepthBuffer: true,
  6784. resolveStencilBuffer: true,
  6785. depthTexture: null,
  6786. samples: 0,
  6787. count: 1,
  6788. depth: 1,
  6789. multiview: false
  6790. }, options );
  6791. /**
  6792. * This flag can be used for type testing.
  6793. *
  6794. * @type {boolean}
  6795. * @readonly
  6796. * @default true
  6797. */
  6798. this.isRenderTarget = true;
  6799. /**
  6800. * The width of the render target.
  6801. *
  6802. * @type {number}
  6803. * @default 1
  6804. */
  6805. this.width = width;
  6806. /**
  6807. * The height of the render target.
  6808. *
  6809. * @type {number}
  6810. * @default 1
  6811. */
  6812. this.height = height;
  6813. /**
  6814. * The depth of the render target.
  6815. *
  6816. * @type {number}
  6817. * @default 1
  6818. */
  6819. this.depth = options.depth;
  6820. /**
  6821. * A rectangular area inside the render target's viewport. Fragments that are
  6822. * outside the area will be discarded.
  6823. *
  6824. * @type {Vector4}
  6825. * @default (0,0,width,height)
  6826. */
  6827. this.scissor = new Vector4( 0, 0, width, height );
  6828. /**
  6829. * Indicates whether the scissor test should be enabled when rendering into
  6830. * this render target or not.
  6831. *
  6832. * @type {boolean}
  6833. * @default false
  6834. */
  6835. this.scissorTest = false;
  6836. /**
  6837. * A rectangular area representing the render target's viewport.
  6838. *
  6839. * @type {Vector4}
  6840. * @default (0,0,width,height)
  6841. */
  6842. this.viewport = new Vector4( 0, 0, width, height );
  6843. const image = { width: width, height: height, depth: options.depth };
  6844. const texture = new Texture( image );
  6845. /**
  6846. * An array of textures. Each color attachment is represented as a separate texture.
  6847. * Has at least a single entry for the default color attachment.
  6848. *
  6849. * @type {Array<Texture>}
  6850. */
  6851. this.textures = [];
  6852. const count = options.count;
  6853. for ( let i = 0; i < count; i ++ ) {
  6854. this.textures[ i ] = texture.clone();
  6855. this.textures[ i ].isRenderTargetTexture = true;
  6856. this.textures[ i ].renderTarget = this;
  6857. }
  6858. this._setTextureOptions( options );
  6859. /**
  6860. * Whether to allocate a depth buffer or not.
  6861. *
  6862. * @type {boolean}
  6863. * @default true
  6864. */
  6865. this.depthBuffer = options.depthBuffer;
  6866. /**
  6867. * Whether to allocate a stencil buffer or not.
  6868. *
  6869. * @type {boolean}
  6870. * @default false
  6871. */
  6872. this.stencilBuffer = options.stencilBuffer;
  6873. /**
  6874. * Whether to resolve the depth buffer or not.
  6875. *
  6876. * @type {boolean}
  6877. * @default true
  6878. */
  6879. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6880. /**
  6881. * Whether to resolve the stencil buffer or not.
  6882. *
  6883. * @type {boolean}
  6884. * @default true
  6885. */
  6886. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6887. this._depthTexture = null;
  6888. this.depthTexture = options.depthTexture;
  6889. /**
  6890. * The number of MSAA samples.
  6891. *
  6892. * A value of `0` disables MSAA.
  6893. *
  6894. * @type {number}
  6895. * @default 0
  6896. */
  6897. this.samples = options.samples;
  6898. /**
  6899. * Whether to this target is used in multiview rendering.
  6900. *
  6901. * @type {boolean}
  6902. * @default false
  6903. */
  6904. this.multiview = options.multiview;
  6905. }
  6906. _setTextureOptions( options = {} ) {
  6907. const values = {
  6908. minFilter: LinearFilter,
  6909. generateMipmaps: false,
  6910. flipY: false,
  6911. internalFormat: null
  6912. };
  6913. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6914. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6915. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6916. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6917. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6918. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6919. if ( options.format !== undefined ) values.format = options.format;
  6920. if ( options.type !== undefined ) values.type = options.type;
  6921. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6922. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6923. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6924. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6925. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6926. for ( let i = 0; i < this.textures.length; i ++ ) {
  6927. const texture = this.textures[ i ];
  6928. texture.setValues( values );
  6929. }
  6930. }
  6931. /**
  6932. * The texture representing the default color attachment.
  6933. *
  6934. * @type {Texture}
  6935. */
  6936. get texture() {
  6937. return this.textures[ 0 ];
  6938. }
  6939. set texture( value ) {
  6940. this.textures[ 0 ] = value;
  6941. }
  6942. set depthTexture( current ) {
  6943. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6944. if ( current !== null ) current.renderTarget = this;
  6945. this._depthTexture = current;
  6946. }
  6947. /**
  6948. * Instead of saving the depth in a renderbuffer, a texture
  6949. * can be used instead which is useful for further processing
  6950. * e.g. in context of post-processing.
  6951. *
  6952. * @type {?DepthTexture}
  6953. * @default null
  6954. */
  6955. get depthTexture() {
  6956. return this._depthTexture;
  6957. }
  6958. /**
  6959. * Sets the size of this render target.
  6960. *
  6961. * @param {number} width - The width.
  6962. * @param {number} height - The height.
  6963. * @param {number} [depth=1] - The depth.
  6964. */
  6965. setSize( width, height, depth = 1 ) {
  6966. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  6967. this.width = width;
  6968. this.height = height;
  6969. this.depth = depth;
  6970. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  6971. this.textures[ i ].image.width = width;
  6972. this.textures[ i ].image.height = height;
  6973. this.textures[ i ].image.depth = depth;
  6974. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  6975. }
  6976. this.dispose();
  6977. }
  6978. this.viewport.set( 0, 0, width, height );
  6979. this.scissor.set( 0, 0, width, height );
  6980. }
  6981. /**
  6982. * Returns a new render target with copied values from this instance.
  6983. *
  6984. * @return {RenderTarget} A clone of this instance.
  6985. */
  6986. clone() {
  6987. return new this.constructor().copy( this );
  6988. }
  6989. /**
  6990. * Copies the settings of the given render target. This is a structural copy so
  6991. * no resources are shared between render targets after the copy. That includes
  6992. * all MRT textures and the depth texture.
  6993. *
  6994. * @param {RenderTarget} source - The render target to copy.
  6995. * @return {RenderTarget} A reference to this instance.
  6996. */
  6997. copy( source ) {
  6998. this.width = source.width;
  6999. this.height = source.height;
  7000. this.depth = source.depth;
  7001. this.scissor.copy( source.scissor );
  7002. this.scissorTest = source.scissorTest;
  7003. this.viewport.copy( source.viewport );
  7004. this.textures.length = 0;
  7005. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7006. this.textures[ i ] = source.textures[ i ].clone();
  7007. this.textures[ i ].isRenderTargetTexture = true;
  7008. this.textures[ i ].renderTarget = this;
  7009. // ensure image object is not shared, see #20328
  7010. const image = Object.assign( {}, source.textures[ i ].image );
  7011. this.textures[ i ].source = new Source( image );
  7012. }
  7013. this.depthBuffer = source.depthBuffer;
  7014. this.stencilBuffer = source.stencilBuffer;
  7015. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7016. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7017. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7018. this.samples = source.samples;
  7019. return this;
  7020. }
  7021. /**
  7022. * Frees the GPU-related resources allocated by this instance. Call this
  7023. * method whenever this instance is no longer used in your app.
  7024. *
  7025. * @fires RenderTarget#dispose
  7026. */
  7027. dispose() {
  7028. this.dispatchEvent( { type: 'dispose' } );
  7029. }
  7030. }
  7031. /**
  7032. * A render target used in context of {@link WebGLRenderer}.
  7033. *
  7034. * @augments RenderTarget
  7035. */
  7036. class WebGLRenderTarget extends RenderTarget {
  7037. /**
  7038. * Constructs a new 3D render target.
  7039. *
  7040. * @param {number} [width=1] - The width of the render target.
  7041. * @param {number} [height=1] - The height of the render target.
  7042. * @param {RenderTarget~Options} [options] - The configuration object.
  7043. */
  7044. constructor( width = 1, height = 1, options = {} ) {
  7045. super( width, height, options );
  7046. /**
  7047. * This flag can be used for type testing.
  7048. *
  7049. * @type {boolean}
  7050. * @readonly
  7051. * @default true
  7052. */
  7053. this.isWebGLRenderTarget = true;
  7054. }
  7055. }
  7056. /**
  7057. * Creates an array of textures directly from raw buffer data.
  7058. *
  7059. * @augments Texture
  7060. */
  7061. class DataArrayTexture extends Texture {
  7062. /**
  7063. * Constructs a new data array texture.
  7064. *
  7065. * @param {?TypedArray} [data=null] - The buffer data.
  7066. * @param {number} [width=1] - The width of the texture.
  7067. * @param {number} [height=1] - The height of the texture.
  7068. * @param {number} [depth=1] - The depth of the texture.
  7069. */
  7070. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7071. super( null );
  7072. /**
  7073. * This flag can be used for type testing.
  7074. *
  7075. * @type {boolean}
  7076. * @readonly
  7077. * @default true
  7078. */
  7079. this.isDataArrayTexture = true;
  7080. /**
  7081. * The image definition of a data texture.
  7082. *
  7083. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7084. */
  7085. this.image = { data, width, height, depth };
  7086. /**
  7087. * How the texture is sampled when a texel covers more than one pixel.
  7088. *
  7089. * Overwritten and set to `NearestFilter` by default.
  7090. *
  7091. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7092. * @default NearestFilter
  7093. */
  7094. this.magFilter = NearestFilter;
  7095. /**
  7096. * How the texture is sampled when a texel covers less than one pixel.
  7097. *
  7098. * Overwritten and set to `NearestFilter` by default.
  7099. *
  7100. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7101. * @default NearestFilter
  7102. */
  7103. this.minFilter = NearestFilter;
  7104. /**
  7105. * This defines how the texture is wrapped in the depth and corresponds to
  7106. * *W* in UVW mapping.
  7107. *
  7108. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7109. * @default ClampToEdgeWrapping
  7110. */
  7111. this.wrapR = ClampToEdgeWrapping;
  7112. /**
  7113. * Whether to generate mipmaps (if possible) for a texture.
  7114. *
  7115. * Overwritten and set to `false` by default.
  7116. *
  7117. * @type {boolean}
  7118. * @default false
  7119. */
  7120. this.generateMipmaps = false;
  7121. /**
  7122. * If set to `true`, the texture is flipped along the vertical axis when
  7123. * uploaded to the GPU.
  7124. *
  7125. * Overwritten and set to `false` by default.
  7126. *
  7127. * @type {boolean}
  7128. * @default false
  7129. */
  7130. this.flipY = false;
  7131. /**
  7132. * Specifies the alignment requirements for the start of each pixel row in memory.
  7133. *
  7134. * Overwritten and set to `1` by default.
  7135. *
  7136. * @type {boolean}
  7137. * @default 1
  7138. */
  7139. this.unpackAlignment = 1;
  7140. /**
  7141. * A set of all layers which need to be updated in the texture.
  7142. *
  7143. * @type {Set<number>}
  7144. */
  7145. this.layerUpdates = new Set();
  7146. }
  7147. /**
  7148. * Describes that a specific layer of the texture needs to be updated.
  7149. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7150. * entire data texture array is sent to the GPU. Marking specific
  7151. * layers will only transmit subsets of all mipmaps associated with a
  7152. * specific depth in the array which is often much more performant.
  7153. *
  7154. * @param {number} layerIndex - The layer index that should be updated.
  7155. */
  7156. addLayerUpdate( layerIndex ) {
  7157. this.layerUpdates.add( layerIndex );
  7158. }
  7159. /**
  7160. * Resets the layer updates registry.
  7161. */
  7162. clearLayerUpdates() {
  7163. this.layerUpdates.clear();
  7164. }
  7165. }
  7166. /**
  7167. * An array render target used in context of {@link WebGLRenderer}.
  7168. *
  7169. * @augments WebGLRenderTarget
  7170. */
  7171. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7172. /**
  7173. * Constructs a new array render target.
  7174. *
  7175. * @param {number} [width=1] - The width of the render target.
  7176. * @param {number} [height=1] - The height of the render target.
  7177. * @param {number} [depth=1] - The height of the render target.
  7178. * @param {RenderTarget~Options} [options] - The configuration object.
  7179. */
  7180. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7181. super( width, height, options );
  7182. /**
  7183. * This flag can be used for type testing.
  7184. *
  7185. * @type {boolean}
  7186. * @readonly
  7187. * @default true
  7188. */
  7189. this.isWebGLArrayRenderTarget = true;
  7190. this.depth = depth;
  7191. /**
  7192. * Overwritten with a different texture type.
  7193. *
  7194. * @type {DataArrayTexture}
  7195. */
  7196. this.texture = new DataArrayTexture( null, width, height, depth );
  7197. this._setTextureOptions( options );
  7198. this.texture.isRenderTargetTexture = true;
  7199. }
  7200. }
  7201. /**
  7202. * Creates a three-dimensional texture from raw data, with parameters to
  7203. * divide it into width, height, and depth.
  7204. *
  7205. * @augments Texture
  7206. */
  7207. class Data3DTexture extends Texture {
  7208. /**
  7209. * Constructs a new data array texture.
  7210. *
  7211. * @param {?TypedArray} [data=null] - The buffer data.
  7212. * @param {number} [width=1] - The width of the texture.
  7213. * @param {number} [height=1] - The height of the texture.
  7214. * @param {number} [depth=1] - The depth of the texture.
  7215. */
  7216. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7217. // We're going to add .setXXX() methods for setting properties later.
  7218. // Users can still set in Data3DTexture directly.
  7219. //
  7220. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7221. // texture.anisotropy = 16;
  7222. //
  7223. // See #14839
  7224. super( null );
  7225. /**
  7226. * This flag can be used for type testing.
  7227. *
  7228. * @type {boolean}
  7229. * @readonly
  7230. * @default true
  7231. */
  7232. this.isData3DTexture = true;
  7233. /**
  7234. * The image definition of a data texture.
  7235. *
  7236. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7237. */
  7238. this.image = { data, width, height, depth };
  7239. /**
  7240. * How the texture is sampled when a texel covers more than one pixel.
  7241. *
  7242. * Overwritten and set to `NearestFilter` by default.
  7243. *
  7244. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7245. * @default NearestFilter
  7246. */
  7247. this.magFilter = NearestFilter;
  7248. /**
  7249. * How the texture is sampled when a texel covers less than one pixel.
  7250. *
  7251. * Overwritten and set to `NearestFilter` by default.
  7252. *
  7253. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7254. * @default NearestFilter
  7255. */
  7256. this.minFilter = NearestFilter;
  7257. /**
  7258. * This defines how the texture is wrapped in the depth and corresponds to
  7259. * *W* in UVW mapping.
  7260. *
  7261. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7262. * @default ClampToEdgeWrapping
  7263. */
  7264. this.wrapR = ClampToEdgeWrapping;
  7265. /**
  7266. * Whether to generate mipmaps (if possible) for a texture.
  7267. *
  7268. * Overwritten and set to `false` by default.
  7269. *
  7270. * @type {boolean}
  7271. * @default false
  7272. */
  7273. this.generateMipmaps = false;
  7274. /**
  7275. * If set to `true`, the texture is flipped along the vertical axis when
  7276. * uploaded to the GPU.
  7277. *
  7278. * Overwritten and set to `false` by default.
  7279. *
  7280. * @type {boolean}
  7281. * @default false
  7282. */
  7283. this.flipY = false;
  7284. /**
  7285. * Specifies the alignment requirements for the start of each pixel row in memory.
  7286. *
  7287. * Overwritten and set to `1` by default.
  7288. *
  7289. * @type {boolean}
  7290. * @default 1
  7291. */
  7292. this.unpackAlignment = 1;
  7293. }
  7294. }
  7295. /**
  7296. * A 3D render target used in context of {@link WebGLRenderer}.
  7297. *
  7298. * @augments WebGLRenderTarget
  7299. */
  7300. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7301. /**
  7302. * Constructs a new 3D render target.
  7303. *
  7304. * @param {number} [width=1] - The width of the render target.
  7305. * @param {number} [height=1] - The height of the render target.
  7306. * @param {number} [depth=1] - The height of the render target.
  7307. * @param {RenderTarget~Options} [options] - The configuration object.
  7308. */
  7309. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7310. super( width, height, options );
  7311. /**
  7312. * This flag can be used for type testing.
  7313. *
  7314. * @type {boolean}
  7315. * @readonly
  7316. * @default true
  7317. */
  7318. this.isWebGL3DRenderTarget = true;
  7319. this.depth = depth;
  7320. /**
  7321. * Overwritten with a different texture type.
  7322. *
  7323. * @type {Data3DTexture}
  7324. */
  7325. this.texture = new Data3DTexture( null, width, height, depth );
  7326. this._setTextureOptions( options );
  7327. this.texture.isRenderTargetTexture = true;
  7328. }
  7329. }
  7330. /**
  7331. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7332. */
  7333. class Box3 {
  7334. /**
  7335. * Constructs a new bounding box.
  7336. *
  7337. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7338. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7339. */
  7340. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7341. /**
  7342. * This flag can be used for type testing.
  7343. *
  7344. * @type {boolean}
  7345. * @readonly
  7346. * @default true
  7347. */
  7348. this.isBox3 = true;
  7349. /**
  7350. * The lower boundary of the box.
  7351. *
  7352. * @type {Vector3}
  7353. */
  7354. this.min = min;
  7355. /**
  7356. * The upper boundary of the box.
  7357. *
  7358. * @type {Vector3}
  7359. */
  7360. this.max = max;
  7361. }
  7362. /**
  7363. * Sets the lower and upper boundaries of this box.
  7364. * Please note that this method only copies the values from the given objects.
  7365. *
  7366. * @param {Vector3} min - The lower boundary of the box.
  7367. * @param {Vector3} max - The upper boundary of the box.
  7368. * @return {Box3} A reference to this bounding box.
  7369. */
  7370. set( min, max ) {
  7371. this.min.copy( min );
  7372. this.max.copy( max );
  7373. return this;
  7374. }
  7375. /**
  7376. * Sets the upper and lower bounds of this box so it encloses the position data
  7377. * in the given array.
  7378. *
  7379. * @param {Array<number>} array - An array holding 3D position data.
  7380. * @return {Box3} A reference to this bounding box.
  7381. */
  7382. setFromArray( array ) {
  7383. this.makeEmpty();
  7384. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7385. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7386. }
  7387. return this;
  7388. }
  7389. /**
  7390. * Sets the upper and lower bounds of this box so it encloses the position data
  7391. * in the given buffer attribute.
  7392. *
  7393. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7394. * @return {Box3} A reference to this bounding box.
  7395. */
  7396. setFromBufferAttribute( attribute ) {
  7397. this.makeEmpty();
  7398. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7399. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7400. }
  7401. return this;
  7402. }
  7403. /**
  7404. * Sets the upper and lower bounds of this box so it encloses the position data
  7405. * in the given array.
  7406. *
  7407. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7408. * @return {Box3} A reference to this bounding box.
  7409. */
  7410. setFromPoints( points ) {
  7411. this.makeEmpty();
  7412. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7413. this.expandByPoint( points[ i ] );
  7414. }
  7415. return this;
  7416. }
  7417. /**
  7418. * Centers this box on the given center vector and sets this box's width, height and
  7419. * depth to the given size values.
  7420. *
  7421. * @param {Vector3} center - The center of the box.
  7422. * @param {Vector3} size - The x, y and z dimensions of the box.
  7423. * @return {Box3} A reference to this bounding box.
  7424. */
  7425. setFromCenterAndSize( center, size ) {
  7426. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7427. this.min.copy( center ).sub( halfSize );
  7428. this.max.copy( center ).add( halfSize );
  7429. return this;
  7430. }
  7431. /**
  7432. * Computes the world-axis-aligned bounding box for the given 3D object
  7433. * (including its children), accounting for the object's, and children's,
  7434. * world transforms. The function may result in a larger box than strictly necessary.
  7435. *
  7436. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7437. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7438. * world-axis-aligned bounding box at the expense of more computation.
  7439. * @return {Box3} A reference to this bounding box.
  7440. */
  7441. setFromObject( object, precise = false ) {
  7442. this.makeEmpty();
  7443. return this.expandByObject( object, precise );
  7444. }
  7445. /**
  7446. * Returns a new box with copied values from this instance.
  7447. *
  7448. * @return {Box3} A clone of this instance.
  7449. */
  7450. clone() {
  7451. return new this.constructor().copy( this );
  7452. }
  7453. /**
  7454. * Copies the values of the given box to this instance.
  7455. *
  7456. * @param {Box3} box - The box to copy.
  7457. * @return {Box3} A reference to this bounding box.
  7458. */
  7459. copy( box ) {
  7460. this.min.copy( box.min );
  7461. this.max.copy( box.max );
  7462. return this;
  7463. }
  7464. /**
  7465. * Makes this box empty which means in encloses a zero space in 3D.
  7466. *
  7467. * @return {Box3} A reference to this bounding box.
  7468. */
  7469. makeEmpty() {
  7470. this.min.x = this.min.y = this.min.z = + Infinity;
  7471. this.max.x = this.max.y = this.max.z = - Infinity;
  7472. return this;
  7473. }
  7474. /**
  7475. * Returns true if this box includes zero points within its bounds.
  7476. * Note that a box with equal lower and upper bounds still includes one
  7477. * point, the one both bounds share.
  7478. *
  7479. * @return {boolean} Whether this box is empty or not.
  7480. */
  7481. isEmpty() {
  7482. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7483. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7484. }
  7485. /**
  7486. * Returns the center point of this box.
  7487. *
  7488. * @param {Vector3} target - The target vector that is used to store the method's result.
  7489. * @return {Vector3} The center point.
  7490. */
  7491. getCenter( target ) {
  7492. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7493. }
  7494. /**
  7495. * Returns the dimensions of this box.
  7496. *
  7497. * @param {Vector3} target - The target vector that is used to store the method's result.
  7498. * @return {Vector3} The size.
  7499. */
  7500. getSize( target ) {
  7501. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7502. }
  7503. /**
  7504. * Expands the boundaries of this box to include the given point.
  7505. *
  7506. * @param {Vector3} point - The point that should be included by the bounding box.
  7507. * @return {Box3} A reference to this bounding box.
  7508. */
  7509. expandByPoint( point ) {
  7510. this.min.min( point );
  7511. this.max.max( point );
  7512. return this;
  7513. }
  7514. /**
  7515. * Expands this box equilaterally by the given vector. The width of this
  7516. * box will be expanded by the x component of the vector in both
  7517. * directions. The height of this box will be expanded by the y component of
  7518. * the vector in both directions. The depth of this box will be
  7519. * expanded by the z component of the vector in both directions.
  7520. *
  7521. * @param {Vector3} vector - The vector that should expand the bounding box.
  7522. * @return {Box3} A reference to this bounding box.
  7523. */
  7524. expandByVector( vector ) {
  7525. this.min.sub( vector );
  7526. this.max.add( vector );
  7527. return this;
  7528. }
  7529. /**
  7530. * Expands each dimension of the box by the given scalar. If negative, the
  7531. * dimensions of the box will be contracted.
  7532. *
  7533. * @param {number} scalar - The scalar value that should expand the bounding box.
  7534. * @return {Box3} A reference to this bounding box.
  7535. */
  7536. expandByScalar( scalar ) {
  7537. this.min.addScalar( - scalar );
  7538. this.max.addScalar( scalar );
  7539. return this;
  7540. }
  7541. /**
  7542. * Expands the boundaries of this box to include the given 3D object and
  7543. * its children, accounting for the object's, and children's, world
  7544. * transforms. The function may result in a larger box than strictly
  7545. * necessary (unless the precise parameter is set to true).
  7546. *
  7547. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7548. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7549. * as little as necessary at the expense of more computation.
  7550. * @return {Box3} A reference to this bounding box.
  7551. */
  7552. expandByObject( object, precise = false ) {
  7553. // Computes the world-axis-aligned bounding box of an object (including its children),
  7554. // accounting for both the object's, and children's, world transforms
  7555. object.updateWorldMatrix( false, false );
  7556. const geometry = object.geometry;
  7557. if ( geometry !== undefined ) {
  7558. const positionAttribute = geometry.getAttribute( 'position' );
  7559. // precise AABB computation based on vertex data requires at least a position attribute.
  7560. // instancing isn't supported so far and uses the normal (conservative) code path.
  7561. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7562. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7563. if ( object.isMesh === true ) {
  7564. object.getVertexPosition( i, _vector$b );
  7565. } else {
  7566. _vector$b.fromBufferAttribute( positionAttribute, i );
  7567. }
  7568. _vector$b.applyMatrix4( object.matrixWorld );
  7569. this.expandByPoint( _vector$b );
  7570. }
  7571. } else {
  7572. if ( object.boundingBox !== undefined ) {
  7573. // object-level bounding box
  7574. if ( object.boundingBox === null ) {
  7575. object.computeBoundingBox();
  7576. }
  7577. _box$4.copy( object.boundingBox );
  7578. } else {
  7579. // geometry-level bounding box
  7580. if ( geometry.boundingBox === null ) {
  7581. geometry.computeBoundingBox();
  7582. }
  7583. _box$4.copy( geometry.boundingBox );
  7584. }
  7585. _box$4.applyMatrix4( object.matrixWorld );
  7586. this.union( _box$4 );
  7587. }
  7588. }
  7589. const children = object.children;
  7590. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7591. this.expandByObject( children[ i ], precise );
  7592. }
  7593. return this;
  7594. }
  7595. /**
  7596. * Returns `true` if the given point lies within or on the boundaries of this box.
  7597. *
  7598. * @param {Vector3} point - The point to test.
  7599. * @return {boolean} Whether the bounding box contains the given point or not.
  7600. */
  7601. containsPoint( point ) {
  7602. return point.x >= this.min.x && point.x <= this.max.x &&
  7603. point.y >= this.min.y && point.y <= this.max.y &&
  7604. point.z >= this.min.z && point.z <= this.max.z;
  7605. }
  7606. /**
  7607. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7608. * If this box and the given one are identical, this function also returns `true`.
  7609. *
  7610. * @param {Box3} box - The bounding box to test.
  7611. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7612. */
  7613. containsBox( box ) {
  7614. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7615. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7616. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7617. }
  7618. /**
  7619. * Returns a point as a proportion of this box's width, height and depth.
  7620. *
  7621. * @param {Vector3} point - A point in 3D space.
  7622. * @param {Vector3} target - The target vector that is used to store the method's result.
  7623. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7624. */
  7625. getParameter( point, target ) {
  7626. // This can potentially have a divide by zero if the box
  7627. // has a size dimension of 0.
  7628. return target.set(
  7629. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7630. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7631. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7632. );
  7633. }
  7634. /**
  7635. * Returns `true` if the given bounding box intersects with this bounding box.
  7636. *
  7637. * @param {Box3} box - The bounding box to test.
  7638. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7639. */
  7640. intersectsBox( box ) {
  7641. // using 6 splitting planes to rule out intersections.
  7642. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7643. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7644. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7645. }
  7646. /**
  7647. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7648. *
  7649. * @param {Sphere} sphere - The bounding sphere to test.
  7650. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7651. */
  7652. intersectsSphere( sphere ) {
  7653. // Find the point on the AABB closest to the sphere center.
  7654. this.clampPoint( sphere.center, _vector$b );
  7655. // If that point is inside the sphere, the AABB and sphere intersect.
  7656. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7657. }
  7658. /**
  7659. * Returns `true` if the given plane intersects with this bounding box.
  7660. *
  7661. * @param {Plane} plane - The plane to test.
  7662. * @return {boolean} Whether the given plane intersects with this bounding box.
  7663. */
  7664. intersectsPlane( plane ) {
  7665. // We compute the minimum and maximum dot product values. If those values
  7666. // are on the same side (back or front) of the plane, then there is no intersection.
  7667. let min, max;
  7668. if ( plane.normal.x > 0 ) {
  7669. min = plane.normal.x * this.min.x;
  7670. max = plane.normal.x * this.max.x;
  7671. } else {
  7672. min = plane.normal.x * this.max.x;
  7673. max = plane.normal.x * this.min.x;
  7674. }
  7675. if ( plane.normal.y > 0 ) {
  7676. min += plane.normal.y * this.min.y;
  7677. max += plane.normal.y * this.max.y;
  7678. } else {
  7679. min += plane.normal.y * this.max.y;
  7680. max += plane.normal.y * this.min.y;
  7681. }
  7682. if ( plane.normal.z > 0 ) {
  7683. min += plane.normal.z * this.min.z;
  7684. max += plane.normal.z * this.max.z;
  7685. } else {
  7686. min += plane.normal.z * this.max.z;
  7687. max += plane.normal.z * this.min.z;
  7688. }
  7689. return ( min <= - plane.constant && max >= - plane.constant );
  7690. }
  7691. /**
  7692. * Returns `true` if the given triangle intersects with this bounding box.
  7693. *
  7694. * @param {Triangle} triangle - The triangle to test.
  7695. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7696. */
  7697. intersectsTriangle( triangle ) {
  7698. if ( this.isEmpty() ) {
  7699. return false;
  7700. }
  7701. // compute box center and extents
  7702. this.getCenter( _center );
  7703. _extents.subVectors( this.max, _center );
  7704. // translate triangle to aabb origin
  7705. _v0$3.subVectors( triangle.a, _center );
  7706. _v1$7.subVectors( triangle.b, _center );
  7707. _v2$4.subVectors( triangle.c, _center );
  7708. // compute edge vectors for triangle
  7709. _f0.subVectors( _v1$7, _v0$3 );
  7710. _f1.subVectors( _v2$4, _v1$7 );
  7711. _f2.subVectors( _v0$3, _v2$4 );
  7712. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7713. // 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
  7714. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7715. let axes = [
  7716. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7717. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7718. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7719. ];
  7720. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7721. return false;
  7722. }
  7723. // test 3 face normals from the aabb
  7724. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7725. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7726. return false;
  7727. }
  7728. // finally testing the face normal of the triangle
  7729. // use already existing triangle edge vectors here
  7730. _triangleNormal.crossVectors( _f0, _f1 );
  7731. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7732. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7733. }
  7734. /**
  7735. * Clamps the given point within the bounds of this box.
  7736. *
  7737. * @param {Vector3} point - The point to clamp.
  7738. * @param {Vector3} target - The target vector that is used to store the method's result.
  7739. * @return {Vector3} The clamped point.
  7740. */
  7741. clampPoint( point, target ) {
  7742. return target.copy( point ).clamp( this.min, this.max );
  7743. }
  7744. /**
  7745. * Returns the euclidean distance from any edge of this box to the specified point. If
  7746. * the given point lies inside of this box, the distance will be `0`.
  7747. *
  7748. * @param {Vector3} point - The point to compute the distance to.
  7749. * @return {number} The euclidean distance.
  7750. */
  7751. distanceToPoint( point ) {
  7752. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7753. }
  7754. /**
  7755. * Returns a bounding sphere that encloses this bounding box.
  7756. *
  7757. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7758. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7759. */
  7760. getBoundingSphere( target ) {
  7761. if ( this.isEmpty() ) {
  7762. target.makeEmpty();
  7763. } else {
  7764. this.getCenter( target.center );
  7765. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7766. }
  7767. return target;
  7768. }
  7769. /**
  7770. * Computes the intersection of this bounding box and the given one, setting the upper
  7771. * bound of this box to the lesser of the two boxes' upper bounds and the
  7772. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7773. * there's no overlap, makes this box empty.
  7774. *
  7775. * @param {Box3} box - The bounding box to intersect with.
  7776. * @return {Box3} A reference to this bounding box.
  7777. */
  7778. intersect( box ) {
  7779. this.min.max( box.min );
  7780. this.max.min( box.max );
  7781. // 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.
  7782. if ( this.isEmpty() ) this.makeEmpty();
  7783. return this;
  7784. }
  7785. /**
  7786. * Computes the union of this box and another and the given one, setting the upper
  7787. * bound of this box to the greater of the two boxes' upper bounds and the
  7788. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7789. *
  7790. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7791. * @return {Box3} A reference to this bounding box.
  7792. */
  7793. union( box ) {
  7794. this.min.min( box.min );
  7795. this.max.max( box.max );
  7796. return this;
  7797. }
  7798. /**
  7799. * Transforms this bounding box by the given 4x4 transformation matrix.
  7800. *
  7801. * @param {Matrix4} matrix - The transformation matrix.
  7802. * @return {Box3} A reference to this bounding box.
  7803. */
  7804. applyMatrix4( matrix ) {
  7805. // transform of empty box is an empty box.
  7806. if ( this.isEmpty() ) return this;
  7807. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7808. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7809. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7810. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7811. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7812. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7813. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7814. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7815. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7816. this.setFromPoints( _points );
  7817. return this;
  7818. }
  7819. /**
  7820. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7821. * effectively moving it in 3D space.
  7822. *
  7823. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7824. * @return {Box3} A reference to this bounding box.
  7825. */
  7826. translate( offset ) {
  7827. this.min.add( offset );
  7828. this.max.add( offset );
  7829. return this;
  7830. }
  7831. /**
  7832. * Returns `true` if this bounding box is equal with the given one.
  7833. *
  7834. * @param {Box3} box - The box to test for equality.
  7835. * @return {boolean} Whether this bounding box is equal with the given one.
  7836. */
  7837. equals( box ) {
  7838. return box.min.equals( this.min ) && box.max.equals( this.max );
  7839. }
  7840. /**
  7841. * Returns a serialized structure of the bounding box.
  7842. *
  7843. * @return {Object} Serialized structure with fields representing the object state.
  7844. */
  7845. toJSON() {
  7846. return {
  7847. min: this.min.toArray(),
  7848. max: this.max.toArray()
  7849. };
  7850. }
  7851. /**
  7852. * Returns a serialized structure of the bounding box.
  7853. *
  7854. * @param {Object} json - The serialized json to set the box from.
  7855. * @return {Box3} A reference to this bounding box.
  7856. */
  7857. fromJSON( json ) {
  7858. this.min.fromArray( json.min );
  7859. this.max.fromArray( json.max );
  7860. return this;
  7861. }
  7862. }
  7863. const _points = [
  7864. /*@__PURE__*/ new Vector3(),
  7865. /*@__PURE__*/ new Vector3(),
  7866. /*@__PURE__*/ new Vector3(),
  7867. /*@__PURE__*/ new Vector3(),
  7868. /*@__PURE__*/ new Vector3(),
  7869. /*@__PURE__*/ new Vector3(),
  7870. /*@__PURE__*/ new Vector3(),
  7871. /*@__PURE__*/ new Vector3()
  7872. ];
  7873. const _vector$b = /*@__PURE__*/ new Vector3();
  7874. const _box$4 = /*@__PURE__*/ new Box3();
  7875. // triangle centered vertices
  7876. const _v0$3 = /*@__PURE__*/ new Vector3();
  7877. const _v1$7 = /*@__PURE__*/ new Vector3();
  7878. const _v2$4 = /*@__PURE__*/ new Vector3();
  7879. // triangle edge vectors
  7880. const _f0 = /*@__PURE__*/ new Vector3();
  7881. const _f1 = /*@__PURE__*/ new Vector3();
  7882. const _f2 = /*@__PURE__*/ new Vector3();
  7883. const _center = /*@__PURE__*/ new Vector3();
  7884. const _extents = /*@__PURE__*/ new Vector3();
  7885. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7886. const _testAxis = /*@__PURE__*/ new Vector3();
  7887. function satForAxes( axes, v0, v1, v2, extents ) {
  7888. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7889. _testAxis.fromArray( axes, i );
  7890. // project the aabb onto the separating axis
  7891. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7892. // project all 3 vertices of the triangle onto the separating axis
  7893. const p0 = v0.dot( _testAxis );
  7894. const p1 = v1.dot( _testAxis );
  7895. const p2 = v2.dot( _testAxis );
  7896. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7897. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7898. // points of the projected triangle are outside the projected half-length of the aabb
  7899. // the axis is separating and we can exit
  7900. return false;
  7901. }
  7902. }
  7903. return true;
  7904. }
  7905. const _box$3 = /*@__PURE__*/ new Box3();
  7906. const _v1$6 = /*@__PURE__*/ new Vector3();
  7907. const _v2$3 = /*@__PURE__*/ new Vector3();
  7908. /**
  7909. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7910. * used as a Bounding Sphere for 3D objects.
  7911. */
  7912. class Sphere {
  7913. /**
  7914. * Constructs a new sphere.
  7915. *
  7916. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7917. * @param {number} [radius=-1] - The radius of the sphere.
  7918. */
  7919. constructor( center = new Vector3(), radius = -1 ) {
  7920. /**
  7921. * This flag can be used for type testing.
  7922. *
  7923. * @type {boolean}
  7924. * @readonly
  7925. * @default true
  7926. */
  7927. this.isSphere = true;
  7928. /**
  7929. * The center of the sphere
  7930. *
  7931. * @type {Vector3}
  7932. */
  7933. this.center = center;
  7934. /**
  7935. * The radius of the sphere.
  7936. *
  7937. * @type {number}
  7938. */
  7939. this.radius = radius;
  7940. }
  7941. /**
  7942. * Sets the sphere's components by copying the given values.
  7943. *
  7944. * @param {Vector3} center - The center.
  7945. * @param {number} radius - The radius.
  7946. * @return {Sphere} A reference to this sphere.
  7947. */
  7948. set( center, radius ) {
  7949. this.center.copy( center );
  7950. this.radius = radius;
  7951. return this;
  7952. }
  7953. /**
  7954. * Computes the minimum bounding sphere for list of points.
  7955. * If the optional center point is given, it is used as the sphere's
  7956. * center. Otherwise, the center of the axis-aligned bounding box
  7957. * encompassing the points is calculated.
  7958. *
  7959. * @param {Array<Vector3>} points - A list of points in 3D space.
  7960. * @param {Vector3} [optionalCenter] - The center of the sphere.
  7961. * @return {Sphere} A reference to this sphere.
  7962. */
  7963. setFromPoints( points, optionalCenter ) {
  7964. const center = this.center;
  7965. if ( optionalCenter !== undefined ) {
  7966. center.copy( optionalCenter );
  7967. } else {
  7968. _box$3.setFromPoints( points ).getCenter( center );
  7969. }
  7970. let maxRadiusSq = 0;
  7971. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7972. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  7973. }
  7974. this.radius = Math.sqrt( maxRadiusSq );
  7975. return this;
  7976. }
  7977. /**
  7978. * Copies the values of the given sphere to this instance.
  7979. *
  7980. * @param {Sphere} sphere - The sphere to copy.
  7981. * @return {Sphere} A reference to this sphere.
  7982. */
  7983. copy( sphere ) {
  7984. this.center.copy( sphere.center );
  7985. this.radius = sphere.radius;
  7986. return this;
  7987. }
  7988. /**
  7989. * Returns `true` if the sphere is empty (the radius set to a negative number).
  7990. *
  7991. * Spheres with a radius of `0` contain only their center point and are not
  7992. * considered to be empty.
  7993. *
  7994. * @return {boolean} Whether this sphere is empty or not.
  7995. */
  7996. isEmpty() {
  7997. return ( this.radius < 0 );
  7998. }
  7999. /**
  8000. * Makes this sphere empty which means in encloses a zero space in 3D.
  8001. *
  8002. * @return {Sphere} A reference to this sphere.
  8003. */
  8004. makeEmpty() {
  8005. this.center.set( 0, 0, 0 );
  8006. this.radius = -1;
  8007. return this;
  8008. }
  8009. /**
  8010. * Returns `true` if this sphere contains the given point inclusive of
  8011. * the surface of the sphere.
  8012. *
  8013. * @param {Vector3} point - The point to check.
  8014. * @return {boolean} Whether this sphere contains the given point or not.
  8015. */
  8016. containsPoint( point ) {
  8017. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8018. }
  8019. /**
  8020. * Returns the closest distance from the boundary of the sphere to the
  8021. * given point. If the sphere contains the point, the distance will
  8022. * be negative.
  8023. *
  8024. * @param {Vector3} point - The point to compute the distance to.
  8025. * @return {number} The distance to the point.
  8026. */
  8027. distanceToPoint( point ) {
  8028. return ( point.distanceTo( this.center ) - this.radius );
  8029. }
  8030. /**
  8031. * Returns `true` if this sphere intersects with the given one.
  8032. *
  8033. * @param {Sphere} sphere - The sphere to test.
  8034. * @return {boolean} Whether this sphere intersects with the given one or not.
  8035. */
  8036. intersectsSphere( sphere ) {
  8037. const radiusSum = this.radius + sphere.radius;
  8038. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8039. }
  8040. /**
  8041. * Returns `true` if this sphere intersects with the given box.
  8042. *
  8043. * @param {Box3} box - The box to test.
  8044. * @return {boolean} Whether this sphere intersects with the given box or not.
  8045. */
  8046. intersectsBox( box ) {
  8047. return box.intersectsSphere( this );
  8048. }
  8049. /**
  8050. * Returns `true` if this sphere intersects with the given plane.
  8051. *
  8052. * @param {Plane} plane - The plane to test.
  8053. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8054. */
  8055. intersectsPlane( plane ) {
  8056. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8057. }
  8058. /**
  8059. * Clamps a point within the sphere. If the point is outside the sphere, it
  8060. * will clamp it to the closest point on the edge of the sphere. Points
  8061. * already inside the sphere will not be affected.
  8062. *
  8063. * @param {Vector3} point - The plane to clamp.
  8064. * @param {Vector3} target - The target vector that is used to store the method's result.
  8065. * @return {Vector3} The clamped point.
  8066. */
  8067. clampPoint( point, target ) {
  8068. const deltaLengthSq = this.center.distanceToSquared( point );
  8069. target.copy( point );
  8070. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8071. target.sub( this.center ).normalize();
  8072. target.multiplyScalar( this.radius ).add( this.center );
  8073. }
  8074. return target;
  8075. }
  8076. /**
  8077. * Returns a bounding box that encloses this sphere.
  8078. *
  8079. * @param {Box3} target - The target box that is used to store the method's result.
  8080. * @return {Box3} The bounding box that encloses this sphere.
  8081. */
  8082. getBoundingBox( target ) {
  8083. if ( this.isEmpty() ) {
  8084. // Empty sphere produces empty bounding box
  8085. target.makeEmpty();
  8086. return target;
  8087. }
  8088. target.set( this.center, this.center );
  8089. target.expandByScalar( this.radius );
  8090. return target;
  8091. }
  8092. /**
  8093. * Transforms this sphere with the given 4x4 transformation matrix.
  8094. *
  8095. * @param {Matrix4} matrix - The transformation matrix.
  8096. * @return {Sphere} A reference to this sphere.
  8097. */
  8098. applyMatrix4( matrix ) {
  8099. this.center.applyMatrix4( matrix );
  8100. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8101. return this;
  8102. }
  8103. /**
  8104. * Translates the sphere's center by the given offset.
  8105. *
  8106. * @param {Vector3} offset - The offset.
  8107. * @return {Sphere} A reference to this sphere.
  8108. */
  8109. translate( offset ) {
  8110. this.center.add( offset );
  8111. return this;
  8112. }
  8113. /**
  8114. * Expands the boundaries of this sphere to include the given point.
  8115. *
  8116. * @param {Vector3} point - The point to include.
  8117. * @return {Sphere} A reference to this sphere.
  8118. */
  8119. expandByPoint( point ) {
  8120. if ( this.isEmpty() ) {
  8121. this.center.copy( point );
  8122. this.radius = 0;
  8123. return this;
  8124. }
  8125. _v1$6.subVectors( point, this.center );
  8126. const lengthSq = _v1$6.lengthSq();
  8127. if ( lengthSq > ( this.radius * this.radius ) ) {
  8128. // calculate the minimal sphere
  8129. const length = Math.sqrt( lengthSq );
  8130. const delta = ( length - this.radius ) * 0.5;
  8131. this.center.addScaledVector( _v1$6, delta / length );
  8132. this.radius += delta;
  8133. }
  8134. return this;
  8135. }
  8136. /**
  8137. * Expands this sphere to enclose both the original sphere and the given sphere.
  8138. *
  8139. * @param {Sphere} sphere - The sphere to include.
  8140. * @return {Sphere} A reference to this sphere.
  8141. */
  8142. union( sphere ) {
  8143. if ( sphere.isEmpty() ) {
  8144. return this;
  8145. }
  8146. if ( this.isEmpty() ) {
  8147. this.copy( sphere );
  8148. return this;
  8149. }
  8150. if ( this.center.equals( sphere.center ) === true ) {
  8151. this.radius = Math.max( this.radius, sphere.radius );
  8152. } else {
  8153. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8154. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8155. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8156. }
  8157. return this;
  8158. }
  8159. /**
  8160. * Returns `true` if this sphere is equal with the given one.
  8161. *
  8162. * @param {Sphere} sphere - The sphere to test for equality.
  8163. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8164. */
  8165. equals( sphere ) {
  8166. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8167. }
  8168. /**
  8169. * Returns a new sphere with copied values from this instance.
  8170. *
  8171. * @return {Sphere} A clone of this instance.
  8172. */
  8173. clone() {
  8174. return new this.constructor().copy( this );
  8175. }
  8176. /**
  8177. * Returns a serialized structure of the bounding sphere.
  8178. *
  8179. * @return {Object} Serialized structure with fields representing the object state.
  8180. */
  8181. toJSON() {
  8182. return {
  8183. radius: this.radius,
  8184. center: this.center.toArray()
  8185. };
  8186. }
  8187. /**
  8188. * Returns a serialized structure of the bounding sphere.
  8189. *
  8190. * @param {Object} json - The serialized json to set the sphere from.
  8191. * @return {Box3} A reference to this bounding sphere.
  8192. */
  8193. fromJSON( json ) {
  8194. this.radius = json.radius;
  8195. this.center.fromArray( json.center );
  8196. return this;
  8197. }
  8198. }
  8199. const _vector$a = /*@__PURE__*/ new Vector3();
  8200. const _segCenter = /*@__PURE__*/ new Vector3();
  8201. const _segDir = /*@__PURE__*/ new Vector3();
  8202. const _diff = /*@__PURE__*/ new Vector3();
  8203. const _edge1 = /*@__PURE__*/ new Vector3();
  8204. const _edge2 = /*@__PURE__*/ new Vector3();
  8205. const _normal$1 = /*@__PURE__*/ new Vector3();
  8206. /**
  8207. * A ray that emits from an origin in a certain direction. The class is used by
  8208. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8209. * mouse picking (working out what objects in the 3D space the mouse is over)
  8210. * amongst other things.
  8211. */
  8212. class Ray {
  8213. /**
  8214. * Constructs a new ray.
  8215. *
  8216. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8217. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8218. */
  8219. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8220. /**
  8221. * The origin of the ray.
  8222. *
  8223. * @type {Vector3}
  8224. */
  8225. this.origin = origin;
  8226. /**
  8227. * The (normalized) direction of the ray.
  8228. *
  8229. * @type {Vector3}
  8230. */
  8231. this.direction = direction;
  8232. }
  8233. /**
  8234. * Sets the ray's components by copying the given values.
  8235. *
  8236. * @param {Vector3} origin - The origin.
  8237. * @param {Vector3} direction - The direction.
  8238. * @return {Ray} A reference to this ray.
  8239. */
  8240. set( origin, direction ) {
  8241. this.origin.copy( origin );
  8242. this.direction.copy( direction );
  8243. return this;
  8244. }
  8245. /**
  8246. * Copies the values of the given ray to this instance.
  8247. *
  8248. * @param {Ray} ray - The ray to copy.
  8249. * @return {Ray} A reference to this ray.
  8250. */
  8251. copy( ray ) {
  8252. this.origin.copy( ray.origin );
  8253. this.direction.copy( ray.direction );
  8254. return this;
  8255. }
  8256. /**
  8257. * Returns a vector that is located at a given distance along this ray.
  8258. *
  8259. * @param {number} t - The distance along the ray to retrieve a position for.
  8260. * @param {Vector3} target - The target vector that is used to store the method's result.
  8261. * @return {Vector3} A position on the ray.
  8262. */
  8263. at( t, target ) {
  8264. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8265. }
  8266. /**
  8267. * Adjusts the direction of the ray to point at the given vector in world space.
  8268. *
  8269. * @param {Vector3} v - The target position.
  8270. * @return {Ray} A reference to this ray.
  8271. */
  8272. lookAt( v ) {
  8273. this.direction.copy( v ).sub( this.origin ).normalize();
  8274. return this;
  8275. }
  8276. /**
  8277. * Shift the origin of this ray along its direction by the given distance.
  8278. *
  8279. * @param {number} t - The distance along the ray to interpolate.
  8280. * @return {Ray} A reference to this ray.
  8281. */
  8282. recast( t ) {
  8283. this.origin.copy( this.at( t, _vector$a ) );
  8284. return this;
  8285. }
  8286. /**
  8287. * Returns the point along this ray that is closest to the given point.
  8288. *
  8289. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8290. * @param {Vector3} target - The target vector that is used to store the method's result.
  8291. * @return {Vector3} The closest point on this ray.
  8292. */
  8293. closestPointToPoint( point, target ) {
  8294. target.subVectors( point, this.origin );
  8295. const directionDistance = target.dot( this.direction );
  8296. if ( directionDistance < 0 ) {
  8297. return target.copy( this.origin );
  8298. }
  8299. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8300. }
  8301. /**
  8302. * Returns the distance of the closest approach between this ray and the given point.
  8303. *
  8304. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8305. * @return {number} The distance.
  8306. */
  8307. distanceToPoint( point ) {
  8308. return Math.sqrt( this.distanceSqToPoint( point ) );
  8309. }
  8310. /**
  8311. * Returns the squared distance of the closest approach between this ray and the given point.
  8312. *
  8313. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8314. * @return {number} The squared distance.
  8315. */
  8316. distanceSqToPoint( point ) {
  8317. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8318. // point behind the ray
  8319. if ( directionDistance < 0 ) {
  8320. return this.origin.distanceToSquared( point );
  8321. }
  8322. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8323. return _vector$a.distanceToSquared( point );
  8324. }
  8325. /**
  8326. * Returns the squared distance between this ray and the given line segment.
  8327. *
  8328. * @param {Vector3} v0 - The start point of the line segment.
  8329. * @param {Vector3} v1 - The end point of the line segment.
  8330. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8331. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8332. * @return {number} The squared distance.
  8333. */
  8334. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8335. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8336. // It returns the min distance between the ray and the segment
  8337. // defined by v0 and v1
  8338. // It can also set two optional targets :
  8339. // - The closest point on the ray
  8340. // - The closest point on the segment
  8341. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8342. _segDir.copy( v1 ).sub( v0 ).normalize();
  8343. _diff.copy( this.origin ).sub( _segCenter );
  8344. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8345. const a01 = - this.direction.dot( _segDir );
  8346. const b0 = _diff.dot( this.direction );
  8347. const b1 = - _diff.dot( _segDir );
  8348. const c = _diff.lengthSq();
  8349. const det = Math.abs( 1 - a01 * a01 );
  8350. let s0, s1, sqrDist, extDet;
  8351. if ( det > 0 ) {
  8352. // The ray and segment are not parallel.
  8353. s0 = a01 * b1 - b0;
  8354. s1 = a01 * b0 - b1;
  8355. extDet = segExtent * det;
  8356. if ( s0 >= 0 ) {
  8357. if ( s1 >= - extDet ) {
  8358. if ( s1 <= extDet ) {
  8359. // region 0
  8360. // Minimum at interior points of ray and segment.
  8361. const invDet = 1 / det;
  8362. s0 *= invDet;
  8363. s1 *= invDet;
  8364. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8365. } else {
  8366. // region 1
  8367. s1 = segExtent;
  8368. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8369. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8370. }
  8371. } else {
  8372. // region 5
  8373. s1 = - segExtent;
  8374. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8375. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8376. }
  8377. } else {
  8378. if ( s1 <= - extDet ) {
  8379. // region 4
  8380. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8381. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8382. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8383. } else if ( s1 <= extDet ) {
  8384. // region 3
  8385. s0 = 0;
  8386. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8387. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8388. } else {
  8389. // region 2
  8390. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8391. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8392. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8393. }
  8394. }
  8395. } else {
  8396. // Ray and segment are parallel.
  8397. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8398. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8399. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8400. }
  8401. if ( optionalPointOnRay ) {
  8402. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8403. }
  8404. if ( optionalPointOnSegment ) {
  8405. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8406. }
  8407. return sqrDist;
  8408. }
  8409. /**
  8410. * Intersects this ray with the given sphere, returning the intersection
  8411. * point or `null` if there is no intersection.
  8412. *
  8413. * @param {Sphere} sphere - The sphere to intersect.
  8414. * @param {Vector3} target - The target vector that is used to store the method's result.
  8415. * @return {?Vector3} The intersection point.
  8416. */
  8417. intersectSphere( sphere, target ) {
  8418. _vector$a.subVectors( sphere.center, this.origin );
  8419. const tca = _vector$a.dot( this.direction );
  8420. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8421. const radius2 = sphere.radius * sphere.radius;
  8422. if ( d2 > radius2 ) return null;
  8423. const thc = Math.sqrt( radius2 - d2 );
  8424. // t0 = first intersect point - entrance on front of sphere
  8425. const t0 = tca - thc;
  8426. // t1 = second intersect point - exit point on back of sphere
  8427. const t1 = tca + thc;
  8428. // test to see if t1 is behind the ray - if so, return null
  8429. if ( t1 < 0 ) return null;
  8430. // test to see if t0 is behind the ray:
  8431. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8432. // in order to always return an intersect point that is in front of the ray.
  8433. if ( t0 < 0 ) return this.at( t1, target );
  8434. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8435. return this.at( t0, target );
  8436. }
  8437. /**
  8438. * Returns `true` if this ray intersects with the given sphere.
  8439. *
  8440. * @param {Sphere} sphere - The sphere to intersect.
  8441. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8442. */
  8443. intersectsSphere( sphere ) {
  8444. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8445. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8446. }
  8447. /**
  8448. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8449. * does not intersect with the plane.
  8450. *
  8451. * @param {Plane} plane - The plane to compute the distance to.
  8452. * @return {?number} Whether this ray intersects with the given sphere or not.
  8453. */
  8454. distanceToPlane( plane ) {
  8455. const denominator = plane.normal.dot( this.direction );
  8456. if ( denominator === 0 ) {
  8457. // line is coplanar, return origin
  8458. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8459. return 0;
  8460. }
  8461. // Null is preferable to undefined since undefined means.... it is undefined
  8462. return null;
  8463. }
  8464. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8465. // Return if the ray never intersects the plane
  8466. return t >= 0 ? t : null;
  8467. }
  8468. /**
  8469. * Intersects this ray with the given plane, returning the intersection
  8470. * point or `null` if there is no intersection.
  8471. *
  8472. * @param {Plane} plane - The plane to intersect.
  8473. * @param {Vector3} target - The target vector that is used to store the method's result.
  8474. * @return {?Vector3} The intersection point.
  8475. */
  8476. intersectPlane( plane, target ) {
  8477. const t = this.distanceToPlane( plane );
  8478. if ( t === null ) {
  8479. return null;
  8480. }
  8481. return this.at( t, target );
  8482. }
  8483. /**
  8484. * Returns `true` if this ray intersects with the given plane.
  8485. *
  8486. * @param {Plane} plane - The plane to intersect.
  8487. * @return {boolean} Whether this ray intersects with the given plane or not.
  8488. */
  8489. intersectsPlane( plane ) {
  8490. // check if the ray lies on the plane first
  8491. const distToPoint = plane.distanceToPoint( this.origin );
  8492. if ( distToPoint === 0 ) {
  8493. return true;
  8494. }
  8495. const denominator = plane.normal.dot( this.direction );
  8496. if ( denominator * distToPoint < 0 ) {
  8497. return true;
  8498. }
  8499. // ray origin is behind the plane (and is pointing behind it)
  8500. return false;
  8501. }
  8502. /**
  8503. * Intersects this ray with the given bounding box, returning the intersection
  8504. * point or `null` if there is no intersection.
  8505. *
  8506. * @param {Box3} box - The box to intersect.
  8507. * @param {Vector3} target - The target vector that is used to store the method's result.
  8508. * @return {?Vector3} The intersection point.
  8509. */
  8510. intersectBox( box, target ) {
  8511. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8512. const invdirx = 1 / this.direction.x,
  8513. invdiry = 1 / this.direction.y,
  8514. invdirz = 1 / this.direction.z;
  8515. const origin = this.origin;
  8516. if ( invdirx >= 0 ) {
  8517. tmin = ( box.min.x - origin.x ) * invdirx;
  8518. tmax = ( box.max.x - origin.x ) * invdirx;
  8519. } else {
  8520. tmin = ( box.max.x - origin.x ) * invdirx;
  8521. tmax = ( box.min.x - origin.x ) * invdirx;
  8522. }
  8523. if ( invdiry >= 0 ) {
  8524. tymin = ( box.min.y - origin.y ) * invdiry;
  8525. tymax = ( box.max.y - origin.y ) * invdiry;
  8526. } else {
  8527. tymin = ( box.max.y - origin.y ) * invdiry;
  8528. tymax = ( box.min.y - origin.y ) * invdiry;
  8529. }
  8530. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8531. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8532. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8533. if ( invdirz >= 0 ) {
  8534. tzmin = ( box.min.z - origin.z ) * invdirz;
  8535. tzmax = ( box.max.z - origin.z ) * invdirz;
  8536. } else {
  8537. tzmin = ( box.max.z - origin.z ) * invdirz;
  8538. tzmax = ( box.min.z - origin.z ) * invdirz;
  8539. }
  8540. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8541. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8542. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8543. //return point closest to the ray (positive side)
  8544. if ( tmax < 0 ) return null;
  8545. return this.at( tmin >= 0 ? tmin : tmax, target );
  8546. }
  8547. /**
  8548. * Returns `true` if this ray intersects with the given box.
  8549. *
  8550. * @param {Box3} box - The box to intersect.
  8551. * @return {boolean} Whether this ray intersects with the given box or not.
  8552. */
  8553. intersectsBox( box ) {
  8554. return this.intersectBox( box, _vector$a ) !== null;
  8555. }
  8556. /**
  8557. * Intersects this ray with the given triangle, returning the intersection
  8558. * point or `null` if there is no intersection.
  8559. *
  8560. * @param {Vector3} a - The first vertex of the triangle.
  8561. * @param {Vector3} b - The second vertex of the triangle.
  8562. * @param {Vector3} c - The third vertex of the triangle.
  8563. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8564. * @param {Vector3} target - The target vector that is used to store the method's result.
  8565. * @return {?Vector3} The intersection point.
  8566. */
  8567. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8568. // Compute the offset origin, edges, and normal.
  8569. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8570. _edge1.subVectors( b, a );
  8571. _edge2.subVectors( c, a );
  8572. _normal$1.crossVectors( _edge1, _edge2 );
  8573. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8574. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8575. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8576. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8577. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8578. let DdN = this.direction.dot( _normal$1 );
  8579. let sign;
  8580. if ( DdN > 0 ) {
  8581. if ( backfaceCulling ) return null;
  8582. sign = 1;
  8583. } else if ( DdN < 0 ) {
  8584. sign = -1;
  8585. DdN = - DdN;
  8586. } else {
  8587. return null;
  8588. }
  8589. _diff.subVectors( this.origin, a );
  8590. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8591. // b1 < 0, no intersection
  8592. if ( DdQxE2 < 0 ) {
  8593. return null;
  8594. }
  8595. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8596. // b2 < 0, no intersection
  8597. if ( DdE1xQ < 0 ) {
  8598. return null;
  8599. }
  8600. // b1+b2 > 1, no intersection
  8601. if ( DdQxE2 + DdE1xQ > DdN ) {
  8602. return null;
  8603. }
  8604. // Line intersects triangle, check if ray does.
  8605. const QdN = - sign * _diff.dot( _normal$1 );
  8606. // t < 0, no intersection
  8607. if ( QdN < 0 ) {
  8608. return null;
  8609. }
  8610. // Ray intersects triangle.
  8611. return this.at( QdN / DdN, target );
  8612. }
  8613. /**
  8614. * Transforms this ray with the given 4x4 transformation matrix.
  8615. *
  8616. * @param {Matrix4} matrix4 - The transformation matrix.
  8617. * @return {Ray} A reference to this ray.
  8618. */
  8619. applyMatrix4( matrix4 ) {
  8620. this.origin.applyMatrix4( matrix4 );
  8621. this.direction.transformDirection( matrix4 );
  8622. return this;
  8623. }
  8624. /**
  8625. * Returns `true` if this ray is equal with the given one.
  8626. *
  8627. * @param {Ray} ray - The ray to test for equality.
  8628. * @return {boolean} Whether this ray is equal with the given one.
  8629. */
  8630. equals( ray ) {
  8631. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8632. }
  8633. /**
  8634. * Returns a new ray with copied values from this instance.
  8635. *
  8636. * @return {Ray} A clone of this instance.
  8637. */
  8638. clone() {
  8639. return new this.constructor().copy( this );
  8640. }
  8641. }
  8642. /**
  8643. * Represents a 4x4 matrix.
  8644. *
  8645. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8646. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial]{@link https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices}
  8647. *
  8648. * This allows a 3D vector representing a point in 3D space to undergo
  8649. * transformations such as translation, rotation, shear, scale, reflection,
  8650. * orthogonal or perspective projection and so on, by being multiplied by the
  8651. * matrix. This is known as `applying` the matrix to the vector.
  8652. *
  8653. * A Note on Row-Major and Column-Major Ordering:
  8654. *
  8655. * The constructor and {@link Matrix3#set} method take arguments in
  8656. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  8657. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8658. * This means that calling:
  8659. * ```js
  8660. * const m = new THREE.Matrix4();
  8661. * m.set( 11, 12, 13, 14,
  8662. * 21, 22, 23, 24,
  8663. * 31, 32, 33, 34,
  8664. * 41, 42, 43, 44 );
  8665. * ```
  8666. * will result in the elements array containing:
  8667. * ```js
  8668. * m.elements = [ 11, 21, 31, 41,
  8669. * 12, 22, 32, 42,
  8670. * 13, 23, 33, 43,
  8671. * 14, 24, 34, 44 ];
  8672. * ```
  8673. * and internally all calculations are performed using column-major ordering.
  8674. * However, as the actual ordering makes no difference mathematically and
  8675. * most people are used to thinking about matrices in row-major order, the
  8676. * three.js documentation shows matrices in row-major order. Just bear in
  8677. * mind that if you are reading the source code, you'll have to take the
  8678. * transpose of any matrices outlined here to make sense of the calculations.
  8679. */
  8680. class Matrix4 {
  8681. /**
  8682. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8683. * in row-major order. If no arguments are provided, the constructor
  8684. * initializes the matrix as an identity matrix.
  8685. *
  8686. * @param {number} [n11] - 1-1 matrix element.
  8687. * @param {number} [n12] - 1-2 matrix element.
  8688. * @param {number} [n13] - 1-3 matrix element.
  8689. * @param {number} [n14] - 1-4 matrix element.
  8690. * @param {number} [n21] - 2-1 matrix element.
  8691. * @param {number} [n22] - 2-2 matrix element.
  8692. * @param {number} [n23] - 2-3 matrix element.
  8693. * @param {number} [n24] - 2-4 matrix element.
  8694. * @param {number} [n31] - 3-1 matrix element.
  8695. * @param {number} [n32] - 3-2 matrix element.
  8696. * @param {number} [n33] - 3-3 matrix element.
  8697. * @param {number} [n34] - 3-4 matrix element.
  8698. * @param {number} [n41] - 4-1 matrix element.
  8699. * @param {number} [n42] - 4-2 matrix element.
  8700. * @param {number} [n43] - 4-3 matrix element.
  8701. * @param {number} [n44] - 4-4 matrix element.
  8702. */
  8703. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8704. /**
  8705. * This flag can be used for type testing.
  8706. *
  8707. * @type {boolean}
  8708. * @readonly
  8709. * @default true
  8710. */
  8711. Matrix4.prototype.isMatrix4 = true;
  8712. /**
  8713. * A column-major list of matrix values.
  8714. *
  8715. * @type {Array<number>}
  8716. */
  8717. this.elements = [
  8718. 1, 0, 0, 0,
  8719. 0, 1, 0, 0,
  8720. 0, 0, 1, 0,
  8721. 0, 0, 0, 1
  8722. ];
  8723. if ( n11 !== undefined ) {
  8724. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8725. }
  8726. }
  8727. /**
  8728. * Sets the elements of the matrix.The arguments are supposed to be
  8729. * in row-major order.
  8730. *
  8731. * @param {number} [n11] - 1-1 matrix element.
  8732. * @param {number} [n12] - 1-2 matrix element.
  8733. * @param {number} [n13] - 1-3 matrix element.
  8734. * @param {number} [n14] - 1-4 matrix element.
  8735. * @param {number} [n21] - 2-1 matrix element.
  8736. * @param {number} [n22] - 2-2 matrix element.
  8737. * @param {number} [n23] - 2-3 matrix element.
  8738. * @param {number} [n24] - 2-4 matrix element.
  8739. * @param {number} [n31] - 3-1 matrix element.
  8740. * @param {number} [n32] - 3-2 matrix element.
  8741. * @param {number} [n33] - 3-3 matrix element.
  8742. * @param {number} [n34] - 3-4 matrix element.
  8743. * @param {number} [n41] - 4-1 matrix element.
  8744. * @param {number} [n42] - 4-2 matrix element.
  8745. * @param {number} [n43] - 4-3 matrix element.
  8746. * @param {number} [n44] - 4-4 matrix element.
  8747. * @return {Matrix4} A reference to this matrix.
  8748. */
  8749. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8750. const te = this.elements;
  8751. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8752. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8753. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8754. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8755. return this;
  8756. }
  8757. /**
  8758. * Sets this matrix to the 4x4 identity matrix.
  8759. *
  8760. * @return {Matrix4} A reference to this matrix.
  8761. */
  8762. identity() {
  8763. this.set(
  8764. 1, 0, 0, 0,
  8765. 0, 1, 0, 0,
  8766. 0, 0, 1, 0,
  8767. 0, 0, 0, 1
  8768. );
  8769. return this;
  8770. }
  8771. /**
  8772. * Returns a matrix with copied values from this instance.
  8773. *
  8774. * @return {Matrix4} A clone of this instance.
  8775. */
  8776. clone() {
  8777. return new Matrix4().fromArray( this.elements );
  8778. }
  8779. /**
  8780. * Copies the values of the given matrix to this instance.
  8781. *
  8782. * @param {Matrix4} m - The matrix to copy.
  8783. * @return {Matrix4} A reference to this matrix.
  8784. */
  8785. copy( m ) {
  8786. const te = this.elements;
  8787. const me = m.elements;
  8788. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8789. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8790. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8791. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8792. return this;
  8793. }
  8794. /**
  8795. * Copies the translation component of the given matrix
  8796. * into this matrix's translation component.
  8797. *
  8798. * @param {Matrix4} m - The matrix to copy the translation component.
  8799. * @return {Matrix4} A reference to this matrix.
  8800. */
  8801. copyPosition( m ) {
  8802. const te = this.elements, me = m.elements;
  8803. te[ 12 ] = me[ 12 ];
  8804. te[ 13 ] = me[ 13 ];
  8805. te[ 14 ] = me[ 14 ];
  8806. return this;
  8807. }
  8808. /**
  8809. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8810. *
  8811. * @param {Matrix3} m - The 3x3 matrix.
  8812. * @return {Matrix4} A reference to this matrix.
  8813. */
  8814. setFromMatrix3( m ) {
  8815. const me = m.elements;
  8816. this.set(
  8817. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8818. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8819. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8820. 0, 0, 0, 1
  8821. );
  8822. return this;
  8823. }
  8824. /**
  8825. * Extracts the basis of this matrix into the three axis vectors provided.
  8826. *
  8827. * @param {Vector3} xAxis - The basis's x axis.
  8828. * @param {Vector3} yAxis - The basis's y axis.
  8829. * @param {Vector3} zAxis - The basis's z axis.
  8830. * @return {Matrix4} A reference to this matrix.
  8831. */
  8832. extractBasis( xAxis, yAxis, zAxis ) {
  8833. xAxis.setFromMatrixColumn( this, 0 );
  8834. yAxis.setFromMatrixColumn( this, 1 );
  8835. zAxis.setFromMatrixColumn( this, 2 );
  8836. return this;
  8837. }
  8838. /**
  8839. * Sets the given basis vectors to this matrix.
  8840. *
  8841. * @param {Vector3} xAxis - The basis's x axis.
  8842. * @param {Vector3} yAxis - The basis's y axis.
  8843. * @param {Vector3} zAxis - The basis's z axis.
  8844. * @return {Matrix4} A reference to this matrix.
  8845. */
  8846. makeBasis( xAxis, yAxis, zAxis ) {
  8847. this.set(
  8848. xAxis.x, yAxis.x, zAxis.x, 0,
  8849. xAxis.y, yAxis.y, zAxis.y, 0,
  8850. xAxis.z, yAxis.z, zAxis.z, 0,
  8851. 0, 0, 0, 1
  8852. );
  8853. return this;
  8854. }
  8855. /**
  8856. * Extracts the rotation component of the given matrix
  8857. * into this matrix's rotation component.
  8858. *
  8859. * Note: This method does not support reflection matrices.
  8860. *
  8861. * @param {Matrix4} m - The matrix.
  8862. * @return {Matrix4} A reference to this matrix.
  8863. */
  8864. extractRotation( m ) {
  8865. const te = this.elements;
  8866. const me = m.elements;
  8867. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8868. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8869. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8870. te[ 0 ] = me[ 0 ] * scaleX;
  8871. te[ 1 ] = me[ 1 ] * scaleX;
  8872. te[ 2 ] = me[ 2 ] * scaleX;
  8873. te[ 3 ] = 0;
  8874. te[ 4 ] = me[ 4 ] * scaleY;
  8875. te[ 5 ] = me[ 5 ] * scaleY;
  8876. te[ 6 ] = me[ 6 ] * scaleY;
  8877. te[ 7 ] = 0;
  8878. te[ 8 ] = me[ 8 ] * scaleZ;
  8879. te[ 9 ] = me[ 9 ] * scaleZ;
  8880. te[ 10 ] = me[ 10 ] * scaleZ;
  8881. te[ 11 ] = 0;
  8882. te[ 12 ] = 0;
  8883. te[ 13 ] = 0;
  8884. te[ 14 ] = 0;
  8885. te[ 15 ] = 1;
  8886. return this;
  8887. }
  8888. /**
  8889. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8890. * the rotation specified by the given Euler angles. The rest of
  8891. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8892. * there are six possible outcomes. See [this page]{@link https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix}
  8893. * for a complete list.
  8894. *
  8895. * @param {Euler} euler - The Euler angles.
  8896. * @return {Matrix4} A reference to this matrix.
  8897. */
  8898. makeRotationFromEuler( euler ) {
  8899. const te = this.elements;
  8900. const x = euler.x, y = euler.y, z = euler.z;
  8901. const a = Math.cos( x ), b = Math.sin( x );
  8902. const c = Math.cos( y ), d = Math.sin( y );
  8903. const e = Math.cos( z ), f = Math.sin( z );
  8904. if ( euler.order === 'XYZ' ) {
  8905. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8906. te[ 0 ] = c * e;
  8907. te[ 4 ] = - c * f;
  8908. te[ 8 ] = d;
  8909. te[ 1 ] = af + be * d;
  8910. te[ 5 ] = ae - bf * d;
  8911. te[ 9 ] = - b * c;
  8912. te[ 2 ] = bf - ae * d;
  8913. te[ 6 ] = be + af * d;
  8914. te[ 10 ] = a * c;
  8915. } else if ( euler.order === 'YXZ' ) {
  8916. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8917. te[ 0 ] = ce + df * b;
  8918. te[ 4 ] = de * b - cf;
  8919. te[ 8 ] = a * d;
  8920. te[ 1 ] = a * f;
  8921. te[ 5 ] = a * e;
  8922. te[ 9 ] = - b;
  8923. te[ 2 ] = cf * b - de;
  8924. te[ 6 ] = df + ce * b;
  8925. te[ 10 ] = a * c;
  8926. } else if ( euler.order === 'ZXY' ) {
  8927. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8928. te[ 0 ] = ce - df * b;
  8929. te[ 4 ] = - a * f;
  8930. te[ 8 ] = de + cf * b;
  8931. te[ 1 ] = cf + de * b;
  8932. te[ 5 ] = a * e;
  8933. te[ 9 ] = df - ce * b;
  8934. te[ 2 ] = - a * d;
  8935. te[ 6 ] = b;
  8936. te[ 10 ] = a * c;
  8937. } else if ( euler.order === 'ZYX' ) {
  8938. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8939. te[ 0 ] = c * e;
  8940. te[ 4 ] = be * d - af;
  8941. te[ 8 ] = ae * d + bf;
  8942. te[ 1 ] = c * f;
  8943. te[ 5 ] = bf * d + ae;
  8944. te[ 9 ] = af * d - be;
  8945. te[ 2 ] = - d;
  8946. te[ 6 ] = b * c;
  8947. te[ 10 ] = a * c;
  8948. } else if ( euler.order === 'YZX' ) {
  8949. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8950. te[ 0 ] = c * e;
  8951. te[ 4 ] = bd - ac * f;
  8952. te[ 8 ] = bc * f + ad;
  8953. te[ 1 ] = f;
  8954. te[ 5 ] = a * e;
  8955. te[ 9 ] = - b * e;
  8956. te[ 2 ] = - d * e;
  8957. te[ 6 ] = ad * f + bc;
  8958. te[ 10 ] = ac - bd * f;
  8959. } else if ( euler.order === 'XZY' ) {
  8960. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  8961. te[ 0 ] = c * e;
  8962. te[ 4 ] = - f;
  8963. te[ 8 ] = d * e;
  8964. te[ 1 ] = ac * f + bd;
  8965. te[ 5 ] = a * e;
  8966. te[ 9 ] = ad * f - bc;
  8967. te[ 2 ] = bc * f - ad;
  8968. te[ 6 ] = b * e;
  8969. te[ 10 ] = bd * f + ac;
  8970. }
  8971. // bottom row
  8972. te[ 3 ] = 0;
  8973. te[ 7 ] = 0;
  8974. te[ 11 ] = 0;
  8975. // last column
  8976. te[ 12 ] = 0;
  8977. te[ 13 ] = 0;
  8978. te[ 14 ] = 0;
  8979. te[ 15 ] = 1;
  8980. return this;
  8981. }
  8982. /**
  8983. * Sets the rotation component of this matrix to the rotation specified by
  8984. * the given Quaternion as outlined [here]{@link https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion}
  8985. * The rest of the matrix is set to the identity.
  8986. *
  8987. * @param {Quaternion} q - The Quaternion.
  8988. * @return {Matrix4} A reference to this matrix.
  8989. */
  8990. makeRotationFromQuaternion( q ) {
  8991. return this.compose( _zero, q, _one );
  8992. }
  8993. /**
  8994. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  8995. * `target`, and oriented by the up-direction.
  8996. *
  8997. * @param {Vector3} eye - The eye vector.
  8998. * @param {Vector3} target - The target vector.
  8999. * @param {Vector3} up - The up vector.
  9000. * @return {Matrix4} A reference to this matrix.
  9001. */
  9002. lookAt( eye, target, up ) {
  9003. const te = this.elements;
  9004. _z.subVectors( eye, target );
  9005. if ( _z.lengthSq() === 0 ) {
  9006. // eye and target are in the same position
  9007. _z.z = 1;
  9008. }
  9009. _z.normalize();
  9010. _x.crossVectors( up, _z );
  9011. if ( _x.lengthSq() === 0 ) {
  9012. // up and z are parallel
  9013. if ( Math.abs( up.z ) === 1 ) {
  9014. _z.x += 0.0001;
  9015. } else {
  9016. _z.z += 0.0001;
  9017. }
  9018. _z.normalize();
  9019. _x.crossVectors( up, _z );
  9020. }
  9021. _x.normalize();
  9022. _y.crossVectors( _z, _x );
  9023. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9024. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9025. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9026. return this;
  9027. }
  9028. /**
  9029. * Post-multiplies this matrix by the given 4x4 matrix.
  9030. *
  9031. * @param {Matrix4} m - The matrix to multiply with.
  9032. * @return {Matrix4} A reference to this matrix.
  9033. */
  9034. multiply( m ) {
  9035. return this.multiplyMatrices( this, m );
  9036. }
  9037. /**
  9038. * Pre-multiplies this matrix by the given 4x4 matrix.
  9039. *
  9040. * @param {Matrix4} m - The matrix to multiply with.
  9041. * @return {Matrix4} A reference to this matrix.
  9042. */
  9043. premultiply( m ) {
  9044. return this.multiplyMatrices( m, this );
  9045. }
  9046. /**
  9047. * Multiples the given 4x4 matrices and stores the result
  9048. * in this matrix.
  9049. *
  9050. * @param {Matrix4} a - The first matrix.
  9051. * @param {Matrix4} b - The second matrix.
  9052. * @return {Matrix4} A reference to this matrix.
  9053. */
  9054. multiplyMatrices( a, b ) {
  9055. const ae = a.elements;
  9056. const be = b.elements;
  9057. const te = this.elements;
  9058. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9059. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9060. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9061. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9062. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9063. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9064. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9065. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9066. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9067. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9068. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9069. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9070. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9071. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9072. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9073. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9074. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9075. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9076. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9077. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9078. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9079. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9080. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9081. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9082. return this;
  9083. }
  9084. /**
  9085. * Multiplies every component of the matrix by the given scalar.
  9086. *
  9087. * @param {number} s - The scalar.
  9088. * @return {Matrix4} A reference to this matrix.
  9089. */
  9090. multiplyScalar( s ) {
  9091. const te = this.elements;
  9092. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9093. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9094. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9095. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9096. return this;
  9097. }
  9098. /**
  9099. * Computes and returns the determinant of this matrix.
  9100. *
  9101. * Based on the method outlined [here]{@link http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html}.
  9102. *
  9103. * @return {number} The determinant.
  9104. */
  9105. determinant() {
  9106. const te = this.elements;
  9107. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9108. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9109. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9110. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9111. //TODO: make this more efficient
  9112. return (
  9113. n41 * (
  9114. + n14 * n23 * n32
  9115. - n13 * n24 * n32
  9116. - n14 * n22 * n33
  9117. + n12 * n24 * n33
  9118. + n13 * n22 * n34
  9119. - n12 * n23 * n34
  9120. ) +
  9121. n42 * (
  9122. + n11 * n23 * n34
  9123. - n11 * n24 * n33
  9124. + n14 * n21 * n33
  9125. - n13 * n21 * n34
  9126. + n13 * n24 * n31
  9127. - n14 * n23 * n31
  9128. ) +
  9129. n43 * (
  9130. + n11 * n24 * n32
  9131. - n11 * n22 * n34
  9132. - n14 * n21 * n32
  9133. + n12 * n21 * n34
  9134. + n14 * n22 * n31
  9135. - n12 * n24 * n31
  9136. ) +
  9137. n44 * (
  9138. - n13 * n22 * n31
  9139. - n11 * n23 * n32
  9140. + n11 * n22 * n33
  9141. + n13 * n21 * n32
  9142. - n12 * n21 * n33
  9143. + n12 * n23 * n31
  9144. )
  9145. );
  9146. }
  9147. /**
  9148. * Transposes this matrix in place.
  9149. *
  9150. * @return {Matrix4} A reference to this matrix.
  9151. */
  9152. transpose() {
  9153. const te = this.elements;
  9154. let tmp;
  9155. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9156. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9157. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9158. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9159. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9160. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9161. return this;
  9162. }
  9163. /**
  9164. * Sets the position component for this matrix from the given vector,
  9165. * without affecting the rest of the matrix.
  9166. *
  9167. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9168. * @param {number} y - The y component of the vector.
  9169. * @param {number} z - The z component of the vector.
  9170. * @return {Matrix4} A reference to this matrix.
  9171. */
  9172. setPosition( x, y, z ) {
  9173. const te = this.elements;
  9174. if ( x.isVector3 ) {
  9175. te[ 12 ] = x.x;
  9176. te[ 13 ] = x.y;
  9177. te[ 14 ] = x.z;
  9178. } else {
  9179. te[ 12 ] = x;
  9180. te[ 13 ] = y;
  9181. te[ 14 ] = z;
  9182. }
  9183. return this;
  9184. }
  9185. /**
  9186. * Inverts this matrix, using the [analytic method]{@link https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution}.
  9187. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9188. * a zero matrix instead.
  9189. *
  9190. * @return {Matrix4} A reference to this matrix.
  9191. */
  9192. invert() {
  9193. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9194. const te = this.elements,
  9195. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9196. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9197. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9198. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9199. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9200. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9201. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9202. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9203. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9204. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9205. const detInv = 1 / det;
  9206. te[ 0 ] = t11 * detInv;
  9207. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9208. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9209. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9210. te[ 4 ] = t12 * detInv;
  9211. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9212. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9213. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9214. te[ 8 ] = t13 * detInv;
  9215. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9216. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9217. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9218. te[ 12 ] = t14 * detInv;
  9219. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9220. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9221. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9222. return this;
  9223. }
  9224. /**
  9225. * Multiplies the columns of this matrix by the given vector.
  9226. *
  9227. * @param {Vector3} v - The scale vector.
  9228. * @return {Matrix4} A reference to this matrix.
  9229. */
  9230. scale( v ) {
  9231. const te = this.elements;
  9232. const x = v.x, y = v.y, z = v.z;
  9233. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9234. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9235. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9236. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9237. return this;
  9238. }
  9239. /**
  9240. * Gets the maximum scale value of the three axes.
  9241. *
  9242. * @return {number} The maximum scale.
  9243. */
  9244. getMaxScaleOnAxis() {
  9245. const te = this.elements;
  9246. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9247. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9248. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9249. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9250. }
  9251. /**
  9252. * Sets this matrix as a translation transform from the given vector.
  9253. *
  9254. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9255. * @param {number} y - The amount to translate in the Y axis.
  9256. * @param {number} z - The amount to translate in the z axis.
  9257. * @return {Matrix4} A reference to this matrix.
  9258. */
  9259. makeTranslation( x, y, z ) {
  9260. if ( x.isVector3 ) {
  9261. this.set(
  9262. 1, 0, 0, x.x,
  9263. 0, 1, 0, x.y,
  9264. 0, 0, 1, x.z,
  9265. 0, 0, 0, 1
  9266. );
  9267. } else {
  9268. this.set(
  9269. 1, 0, 0, x,
  9270. 0, 1, 0, y,
  9271. 0, 0, 1, z,
  9272. 0, 0, 0, 1
  9273. );
  9274. }
  9275. return this;
  9276. }
  9277. /**
  9278. * Sets this matrix as a rotational transformation around the X axis by
  9279. * the given angle.
  9280. *
  9281. * @param {number} theta - The rotation in radians.
  9282. * @return {Matrix4} A reference to this matrix.
  9283. */
  9284. makeRotationX( theta ) {
  9285. const c = Math.cos( theta ), s = Math.sin( theta );
  9286. this.set(
  9287. 1, 0, 0, 0,
  9288. 0, c, - s, 0,
  9289. 0, s, c, 0,
  9290. 0, 0, 0, 1
  9291. );
  9292. return this;
  9293. }
  9294. /**
  9295. * Sets this matrix as a rotational transformation around the Y axis by
  9296. * the given angle.
  9297. *
  9298. * @param {number} theta - The rotation in radians.
  9299. * @return {Matrix4} A reference to this matrix.
  9300. */
  9301. makeRotationY( theta ) {
  9302. const c = Math.cos( theta ), s = Math.sin( theta );
  9303. this.set(
  9304. c, 0, s, 0,
  9305. 0, 1, 0, 0,
  9306. - s, 0, c, 0,
  9307. 0, 0, 0, 1
  9308. );
  9309. return this;
  9310. }
  9311. /**
  9312. * Sets this matrix as a rotational transformation around the Z axis by
  9313. * the given angle.
  9314. *
  9315. * @param {number} theta - The rotation in radians.
  9316. * @return {Matrix4} A reference to this matrix.
  9317. */
  9318. makeRotationZ( theta ) {
  9319. const c = Math.cos( theta ), s = Math.sin( theta );
  9320. this.set(
  9321. c, - s, 0, 0,
  9322. s, c, 0, 0,
  9323. 0, 0, 1, 0,
  9324. 0, 0, 0, 1
  9325. );
  9326. return this;
  9327. }
  9328. /**
  9329. * Sets this matrix as a rotational transformation around the given axis by
  9330. * the given angle.
  9331. *
  9332. * This is a somewhat controversial but mathematically sound alternative to
  9333. * rotating via Quaternions. See the discussion [here]{@link https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199}.
  9334. *
  9335. * @param {Vector3} axis - The normalized rotation axis.
  9336. * @param {number} angle - The rotation in radians.
  9337. * @return {Matrix4} A reference to this matrix.
  9338. */
  9339. makeRotationAxis( axis, angle ) {
  9340. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9341. const c = Math.cos( angle );
  9342. const s = Math.sin( angle );
  9343. const t = 1 - c;
  9344. const x = axis.x, y = axis.y, z = axis.z;
  9345. const tx = t * x, ty = t * y;
  9346. this.set(
  9347. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9348. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9349. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9350. 0, 0, 0, 1
  9351. );
  9352. return this;
  9353. }
  9354. /**
  9355. * Sets this matrix as a scale transformation.
  9356. *
  9357. * @param {number} x - The amount to scale in the X axis.
  9358. * @param {number} y - The amount to scale in the Y axis.
  9359. * @param {number} z - The amount to scale in the Z axis.
  9360. * @return {Matrix4} A reference to this matrix.
  9361. */
  9362. makeScale( x, y, z ) {
  9363. this.set(
  9364. x, 0, 0, 0,
  9365. 0, y, 0, 0,
  9366. 0, 0, z, 0,
  9367. 0, 0, 0, 1
  9368. );
  9369. return this;
  9370. }
  9371. /**
  9372. * Sets this matrix as a shear transformation.
  9373. *
  9374. * @param {number} xy - The amount to shear X by Y.
  9375. * @param {number} xz - The amount to shear X by Z.
  9376. * @param {number} yx - The amount to shear Y by X.
  9377. * @param {number} yz - The amount to shear Y by Z.
  9378. * @param {number} zx - The amount to shear Z by X.
  9379. * @param {number} zy - The amount to shear Z by Y.
  9380. * @return {Matrix4} A reference to this matrix.
  9381. */
  9382. makeShear( xy, xz, yx, yz, zx, zy ) {
  9383. this.set(
  9384. 1, yx, zx, 0,
  9385. xy, 1, zy, 0,
  9386. xz, yz, 1, 0,
  9387. 0, 0, 0, 1
  9388. );
  9389. return this;
  9390. }
  9391. /**
  9392. * Sets this matrix to the transformation composed of the given position,
  9393. * rotation (Quaternion) and scale.
  9394. *
  9395. * @param {Vector3} position - The position vector.
  9396. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9397. * @param {Vector3} scale - The scale vector.
  9398. * @return {Matrix4} A reference to this matrix.
  9399. */
  9400. compose( position, quaternion, scale ) {
  9401. const te = this.elements;
  9402. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9403. const x2 = x + x, y2 = y + y, z2 = z + z;
  9404. const xx = x * x2, xy = x * y2, xz = x * z2;
  9405. const yy = y * y2, yz = y * z2, zz = z * z2;
  9406. const wx = w * x2, wy = w * y2, wz = w * z2;
  9407. const sx = scale.x, sy = scale.y, sz = scale.z;
  9408. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9409. te[ 1 ] = ( xy + wz ) * sx;
  9410. te[ 2 ] = ( xz - wy ) * sx;
  9411. te[ 3 ] = 0;
  9412. te[ 4 ] = ( xy - wz ) * sy;
  9413. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9414. te[ 6 ] = ( yz + wx ) * sy;
  9415. te[ 7 ] = 0;
  9416. te[ 8 ] = ( xz + wy ) * sz;
  9417. te[ 9 ] = ( yz - wx ) * sz;
  9418. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9419. te[ 11 ] = 0;
  9420. te[ 12 ] = position.x;
  9421. te[ 13 ] = position.y;
  9422. te[ 14 ] = position.z;
  9423. te[ 15 ] = 1;
  9424. return this;
  9425. }
  9426. /**
  9427. * Decomposes this matrix into its position, rotation and scale components
  9428. * and provides the result in the given objects.
  9429. *
  9430. * Note: Not all matrices are decomposable in this way. For example, if an
  9431. * object has a non-uniformly scaled parent, then the object's world matrix
  9432. * may not be decomposable, and this method may not be appropriate.
  9433. *
  9434. * @param {Vector3} position - The position vector.
  9435. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9436. * @param {Vector3} scale - The scale vector.
  9437. * @return {Matrix4} A reference to this matrix.
  9438. */
  9439. decompose( position, quaternion, scale ) {
  9440. const te = this.elements;
  9441. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9442. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9443. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9444. // if determine is negative, we need to invert one scale
  9445. const det = this.determinant();
  9446. if ( det < 0 ) sx = - sx;
  9447. position.x = te[ 12 ];
  9448. position.y = te[ 13 ];
  9449. position.z = te[ 14 ];
  9450. // scale the rotation part
  9451. _m1$4.copy( this );
  9452. const invSX = 1 / sx;
  9453. const invSY = 1 / sy;
  9454. const invSZ = 1 / sz;
  9455. _m1$4.elements[ 0 ] *= invSX;
  9456. _m1$4.elements[ 1 ] *= invSX;
  9457. _m1$4.elements[ 2 ] *= invSX;
  9458. _m1$4.elements[ 4 ] *= invSY;
  9459. _m1$4.elements[ 5 ] *= invSY;
  9460. _m1$4.elements[ 6 ] *= invSY;
  9461. _m1$4.elements[ 8 ] *= invSZ;
  9462. _m1$4.elements[ 9 ] *= invSZ;
  9463. _m1$4.elements[ 10 ] *= invSZ;
  9464. quaternion.setFromRotationMatrix( _m1$4 );
  9465. scale.x = sx;
  9466. scale.y = sy;
  9467. scale.z = sz;
  9468. return this;
  9469. }
  9470. /**
  9471. * Creates a perspective projection matrix. This is used internally by
  9472. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9473. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9474. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9475. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9476. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9477. * @param {number} near - The distance from the camera to the near plane.
  9478. * @param {number} far - The distance from the camera to the far plane.
  9479. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9480. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9481. * @return {Matrix4} A reference to this matrix.
  9482. */
  9483. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9484. const te = this.elements;
  9485. const x = 2 * near / ( right - left );
  9486. const y = 2 * near / ( top - bottom );
  9487. const a = ( right + left ) / ( right - left );
  9488. const b = ( top + bottom ) / ( top - bottom );
  9489. let c, d;
  9490. if ( reversedDepth ) {
  9491. c = near / ( far - near );
  9492. d = ( far * near ) / ( far - near );
  9493. } else {
  9494. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9495. c = - ( far + near ) / ( far - near );
  9496. d = ( -2 * far * near ) / ( far - near );
  9497. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9498. c = - far / ( far - near );
  9499. d = ( - far * near ) / ( far - near );
  9500. } else {
  9501. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9502. }
  9503. }
  9504. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9505. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9506. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9507. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9508. return this;
  9509. }
  9510. /**
  9511. * Creates a orthographic projection matrix. This is used internally by
  9512. * {@link OrthographicCamera#updateProjectionMatrix}.
  9513. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9514. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9515. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9516. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9517. * @param {number} near - The distance from the camera to the near plane.
  9518. * @param {number} far - The distance from the camera to the far plane.
  9519. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9520. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9521. * @return {Matrix4} A reference to this matrix.
  9522. */
  9523. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9524. const te = this.elements;
  9525. const x = 2 / ( right - left );
  9526. const y = 2 / ( top - bottom );
  9527. const a = - ( right + left ) / ( right - left );
  9528. const b = - ( top + bottom ) / ( top - bottom );
  9529. let c, d;
  9530. if ( reversedDepth ) {
  9531. c = 1 / ( far - near );
  9532. d = far / ( far - near );
  9533. } else {
  9534. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9535. c = -2 / ( far - near );
  9536. d = - ( far + near ) / ( far - near );
  9537. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9538. c = -1 / ( far - near );
  9539. d = - near / ( far - near );
  9540. } else {
  9541. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9542. }
  9543. }
  9544. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9545. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9546. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9547. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9548. return this;
  9549. }
  9550. /**
  9551. * Returns `true` if this matrix is equal with the given one.
  9552. *
  9553. * @param {Matrix4} matrix - The matrix to test for equality.
  9554. * @return {boolean} Whether this matrix is equal with the given one.
  9555. */
  9556. equals( matrix ) {
  9557. const te = this.elements;
  9558. const me = matrix.elements;
  9559. for ( let i = 0; i < 16; i ++ ) {
  9560. if ( te[ i ] !== me[ i ] ) return false;
  9561. }
  9562. return true;
  9563. }
  9564. /**
  9565. * Sets the elements of the matrix from the given array.
  9566. *
  9567. * @param {Array<number>} array - The matrix elements in column-major order.
  9568. * @param {number} [offset=0] - Index of the first element in the array.
  9569. * @return {Matrix4} A reference to this matrix.
  9570. */
  9571. fromArray( array, offset = 0 ) {
  9572. for ( let i = 0; i < 16; i ++ ) {
  9573. this.elements[ i ] = array[ i + offset ];
  9574. }
  9575. return this;
  9576. }
  9577. /**
  9578. * Writes the elements of this matrix to the given array. If no array is provided,
  9579. * the method returns a new instance.
  9580. *
  9581. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9582. * @param {number} [offset=0] - Index of the first element in the array.
  9583. * @return {Array<number>} The matrix elements in column-major order.
  9584. */
  9585. toArray( array = [], offset = 0 ) {
  9586. const te = this.elements;
  9587. array[ offset ] = te[ 0 ];
  9588. array[ offset + 1 ] = te[ 1 ];
  9589. array[ offset + 2 ] = te[ 2 ];
  9590. array[ offset + 3 ] = te[ 3 ];
  9591. array[ offset + 4 ] = te[ 4 ];
  9592. array[ offset + 5 ] = te[ 5 ];
  9593. array[ offset + 6 ] = te[ 6 ];
  9594. array[ offset + 7 ] = te[ 7 ];
  9595. array[ offset + 8 ] = te[ 8 ];
  9596. array[ offset + 9 ] = te[ 9 ];
  9597. array[ offset + 10 ] = te[ 10 ];
  9598. array[ offset + 11 ] = te[ 11 ];
  9599. array[ offset + 12 ] = te[ 12 ];
  9600. array[ offset + 13 ] = te[ 13 ];
  9601. array[ offset + 14 ] = te[ 14 ];
  9602. array[ offset + 15 ] = te[ 15 ];
  9603. return array;
  9604. }
  9605. }
  9606. const _v1$5 = /*@__PURE__*/ new Vector3();
  9607. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9608. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9609. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9610. const _x = /*@__PURE__*/ new Vector3();
  9611. const _y = /*@__PURE__*/ new Vector3();
  9612. const _z = /*@__PURE__*/ new Vector3();
  9613. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9614. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9615. /**
  9616. * A class representing Euler angles.
  9617. *
  9618. * Euler angles describe a rotational transformation by rotating an object on
  9619. * its various axes in specified amounts per axis, and a specified axis
  9620. * order.
  9621. *
  9622. * Iterating through an instance will yield its components (x, y, z,
  9623. * order) in the corresponding order.
  9624. *
  9625. * ```js
  9626. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9627. * const b = new THREE.Vector3( 1, 0, 1 );
  9628. * b.applyEuler(a);
  9629. * ```
  9630. */
  9631. class Euler {
  9632. /**
  9633. * Constructs a new euler instance.
  9634. *
  9635. * @param {number} [x=0] - The angle of the x axis in radians.
  9636. * @param {number} [y=0] - The angle of the y axis in radians.
  9637. * @param {number} [z=0] - The angle of the z axis in radians.
  9638. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9639. */
  9640. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9641. /**
  9642. * This flag can be used for type testing.
  9643. *
  9644. * @type {boolean}
  9645. * @readonly
  9646. * @default true
  9647. */
  9648. this.isEuler = true;
  9649. this._x = x;
  9650. this._y = y;
  9651. this._z = z;
  9652. this._order = order;
  9653. }
  9654. /**
  9655. * The angle of the x axis in radians.
  9656. *
  9657. * @type {number}
  9658. * @default 0
  9659. */
  9660. get x() {
  9661. return this._x;
  9662. }
  9663. set x( value ) {
  9664. this._x = value;
  9665. this._onChangeCallback();
  9666. }
  9667. /**
  9668. * The angle of the y axis in radians.
  9669. *
  9670. * @type {number}
  9671. * @default 0
  9672. */
  9673. get y() {
  9674. return this._y;
  9675. }
  9676. set y( value ) {
  9677. this._y = value;
  9678. this._onChangeCallback();
  9679. }
  9680. /**
  9681. * The angle of the z axis in radians.
  9682. *
  9683. * @type {number}
  9684. * @default 0
  9685. */
  9686. get z() {
  9687. return this._z;
  9688. }
  9689. set z( value ) {
  9690. this._z = value;
  9691. this._onChangeCallback();
  9692. }
  9693. /**
  9694. * A string representing the order that the rotations are applied.
  9695. *
  9696. * @type {string}
  9697. * @default 'XYZ'
  9698. */
  9699. get order() {
  9700. return this._order;
  9701. }
  9702. set order( value ) {
  9703. this._order = value;
  9704. this._onChangeCallback();
  9705. }
  9706. /**
  9707. * Sets the Euler components.
  9708. *
  9709. * @param {number} x - The angle of the x axis in radians.
  9710. * @param {number} y - The angle of the y axis in radians.
  9711. * @param {number} z - The angle of the z axis in radians.
  9712. * @param {string} [order] - A string representing the order that the rotations are applied.
  9713. * @return {Euler} A reference to this Euler instance.
  9714. */
  9715. set( x, y, z, order = this._order ) {
  9716. this._x = x;
  9717. this._y = y;
  9718. this._z = z;
  9719. this._order = order;
  9720. this._onChangeCallback();
  9721. return this;
  9722. }
  9723. /**
  9724. * Returns a new Euler instance with copied values from this instance.
  9725. *
  9726. * @return {Euler} A clone of this instance.
  9727. */
  9728. clone() {
  9729. return new this.constructor( this._x, this._y, this._z, this._order );
  9730. }
  9731. /**
  9732. * Copies the values of the given Euler instance to this instance.
  9733. *
  9734. * @param {Euler} euler - The Euler instance to copy.
  9735. * @return {Euler} A reference to this Euler instance.
  9736. */
  9737. copy( euler ) {
  9738. this._x = euler._x;
  9739. this._y = euler._y;
  9740. this._z = euler._z;
  9741. this._order = euler._order;
  9742. this._onChangeCallback();
  9743. return this;
  9744. }
  9745. /**
  9746. * Sets the angles of this Euler instance from a pure rotation matrix.
  9747. *
  9748. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9749. * @param {string} [order] - A string representing the order that the rotations are applied.
  9750. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9751. * @return {Euler} A reference to this Euler instance.
  9752. */
  9753. setFromRotationMatrix( m, order = this._order, update = true ) {
  9754. const te = m.elements;
  9755. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9756. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9757. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9758. switch ( order ) {
  9759. case 'XYZ':
  9760. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9761. if ( Math.abs( m13 ) < 0.9999999 ) {
  9762. this._x = Math.atan2( - m23, m33 );
  9763. this._z = Math.atan2( - m12, m11 );
  9764. } else {
  9765. this._x = Math.atan2( m32, m22 );
  9766. this._z = 0;
  9767. }
  9768. break;
  9769. case 'YXZ':
  9770. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9771. if ( Math.abs( m23 ) < 0.9999999 ) {
  9772. this._y = Math.atan2( m13, m33 );
  9773. this._z = Math.atan2( m21, m22 );
  9774. } else {
  9775. this._y = Math.atan2( - m31, m11 );
  9776. this._z = 0;
  9777. }
  9778. break;
  9779. case 'ZXY':
  9780. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9781. if ( Math.abs( m32 ) < 0.9999999 ) {
  9782. this._y = Math.atan2( - m31, m33 );
  9783. this._z = Math.atan2( - m12, m22 );
  9784. } else {
  9785. this._y = 0;
  9786. this._z = Math.atan2( m21, m11 );
  9787. }
  9788. break;
  9789. case 'ZYX':
  9790. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9791. if ( Math.abs( m31 ) < 0.9999999 ) {
  9792. this._x = Math.atan2( m32, m33 );
  9793. this._z = Math.atan2( m21, m11 );
  9794. } else {
  9795. this._x = 0;
  9796. this._z = Math.atan2( - m12, m22 );
  9797. }
  9798. break;
  9799. case 'YZX':
  9800. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9801. if ( Math.abs( m21 ) < 0.9999999 ) {
  9802. this._x = Math.atan2( - m23, m22 );
  9803. this._y = Math.atan2( - m31, m11 );
  9804. } else {
  9805. this._x = 0;
  9806. this._y = Math.atan2( m13, m33 );
  9807. }
  9808. break;
  9809. case 'XZY':
  9810. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9811. if ( Math.abs( m12 ) < 0.9999999 ) {
  9812. this._x = Math.atan2( m32, m22 );
  9813. this._y = Math.atan2( m13, m11 );
  9814. } else {
  9815. this._x = Math.atan2( - m23, m33 );
  9816. this._y = 0;
  9817. }
  9818. break;
  9819. default:
  9820. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9821. }
  9822. this._order = order;
  9823. if ( update === true ) this._onChangeCallback();
  9824. return this;
  9825. }
  9826. /**
  9827. * Sets the angles of this Euler instance from a normalized quaternion.
  9828. *
  9829. * @param {Quaternion} q - A normalized Quaternion.
  9830. * @param {string} [order] - A string representing the order that the rotations are applied.
  9831. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9832. * @return {Euler} A reference to this Euler instance.
  9833. */
  9834. setFromQuaternion( q, order, update ) {
  9835. _matrix$2.makeRotationFromQuaternion( q );
  9836. return this.setFromRotationMatrix( _matrix$2, order, update );
  9837. }
  9838. /**
  9839. * Sets the angles of this Euler instance from the given vector.
  9840. *
  9841. * @param {Vector3} v - The vector.
  9842. * @param {string} [order] - A string representing the order that the rotations are applied.
  9843. * @return {Euler} A reference to this Euler instance.
  9844. */
  9845. setFromVector3( v, order = this._order ) {
  9846. return this.set( v.x, v.y, v.z, order );
  9847. }
  9848. /**
  9849. * Resets the euler angle with a new order by creating a quaternion from this
  9850. * euler angle and then setting this euler angle with the quaternion and the
  9851. * new order.
  9852. *
  9853. * Warning: This discards revolution information.
  9854. *
  9855. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9856. * @return {Euler} A reference to this Euler instance.
  9857. */
  9858. reorder( newOrder ) {
  9859. _quaternion$3.setFromEuler( this );
  9860. return this.setFromQuaternion( _quaternion$3, newOrder );
  9861. }
  9862. /**
  9863. * Returns `true` if this Euler instance is equal with the given one.
  9864. *
  9865. * @param {Euler} euler - The Euler instance to test for equality.
  9866. * @return {boolean} Whether this Euler instance is equal with the given one.
  9867. */
  9868. equals( euler ) {
  9869. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9870. }
  9871. /**
  9872. * Sets this Euler instance's components to values from the given array. The first three
  9873. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9874. * defines the Euler order.
  9875. *
  9876. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9877. * @return {Euler} A reference to this Euler instance.
  9878. */
  9879. fromArray( array ) {
  9880. this._x = array[ 0 ];
  9881. this._y = array[ 1 ];
  9882. this._z = array[ 2 ];
  9883. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9884. this._onChangeCallback();
  9885. return this;
  9886. }
  9887. /**
  9888. * Writes the components of this Euler instance to the given array. If no array is provided,
  9889. * the method returns a new instance.
  9890. *
  9891. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9892. * @param {number} [offset=0] - Index of the first element in the array.
  9893. * @return {Array<number,number,number,string>} The Euler components.
  9894. */
  9895. toArray( array = [], offset = 0 ) {
  9896. array[ offset ] = this._x;
  9897. array[ offset + 1 ] = this._y;
  9898. array[ offset + 2 ] = this._z;
  9899. array[ offset + 3 ] = this._order;
  9900. return array;
  9901. }
  9902. _onChange( callback ) {
  9903. this._onChangeCallback = callback;
  9904. return this;
  9905. }
  9906. _onChangeCallback() {}
  9907. *[ Symbol.iterator ]() {
  9908. yield this._x;
  9909. yield this._y;
  9910. yield this._z;
  9911. yield this._order;
  9912. }
  9913. }
  9914. /**
  9915. * The default Euler angle order.
  9916. *
  9917. * @static
  9918. * @type {string}
  9919. * @default 'XYZ'
  9920. */
  9921. Euler.DEFAULT_ORDER = 'XYZ';
  9922. /**
  9923. * A layers object assigns an 3D object to 1 or more of 32
  9924. * layers numbered `0` to `31` - internally the layers are stored as a
  9925. * bit mask], and by default all 3D objects are a member of layer `0`.
  9926. *
  9927. * This can be used to control visibility - an object must share a layer with
  9928. * a camera to be visible when that camera's view is
  9929. * rendered.
  9930. *
  9931. * All classes that inherit from {@link Object3D} have an `layers` property which
  9932. * is an instance of this class.
  9933. */
  9934. class Layers {
  9935. /**
  9936. * Constructs a new layers instance, with membership
  9937. * initially set to layer `0`.
  9938. */
  9939. constructor() {
  9940. /**
  9941. * A bit mask storing which of the 32 layers this layers object is currently
  9942. * a member of.
  9943. *
  9944. * @type {number}
  9945. */
  9946. this.mask = 1 | 0;
  9947. }
  9948. /**
  9949. * Sets membership to the given layer, and remove membership all other layers.
  9950. *
  9951. * @param {number} layer - The layer to set.
  9952. */
  9953. set( layer ) {
  9954. this.mask = ( 1 << layer | 0 ) >>> 0;
  9955. }
  9956. /**
  9957. * Adds membership of the given layer.
  9958. *
  9959. * @param {number} layer - The layer to enable.
  9960. */
  9961. enable( layer ) {
  9962. this.mask |= 1 << layer | 0;
  9963. }
  9964. /**
  9965. * Adds membership to all layers.
  9966. */
  9967. enableAll() {
  9968. this.mask = 0xffffffff | 0;
  9969. }
  9970. /**
  9971. * Toggles the membership of the given layer.
  9972. *
  9973. * @param {number} layer - The layer to toggle.
  9974. */
  9975. toggle( layer ) {
  9976. this.mask ^= 1 << layer | 0;
  9977. }
  9978. /**
  9979. * Removes membership of the given layer.
  9980. *
  9981. * @param {number} layer - The layer to enable.
  9982. */
  9983. disable( layer ) {
  9984. this.mask &= ~ ( 1 << layer | 0 );
  9985. }
  9986. /**
  9987. * Removes the membership from all layers.
  9988. */
  9989. disableAll() {
  9990. this.mask = 0;
  9991. }
  9992. /**
  9993. * Returns `true` if this and the given layers object have at least one
  9994. * layer in common.
  9995. *
  9996. * @param {Layers} layers - The layers to test.
  9997. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  9998. */
  9999. test( layers ) {
  10000. return ( this.mask & layers.mask ) !== 0;
  10001. }
  10002. /**
  10003. * Returns `true` if the given layer is enabled.
  10004. *
  10005. * @param {number} layer - The layer to test.
  10006. * @return {boolean } Whether the given layer is enabled or not.
  10007. */
  10008. isEnabled( layer ) {
  10009. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10010. }
  10011. }
  10012. let _object3DId = 0;
  10013. const _v1$4 = /*@__PURE__*/ new Vector3();
  10014. const _q1 = /*@__PURE__*/ new Quaternion();
  10015. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10016. const _target = /*@__PURE__*/ new Vector3();
  10017. const _position$3 = /*@__PURE__*/ new Vector3();
  10018. const _scale$2 = /*@__PURE__*/ new Vector3();
  10019. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10020. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10021. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10022. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10023. /**
  10024. * Fires when the object has been added to its parent object.
  10025. *
  10026. * @event Object3D#added
  10027. * @type {Object}
  10028. */
  10029. const _addedEvent = { type: 'added' };
  10030. /**
  10031. * Fires when the object has been removed from its parent object.
  10032. *
  10033. * @event Object3D#removed
  10034. * @type {Object}
  10035. */
  10036. const _removedEvent = { type: 'removed' };
  10037. /**
  10038. * Fires when a new child object has been added.
  10039. *
  10040. * @event Object3D#childadded
  10041. * @type {Object}
  10042. */
  10043. const _childaddedEvent = { type: 'childadded', child: null };
  10044. /**
  10045. * Fires when a child object has been removed.
  10046. *
  10047. * @event Object3D#childremoved
  10048. * @type {Object}
  10049. */
  10050. const _childremovedEvent = { type: 'childremoved', child: null };
  10051. /**
  10052. * This is the base class for most objects in three.js and provides a set of
  10053. * properties and methods for manipulating objects in 3D space.
  10054. *
  10055. * @augments EventDispatcher
  10056. */
  10057. class Object3D extends EventDispatcher {
  10058. /**
  10059. * Constructs a new 3D object.
  10060. */
  10061. constructor() {
  10062. super();
  10063. /**
  10064. * This flag can be used for type testing.
  10065. *
  10066. * @type {boolean}
  10067. * @readonly
  10068. * @default true
  10069. */
  10070. this.isObject3D = true;
  10071. /**
  10072. * The ID of the 3D object.
  10073. *
  10074. * @name Object3D#id
  10075. * @type {number}
  10076. * @readonly
  10077. */
  10078. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10079. /**
  10080. * The UUID of the 3D object.
  10081. *
  10082. * @type {string}
  10083. * @readonly
  10084. */
  10085. this.uuid = generateUUID();
  10086. /**
  10087. * The name of the 3D object.
  10088. *
  10089. * @type {string}
  10090. */
  10091. this.name = '';
  10092. /**
  10093. * The type property is used for detecting the object type
  10094. * in context of serialization/deserialization.
  10095. *
  10096. * @type {string}
  10097. * @readonly
  10098. */
  10099. this.type = 'Object3D';
  10100. /**
  10101. * A reference to the parent object.
  10102. *
  10103. * @type {?Object3D}
  10104. * @default null
  10105. */
  10106. this.parent = null;
  10107. /**
  10108. * An array holding the child 3D objects of this instance.
  10109. *
  10110. * @type {Array<Object3D>}
  10111. */
  10112. this.children = [];
  10113. /**
  10114. * Defines the `up` direction of the 3D object which influences
  10115. * the orientation via methods like {@link Object3D#lookAt}.
  10116. *
  10117. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10118. *
  10119. * @type {Vector3}
  10120. */
  10121. this.up = Object3D.DEFAULT_UP.clone();
  10122. const position = new Vector3();
  10123. const rotation = new Euler();
  10124. const quaternion = new Quaternion();
  10125. const scale = new Vector3( 1, 1, 1 );
  10126. function onRotationChange() {
  10127. quaternion.setFromEuler( rotation, false );
  10128. }
  10129. function onQuaternionChange() {
  10130. rotation.setFromQuaternion( quaternion, undefined, false );
  10131. }
  10132. rotation._onChange( onRotationChange );
  10133. quaternion._onChange( onQuaternionChange );
  10134. Object.defineProperties( this, {
  10135. /**
  10136. * Represents the object's local position.
  10137. *
  10138. * @name Object3D#position
  10139. * @type {Vector3}
  10140. * @default (0,0,0)
  10141. */
  10142. position: {
  10143. configurable: true,
  10144. enumerable: true,
  10145. value: position
  10146. },
  10147. /**
  10148. * Represents the object's local rotation as Euler angles, in radians.
  10149. *
  10150. * @name Object3D#rotation
  10151. * @type {Euler}
  10152. * @default (0,0,0)
  10153. */
  10154. rotation: {
  10155. configurable: true,
  10156. enumerable: true,
  10157. value: rotation
  10158. },
  10159. /**
  10160. * Represents the object's local rotation as Quaternions.
  10161. *
  10162. * @name Object3D#quaternion
  10163. * @type {Quaternion}
  10164. */
  10165. quaternion: {
  10166. configurable: true,
  10167. enumerable: true,
  10168. value: quaternion
  10169. },
  10170. /**
  10171. * Represents the object's local scale.
  10172. *
  10173. * @name Object3D#scale
  10174. * @type {Vector3}
  10175. * @default (1,1,1)
  10176. */
  10177. scale: {
  10178. configurable: true,
  10179. enumerable: true,
  10180. value: scale
  10181. },
  10182. /**
  10183. * Represents the object's model-view matrix.
  10184. *
  10185. * @name Object3D#modelViewMatrix
  10186. * @type {Matrix4}
  10187. */
  10188. modelViewMatrix: {
  10189. value: new Matrix4()
  10190. },
  10191. /**
  10192. * Represents the object's normal matrix.
  10193. *
  10194. * @name Object3D#normalMatrix
  10195. * @type {Matrix3}
  10196. */
  10197. normalMatrix: {
  10198. value: new Matrix3()
  10199. }
  10200. } );
  10201. /**
  10202. * Represents the object's transformation matrix in local space.
  10203. *
  10204. * @type {Matrix4}
  10205. */
  10206. this.matrix = new Matrix4();
  10207. /**
  10208. * Represents the object's transformation matrix in world space.
  10209. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10210. *
  10211. * @type {Matrix4}
  10212. */
  10213. this.matrixWorld = new Matrix4();
  10214. /**
  10215. * When set to `true`, the engine automatically computes the local matrix from position,
  10216. * rotation and scale every frame.
  10217. *
  10218. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10219. *
  10220. * @type {boolean}
  10221. * @default true
  10222. */
  10223. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10224. /**
  10225. * When set to `true`, the engine automatically computes the world matrix from the current local
  10226. * matrix and the object's transformation hierarchy.
  10227. *
  10228. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10229. *
  10230. * @type {boolean}
  10231. * @default true
  10232. */
  10233. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10234. /**
  10235. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10236. * to `false`.
  10237. *
  10238. * @type {boolean}
  10239. * @default false
  10240. */
  10241. this.matrixWorldNeedsUpdate = false;
  10242. /**
  10243. * The layer membership of the 3D object. The 3D object is only visible if it has
  10244. * at least one layer in common with the camera in use. This property can also be
  10245. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10246. *
  10247. * @type {Layers}
  10248. */
  10249. this.layers = new Layers();
  10250. /**
  10251. * When set to `true`, the 3D object gets rendered.
  10252. *
  10253. * @type {boolean}
  10254. * @default true
  10255. */
  10256. this.visible = true;
  10257. /**
  10258. * When set to `true`, the 3D object gets rendered into shadow maps.
  10259. *
  10260. * @type {boolean}
  10261. * @default false
  10262. */
  10263. this.castShadow = false;
  10264. /**
  10265. * When set to `true`, the 3D object is affected by shadows in the scene.
  10266. *
  10267. * @type {boolean}
  10268. * @default false
  10269. */
  10270. this.receiveShadow = false;
  10271. /**
  10272. * When set to `true`, the 3D object is honored by view frustum culling.
  10273. *
  10274. * @type {boolean}
  10275. * @default true
  10276. */
  10277. this.frustumCulled = true;
  10278. /**
  10279. * This value allows the default rendering order of scene graph objects to be
  10280. * overridden although opaque and transparent objects remain sorted independently.
  10281. * When this property is set for an instance of {@link Group},all descendants
  10282. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10283. * render order.
  10284. *
  10285. * @type {number}
  10286. * @default 0
  10287. */
  10288. this.renderOrder = 0;
  10289. /**
  10290. * An array holding the animation clips of the 3D object.
  10291. *
  10292. * @type {Array<AnimationClip>}
  10293. */
  10294. this.animations = [];
  10295. /**
  10296. * Custom depth material to be used when rendering to the depth map. Can only be used
  10297. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10298. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10299. * material for proper shadows.
  10300. *
  10301. * Only relevant in context of {@link WebGLRenderer}.
  10302. *
  10303. * @type {(Material|undefined)}
  10304. * @default undefined
  10305. */
  10306. this.customDepthMaterial = undefined;
  10307. /**
  10308. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10309. *
  10310. * Only relevant in context of {@link WebGLRenderer}.
  10311. *
  10312. * @type {(Material|undefined)}
  10313. * @default undefined
  10314. */
  10315. this.customDistanceMaterial = undefined;
  10316. /**
  10317. * An object that can be used to store custom data about the 3D object. It
  10318. * should not hold references to functions as these will not be cloned.
  10319. *
  10320. * @type {Object}
  10321. */
  10322. this.userData = {};
  10323. }
  10324. /**
  10325. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10326. *
  10327. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10328. * @param {Object3D} object - The 3D object.
  10329. * @param {Camera} camera - The camera that is used to render the scene.
  10330. * @param {Camera} shadowCamera - The shadow camera.
  10331. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10332. * @param {Material} depthMaterial - The depth material.
  10333. * @param {Object} group - The geometry group data.
  10334. */
  10335. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10336. /**
  10337. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10338. *
  10339. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10340. * @param {Object3D} object - The 3D object.
  10341. * @param {Camera} camera - The camera that is used to render the scene.
  10342. * @param {Camera} shadowCamera - The shadow camera.
  10343. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10344. * @param {Material} depthMaterial - The depth material.
  10345. * @param {Object} group - The geometry group data.
  10346. */
  10347. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10348. /**
  10349. * A callback that is executed immediately before a 3D object is rendered.
  10350. *
  10351. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10352. * @param {Object3D} object - The 3D object.
  10353. * @param {Camera} camera - The camera that is used to render the scene.
  10354. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10355. * @param {Material} material - The 3D object's material.
  10356. * @param {Object} group - The geometry group data.
  10357. */
  10358. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10359. /**
  10360. * A callback that is executed immediately after a 3D object is rendered.
  10361. *
  10362. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10363. * @param {Object3D} object - The 3D object.
  10364. * @param {Camera} camera - The camera that is used to render the scene.
  10365. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10366. * @param {Material} material - The 3D object's material.
  10367. * @param {Object} group - The geometry group data.
  10368. */
  10369. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10370. /**
  10371. * Applies the given transformation matrix to the object and updates the object's position,
  10372. * rotation and scale.
  10373. *
  10374. * @param {Matrix4} matrix - The transformation matrix.
  10375. */
  10376. applyMatrix4( matrix ) {
  10377. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10378. this.matrix.premultiply( matrix );
  10379. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10380. }
  10381. /**
  10382. * Applies a rotation represented by given the quaternion to the 3D object.
  10383. *
  10384. * @param {Quaternion} q - The quaternion.
  10385. * @return {Object3D} A reference to this instance.
  10386. */
  10387. applyQuaternion( q ) {
  10388. this.quaternion.premultiply( q );
  10389. return this;
  10390. }
  10391. /**
  10392. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10393. *
  10394. * @param {Vector3} axis - The (normalized) axis vector.
  10395. * @param {number} angle - The angle in radians.
  10396. */
  10397. setRotationFromAxisAngle( axis, angle ) {
  10398. // assumes axis is normalized
  10399. this.quaternion.setFromAxisAngle( axis, angle );
  10400. }
  10401. /**
  10402. * Sets the given rotation represented as Euler angles to the 3D object.
  10403. *
  10404. * @param {Euler} euler - The Euler angles.
  10405. */
  10406. setRotationFromEuler( euler ) {
  10407. this.quaternion.setFromEuler( euler, true );
  10408. }
  10409. /**
  10410. * Sets the given rotation represented as rotation matrix to the 3D object.
  10411. *
  10412. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10413. * a pure rotation matrix (i.e, unscaled).
  10414. */
  10415. setRotationFromMatrix( m ) {
  10416. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10417. this.quaternion.setFromRotationMatrix( m );
  10418. }
  10419. /**
  10420. * Sets the given rotation represented as a Quaternion to the 3D object.
  10421. *
  10422. * @param {Quaternion} q - The Quaternion
  10423. */
  10424. setRotationFromQuaternion( q ) {
  10425. // assumes q is normalized
  10426. this.quaternion.copy( q );
  10427. }
  10428. /**
  10429. * Rotates the 3D object along an axis in local space.
  10430. *
  10431. * @param {Vector3} axis - The (normalized) axis vector.
  10432. * @param {number} angle - The angle in radians.
  10433. * @return {Object3D} A reference to this instance.
  10434. */
  10435. rotateOnAxis( axis, angle ) {
  10436. // rotate object on axis in object space
  10437. // axis is assumed to be normalized
  10438. _q1.setFromAxisAngle( axis, angle );
  10439. this.quaternion.multiply( _q1 );
  10440. return this;
  10441. }
  10442. /**
  10443. * Rotates the 3D object along an axis in world space.
  10444. *
  10445. * @param {Vector3} axis - The (normalized) axis vector.
  10446. * @param {number} angle - The angle in radians.
  10447. * @return {Object3D} A reference to this instance.
  10448. */
  10449. rotateOnWorldAxis( axis, angle ) {
  10450. // rotate object on axis in world space
  10451. // axis is assumed to be normalized
  10452. // method assumes no rotated parent
  10453. _q1.setFromAxisAngle( axis, angle );
  10454. this.quaternion.premultiply( _q1 );
  10455. return this;
  10456. }
  10457. /**
  10458. * Rotates the 3D object around its X axis in local space.
  10459. *
  10460. * @param {number} angle - The angle in radians.
  10461. * @return {Object3D} A reference to this instance.
  10462. */
  10463. rotateX( angle ) {
  10464. return this.rotateOnAxis( _xAxis, angle );
  10465. }
  10466. /**
  10467. * Rotates the 3D object around its Y axis in local space.
  10468. *
  10469. * @param {number} angle - The angle in radians.
  10470. * @return {Object3D} A reference to this instance.
  10471. */
  10472. rotateY( angle ) {
  10473. return this.rotateOnAxis( _yAxis, angle );
  10474. }
  10475. /**
  10476. * Rotates the 3D object around its Z axis in local space.
  10477. *
  10478. * @param {number} angle - The angle in radians.
  10479. * @return {Object3D} A reference to this instance.
  10480. */
  10481. rotateZ( angle ) {
  10482. return this.rotateOnAxis( _zAxis, angle );
  10483. }
  10484. /**
  10485. * Translate the 3D object by a distance along the given axis in local space.
  10486. *
  10487. * @param {Vector3} axis - The (normalized) axis vector.
  10488. * @param {number} distance - The distance in world units.
  10489. * @return {Object3D} A reference to this instance.
  10490. */
  10491. translateOnAxis( axis, distance ) {
  10492. // translate object by distance along axis in object space
  10493. // axis is assumed to be normalized
  10494. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10495. this.position.add( _v1$4.multiplyScalar( distance ) );
  10496. return this;
  10497. }
  10498. /**
  10499. * Translate the 3D object by a distance along its X-axis in local space.
  10500. *
  10501. * @param {number} distance - The distance in world units.
  10502. * @return {Object3D} A reference to this instance.
  10503. */
  10504. translateX( distance ) {
  10505. return this.translateOnAxis( _xAxis, distance );
  10506. }
  10507. /**
  10508. * Translate the 3D object by a distance along its Y-axis in local space.
  10509. *
  10510. * @param {number} distance - The distance in world units.
  10511. * @return {Object3D} A reference to this instance.
  10512. */
  10513. translateY( distance ) {
  10514. return this.translateOnAxis( _yAxis, distance );
  10515. }
  10516. /**
  10517. * Translate the 3D object by a distance along its Z-axis in local space.
  10518. *
  10519. * @param {number} distance - The distance in world units.
  10520. * @return {Object3D} A reference to this instance.
  10521. */
  10522. translateZ( distance ) {
  10523. return this.translateOnAxis( _zAxis, distance );
  10524. }
  10525. /**
  10526. * Converts the given vector from this 3D object's local space to world space.
  10527. *
  10528. * @param {Vector3} vector - The vector to convert.
  10529. * @return {Vector3} The converted vector.
  10530. */
  10531. localToWorld( vector ) {
  10532. this.updateWorldMatrix( true, false );
  10533. return vector.applyMatrix4( this.matrixWorld );
  10534. }
  10535. /**
  10536. * Converts the given vector from this 3D object's word space to local space.
  10537. *
  10538. * @param {Vector3} vector - The vector to convert.
  10539. * @return {Vector3} The converted vector.
  10540. */
  10541. worldToLocal( vector ) {
  10542. this.updateWorldMatrix( true, false );
  10543. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10544. }
  10545. /**
  10546. * Rotates the object to face a point in world space.
  10547. *
  10548. * This method does not support objects having non-uniformly-scaled parent(s).
  10549. *
  10550. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10551. * @param {number} [y] - The y coordinate in world space.
  10552. * @param {number} [z] - The z coordinate in world space.
  10553. */
  10554. lookAt( x, y, z ) {
  10555. // This method does not support objects having non-uniformly-scaled parent(s)
  10556. if ( x.isVector3 ) {
  10557. _target.copy( x );
  10558. } else {
  10559. _target.set( x, y, z );
  10560. }
  10561. const parent = this.parent;
  10562. this.updateWorldMatrix( true, false );
  10563. _position$3.setFromMatrixPosition( this.matrixWorld );
  10564. if ( this.isCamera || this.isLight ) {
  10565. _m1$3.lookAt( _position$3, _target, this.up );
  10566. } else {
  10567. _m1$3.lookAt( _target, _position$3, this.up );
  10568. }
  10569. this.quaternion.setFromRotationMatrix( _m1$3 );
  10570. if ( parent ) {
  10571. _m1$3.extractRotation( parent.matrixWorld );
  10572. _q1.setFromRotationMatrix( _m1$3 );
  10573. this.quaternion.premultiply( _q1.invert() );
  10574. }
  10575. }
  10576. /**
  10577. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10578. * objects may be added. Any current parent on an object passed in here will be
  10579. * removed, since an object can have at most one parent.
  10580. *
  10581. * @fires Object3D#added
  10582. * @fires Object3D#childadded
  10583. * @param {Object3D} object - The 3D object to add.
  10584. * @return {Object3D} A reference to this instance.
  10585. */
  10586. add( object ) {
  10587. if ( arguments.length > 1 ) {
  10588. for ( let i = 0; i < arguments.length; i ++ ) {
  10589. this.add( arguments[ i ] );
  10590. }
  10591. return this;
  10592. }
  10593. if ( object === this ) {
  10594. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10595. return this;
  10596. }
  10597. if ( object && object.isObject3D ) {
  10598. object.removeFromParent();
  10599. object.parent = this;
  10600. this.children.push( object );
  10601. object.dispatchEvent( _addedEvent );
  10602. _childaddedEvent.child = object;
  10603. this.dispatchEvent( _childaddedEvent );
  10604. _childaddedEvent.child = null;
  10605. } else {
  10606. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10607. }
  10608. return this;
  10609. }
  10610. /**
  10611. * Removes the given 3D object as child from this 3D object.
  10612. * An arbitrary number of objects may be removed.
  10613. *
  10614. * @fires Object3D#removed
  10615. * @fires Object3D#childremoved
  10616. * @param {Object3D} object - The 3D object to remove.
  10617. * @return {Object3D} A reference to this instance.
  10618. */
  10619. remove( object ) {
  10620. if ( arguments.length > 1 ) {
  10621. for ( let i = 0; i < arguments.length; i ++ ) {
  10622. this.remove( arguments[ i ] );
  10623. }
  10624. return this;
  10625. }
  10626. const index = this.children.indexOf( object );
  10627. if ( index !== -1 ) {
  10628. object.parent = null;
  10629. this.children.splice( index, 1 );
  10630. object.dispatchEvent( _removedEvent );
  10631. _childremovedEvent.child = object;
  10632. this.dispatchEvent( _childremovedEvent );
  10633. _childremovedEvent.child = null;
  10634. }
  10635. return this;
  10636. }
  10637. /**
  10638. * Removes this 3D object from its current parent.
  10639. *
  10640. * @fires Object3D#removed
  10641. * @fires Object3D#childremoved
  10642. * @return {Object3D} A reference to this instance.
  10643. */
  10644. removeFromParent() {
  10645. const parent = this.parent;
  10646. if ( parent !== null ) {
  10647. parent.remove( this );
  10648. }
  10649. return this;
  10650. }
  10651. /**
  10652. * Removes all child objects.
  10653. *
  10654. * @fires Object3D#removed
  10655. * @fires Object3D#childremoved
  10656. * @return {Object3D} A reference to this instance.
  10657. */
  10658. clear() {
  10659. return this.remove( ... this.children );
  10660. }
  10661. /**
  10662. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10663. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10664. *
  10665. * @fires Object3D#added
  10666. * @fires Object3D#childadded
  10667. * @param {Object3D} object - The 3D object to attach.
  10668. * @return {Object3D} A reference to this instance.
  10669. */
  10670. attach( object ) {
  10671. // adds object as a child of this, while maintaining the object's world transform
  10672. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10673. this.updateWorldMatrix( true, false );
  10674. _m1$3.copy( this.matrixWorld ).invert();
  10675. if ( object.parent !== null ) {
  10676. object.parent.updateWorldMatrix( true, false );
  10677. _m1$3.multiply( object.parent.matrixWorld );
  10678. }
  10679. object.applyMatrix4( _m1$3 );
  10680. object.removeFromParent();
  10681. object.parent = this;
  10682. this.children.push( object );
  10683. object.updateWorldMatrix( false, true );
  10684. object.dispatchEvent( _addedEvent );
  10685. _childaddedEvent.child = object;
  10686. this.dispatchEvent( _childaddedEvent );
  10687. _childaddedEvent.child = null;
  10688. return this;
  10689. }
  10690. /**
  10691. * Searches through the 3D object and its children, starting with the 3D object
  10692. * itself, and returns the first with a matching ID.
  10693. *
  10694. * @param {number} id - The id.
  10695. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10696. */
  10697. getObjectById( id ) {
  10698. return this.getObjectByProperty( 'id', id );
  10699. }
  10700. /**
  10701. * Searches through the 3D object and its children, starting with the 3D object
  10702. * itself, and returns the first with a matching name.
  10703. *
  10704. * @param {string} name - The name.
  10705. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10706. */
  10707. getObjectByName( name ) {
  10708. return this.getObjectByProperty( 'name', name );
  10709. }
  10710. /**
  10711. * Searches through the 3D object and its children, starting with the 3D object
  10712. * itself, and returns the first with a matching property value.
  10713. *
  10714. * @param {string} name - The name of the property.
  10715. * @param {any} value - The value.
  10716. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10717. */
  10718. getObjectByProperty( name, value ) {
  10719. if ( this[ name ] === value ) return this;
  10720. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10721. const child = this.children[ i ];
  10722. const object = child.getObjectByProperty( name, value );
  10723. if ( object !== undefined ) {
  10724. return object;
  10725. }
  10726. }
  10727. return undefined;
  10728. }
  10729. /**
  10730. * Searches through the 3D object and its children, starting with the 3D object
  10731. * itself, and returns all 3D objects with a matching property value.
  10732. *
  10733. * @param {string} name - The name of the property.
  10734. * @param {any} value - The value.
  10735. * @param {Array<Object3D>} result - The method stores the result in this array.
  10736. * @return {Array<Object3D>} The found 3D objects.
  10737. */
  10738. getObjectsByProperty( name, value, result = [] ) {
  10739. if ( this[ name ] === value ) result.push( this );
  10740. const children = this.children;
  10741. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10742. children[ i ].getObjectsByProperty( name, value, result );
  10743. }
  10744. return result;
  10745. }
  10746. /**
  10747. * Returns a vector representing the position of the 3D object in world space.
  10748. *
  10749. * @param {Vector3} target - The target vector the result is stored to.
  10750. * @return {Vector3} The 3D object's position in world space.
  10751. */
  10752. getWorldPosition( target ) {
  10753. this.updateWorldMatrix( true, false );
  10754. return target.setFromMatrixPosition( this.matrixWorld );
  10755. }
  10756. /**
  10757. * Returns a Quaternion representing the position of the 3D object in world space.
  10758. *
  10759. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10760. * @return {Quaternion} The 3D object's rotation in world space.
  10761. */
  10762. getWorldQuaternion( target ) {
  10763. this.updateWorldMatrix( true, false );
  10764. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10765. return target;
  10766. }
  10767. /**
  10768. * Returns a vector representing the scale of the 3D object in world space.
  10769. *
  10770. * @param {Vector3} target - The target vector the result is stored to.
  10771. * @return {Vector3} The 3D object's scale in world space.
  10772. */
  10773. getWorldScale( target ) {
  10774. this.updateWorldMatrix( true, false );
  10775. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10776. return target;
  10777. }
  10778. /**
  10779. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10780. *
  10781. * @param {Vector3} target - The target vector the result is stored to.
  10782. * @return {Vector3} The 3D object's direction in world space.
  10783. */
  10784. getWorldDirection( target ) {
  10785. this.updateWorldMatrix( true, false );
  10786. const e = this.matrixWorld.elements;
  10787. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10788. }
  10789. /**
  10790. * Abstract method to get intersections between a casted ray and this
  10791. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10792. * implement this method in order to use raycasting.
  10793. *
  10794. * @abstract
  10795. * @param {Raycaster} raycaster - The raycaster.
  10796. * @param {Array<Object>} intersects - An array holding the result of the method.
  10797. */
  10798. raycast( /* raycaster, intersects */ ) {}
  10799. /**
  10800. * Executes the callback on this 3D object and all descendants.
  10801. *
  10802. * Note: Modifying the scene graph inside the callback is discouraged.
  10803. *
  10804. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10805. */
  10806. traverse( callback ) {
  10807. callback( this );
  10808. const children = this.children;
  10809. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10810. children[ i ].traverse( callback );
  10811. }
  10812. }
  10813. /**
  10814. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10815. * Descendants of invisible 3D objects are not traversed.
  10816. *
  10817. * Note: Modifying the scene graph inside the callback is discouraged.
  10818. *
  10819. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10820. */
  10821. traverseVisible( callback ) {
  10822. if ( this.visible === false ) return;
  10823. callback( this );
  10824. const children = this.children;
  10825. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10826. children[ i ].traverseVisible( callback );
  10827. }
  10828. }
  10829. /**
  10830. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10831. *
  10832. * Note: Modifying the scene graph inside the callback is discouraged.
  10833. *
  10834. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10835. */
  10836. traverseAncestors( callback ) {
  10837. const parent = this.parent;
  10838. if ( parent !== null ) {
  10839. callback( parent );
  10840. parent.traverseAncestors( callback );
  10841. }
  10842. }
  10843. /**
  10844. * Updates the transformation matrix in local space by computing it from the current
  10845. * position, rotation and scale values.
  10846. */
  10847. updateMatrix() {
  10848. this.matrix.compose( this.position, this.quaternion, this.scale );
  10849. this.matrixWorldNeedsUpdate = true;
  10850. }
  10851. /**
  10852. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10853. *
  10854. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10855. * local space. The computation of the local and world matrix can be controlled with the
  10856. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10857. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10858. *
  10859. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10860. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10861. */
  10862. updateMatrixWorld( force ) {
  10863. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10864. if ( this.matrixWorldNeedsUpdate || force ) {
  10865. if ( this.matrixWorldAutoUpdate === true ) {
  10866. if ( this.parent === null ) {
  10867. this.matrixWorld.copy( this.matrix );
  10868. } else {
  10869. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10870. }
  10871. }
  10872. this.matrixWorldNeedsUpdate = false;
  10873. force = true;
  10874. }
  10875. // make sure descendants are updated if required
  10876. const children = this.children;
  10877. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10878. const child = children[ i ];
  10879. child.updateMatrixWorld( force );
  10880. }
  10881. }
  10882. /**
  10883. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10884. * update of ancestor and descendant nodes.
  10885. *
  10886. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10887. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10888. */
  10889. updateWorldMatrix( updateParents, updateChildren ) {
  10890. const parent = this.parent;
  10891. if ( updateParents === true && parent !== null ) {
  10892. parent.updateWorldMatrix( true, false );
  10893. }
  10894. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10895. if ( this.matrixWorldAutoUpdate === true ) {
  10896. if ( this.parent === null ) {
  10897. this.matrixWorld.copy( this.matrix );
  10898. } else {
  10899. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10900. }
  10901. }
  10902. // make sure descendants are updated
  10903. if ( updateChildren === true ) {
  10904. const children = this.children;
  10905. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10906. const child = children[ i ];
  10907. child.updateWorldMatrix( false, true );
  10908. }
  10909. }
  10910. }
  10911. /**
  10912. * Serializes the 3D object into JSON.
  10913. *
  10914. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10915. * @return {Object} A JSON object representing the serialized 3D object.
  10916. * @see {@link ObjectLoader#parse}
  10917. */
  10918. toJSON( meta ) {
  10919. // meta is a string when called from JSON.stringify
  10920. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10921. const output = {};
  10922. // meta is a hash used to collect geometries, materials.
  10923. // not providing it implies that this is the root object
  10924. // being serialized.
  10925. if ( isRootObject ) {
  10926. // initialize meta obj
  10927. meta = {
  10928. geometries: {},
  10929. materials: {},
  10930. textures: {},
  10931. images: {},
  10932. shapes: {},
  10933. skeletons: {},
  10934. animations: {},
  10935. nodes: {}
  10936. };
  10937. output.metadata = {
  10938. version: 4.7,
  10939. type: 'Object',
  10940. generator: 'Object3D.toJSON'
  10941. };
  10942. }
  10943. // standard Object3D serialization
  10944. const object = {};
  10945. object.uuid = this.uuid;
  10946. object.type = this.type;
  10947. if ( this.name !== '' ) object.name = this.name;
  10948. if ( this.castShadow === true ) object.castShadow = true;
  10949. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10950. if ( this.visible === false ) object.visible = false;
  10951. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10952. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10953. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10954. object.layers = this.layers.mask;
  10955. object.matrix = this.matrix.toArray();
  10956. object.up = this.up.toArray();
  10957. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10958. // object specific properties
  10959. if ( this.isInstancedMesh ) {
  10960. object.type = 'InstancedMesh';
  10961. object.count = this.count;
  10962. object.instanceMatrix = this.instanceMatrix.toJSON();
  10963. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10964. }
  10965. if ( this.isBatchedMesh ) {
  10966. object.type = 'BatchedMesh';
  10967. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  10968. object.sortObjects = this.sortObjects;
  10969. object.drawRanges = this._drawRanges;
  10970. object.reservedRanges = this._reservedRanges;
  10971. object.geometryInfo = this._geometryInfo.map( info => ( {
  10972. ...info,
  10973. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  10974. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  10975. } ) );
  10976. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  10977. object.availableInstanceIds = this._availableInstanceIds.slice();
  10978. object.availableGeometryIds = this._availableGeometryIds.slice();
  10979. object.nextIndexStart = this._nextIndexStart;
  10980. object.nextVertexStart = this._nextVertexStart;
  10981. object.geometryCount = this._geometryCount;
  10982. object.maxInstanceCount = this._maxInstanceCount;
  10983. object.maxVertexCount = this._maxVertexCount;
  10984. object.maxIndexCount = this._maxIndexCount;
  10985. object.geometryInitialized = this._geometryInitialized;
  10986. object.matricesTexture = this._matricesTexture.toJSON( meta );
  10987. object.indirectTexture = this._indirectTexture.toJSON( meta );
  10988. if ( this._colorsTexture !== null ) {
  10989. object.colorsTexture = this._colorsTexture.toJSON( meta );
  10990. }
  10991. if ( this.boundingSphere !== null ) {
  10992. object.boundingSphere = this.boundingSphere.toJSON();
  10993. }
  10994. if ( this.boundingBox !== null ) {
  10995. object.boundingBox = this.boundingBox.toJSON();
  10996. }
  10997. }
  10998. //
  10999. function serialize( library, element ) {
  11000. if ( library[ element.uuid ] === undefined ) {
  11001. library[ element.uuid ] = element.toJSON( meta );
  11002. }
  11003. return element.uuid;
  11004. }
  11005. if ( this.isScene ) {
  11006. if ( this.background ) {
  11007. if ( this.background.isColor ) {
  11008. object.background = this.background.toJSON();
  11009. } else if ( this.background.isTexture ) {
  11010. object.background = this.background.toJSON( meta ).uuid;
  11011. }
  11012. }
  11013. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11014. object.environment = this.environment.toJSON( meta ).uuid;
  11015. }
  11016. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11017. object.geometry = serialize( meta.geometries, this.geometry );
  11018. const parameters = this.geometry.parameters;
  11019. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11020. const shapes = parameters.shapes;
  11021. if ( Array.isArray( shapes ) ) {
  11022. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11023. const shape = shapes[ i ];
  11024. serialize( meta.shapes, shape );
  11025. }
  11026. } else {
  11027. serialize( meta.shapes, shapes );
  11028. }
  11029. }
  11030. }
  11031. if ( this.isSkinnedMesh ) {
  11032. object.bindMode = this.bindMode;
  11033. object.bindMatrix = this.bindMatrix.toArray();
  11034. if ( this.skeleton !== undefined ) {
  11035. serialize( meta.skeletons, this.skeleton );
  11036. object.skeleton = this.skeleton.uuid;
  11037. }
  11038. }
  11039. if ( this.material !== undefined ) {
  11040. if ( Array.isArray( this.material ) ) {
  11041. const uuids = [];
  11042. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11043. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11044. }
  11045. object.material = uuids;
  11046. } else {
  11047. object.material = serialize( meta.materials, this.material );
  11048. }
  11049. }
  11050. //
  11051. if ( this.children.length > 0 ) {
  11052. object.children = [];
  11053. for ( let i = 0; i < this.children.length; i ++ ) {
  11054. object.children.push( this.children[ i ].toJSON( meta ).object );
  11055. }
  11056. }
  11057. //
  11058. if ( this.animations.length > 0 ) {
  11059. object.animations = [];
  11060. for ( let i = 0; i < this.animations.length; i ++ ) {
  11061. const animation = this.animations[ i ];
  11062. object.animations.push( serialize( meta.animations, animation ) );
  11063. }
  11064. }
  11065. if ( isRootObject ) {
  11066. const geometries = extractFromCache( meta.geometries );
  11067. const materials = extractFromCache( meta.materials );
  11068. const textures = extractFromCache( meta.textures );
  11069. const images = extractFromCache( meta.images );
  11070. const shapes = extractFromCache( meta.shapes );
  11071. const skeletons = extractFromCache( meta.skeletons );
  11072. const animations = extractFromCache( meta.animations );
  11073. const nodes = extractFromCache( meta.nodes );
  11074. if ( geometries.length > 0 ) output.geometries = geometries;
  11075. if ( materials.length > 0 ) output.materials = materials;
  11076. if ( textures.length > 0 ) output.textures = textures;
  11077. if ( images.length > 0 ) output.images = images;
  11078. if ( shapes.length > 0 ) output.shapes = shapes;
  11079. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11080. if ( animations.length > 0 ) output.animations = animations;
  11081. if ( nodes.length > 0 ) output.nodes = nodes;
  11082. }
  11083. output.object = object;
  11084. return output;
  11085. // extract data from the cache hash
  11086. // remove metadata on each item
  11087. // and return as array
  11088. function extractFromCache( cache ) {
  11089. const values = [];
  11090. for ( const key in cache ) {
  11091. const data = cache[ key ];
  11092. delete data.metadata;
  11093. values.push( data );
  11094. }
  11095. return values;
  11096. }
  11097. }
  11098. /**
  11099. * Returns a new 3D object with copied values from this instance.
  11100. *
  11101. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11102. * @return {Object3D} A clone of this instance.
  11103. */
  11104. clone( recursive ) {
  11105. return new this.constructor().copy( this, recursive );
  11106. }
  11107. /**
  11108. * Copies the values of the given 3D object to this instance.
  11109. *
  11110. * @param {Object3D} source - The 3D object to copy.
  11111. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11112. * @return {Object3D} A reference to this instance.
  11113. */
  11114. copy( source, recursive = true ) {
  11115. this.name = source.name;
  11116. this.up.copy( source.up );
  11117. this.position.copy( source.position );
  11118. this.rotation.order = source.rotation.order;
  11119. this.quaternion.copy( source.quaternion );
  11120. this.scale.copy( source.scale );
  11121. this.matrix.copy( source.matrix );
  11122. this.matrixWorld.copy( source.matrixWorld );
  11123. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11124. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11125. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11126. this.layers.mask = source.layers.mask;
  11127. this.visible = source.visible;
  11128. this.castShadow = source.castShadow;
  11129. this.receiveShadow = source.receiveShadow;
  11130. this.frustumCulled = source.frustumCulled;
  11131. this.renderOrder = source.renderOrder;
  11132. this.animations = source.animations.slice();
  11133. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11134. if ( recursive === true ) {
  11135. for ( let i = 0; i < source.children.length; i ++ ) {
  11136. const child = source.children[ i ];
  11137. this.add( child.clone() );
  11138. }
  11139. }
  11140. return this;
  11141. }
  11142. }
  11143. /**
  11144. * The default up direction for objects, also used as the default
  11145. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11146. *
  11147. * @static
  11148. * @type {Vector3}
  11149. * @default (0,1,0)
  11150. */
  11151. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11152. /**
  11153. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11154. * newly created 3D objects.
  11155. *
  11156. * @static
  11157. * @type {boolean}
  11158. * @default true
  11159. */
  11160. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11161. /**
  11162. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11163. * newly created 3D objects.
  11164. *
  11165. * @static
  11166. * @type {boolean}
  11167. * @default true
  11168. */
  11169. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11170. const _v0$2 = /*@__PURE__*/ new Vector3();
  11171. const _v1$3 = /*@__PURE__*/ new Vector3();
  11172. const _v2$2 = /*@__PURE__*/ new Vector3();
  11173. const _v3$2 = /*@__PURE__*/ new Vector3();
  11174. const _vab = /*@__PURE__*/ new Vector3();
  11175. const _vac = /*@__PURE__*/ new Vector3();
  11176. const _vbc = /*@__PURE__*/ new Vector3();
  11177. const _vap = /*@__PURE__*/ new Vector3();
  11178. const _vbp = /*@__PURE__*/ new Vector3();
  11179. const _vcp = /*@__PURE__*/ new Vector3();
  11180. const _v40 = /*@__PURE__*/ new Vector4();
  11181. const _v41 = /*@__PURE__*/ new Vector4();
  11182. const _v42 = /*@__PURE__*/ new Vector4();
  11183. /**
  11184. * A geometric triangle as defined by three vectors representing its three corners.
  11185. */
  11186. class Triangle {
  11187. /**
  11188. * Constructs a new triangle.
  11189. *
  11190. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11191. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11192. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11193. */
  11194. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11195. /**
  11196. * The first corner of the triangle.
  11197. *
  11198. * @type {Vector3}
  11199. */
  11200. this.a = a;
  11201. /**
  11202. * The second corner of the triangle.
  11203. *
  11204. * @type {Vector3}
  11205. */
  11206. this.b = b;
  11207. /**
  11208. * The third corner of the triangle.
  11209. *
  11210. * @type {Vector3}
  11211. */
  11212. this.c = c;
  11213. }
  11214. /**
  11215. * Computes the normal vector of a triangle.
  11216. *
  11217. * @param {Vector3} a - The first corner of the triangle.
  11218. * @param {Vector3} b - The second corner of the triangle.
  11219. * @param {Vector3} c - The third corner of the triangle.
  11220. * @param {Vector3} target - The target vector that is used to store the method's result.
  11221. * @return {Vector3} The triangle's normal.
  11222. */
  11223. static getNormal( a, b, c, target ) {
  11224. target.subVectors( c, b );
  11225. _v0$2.subVectors( a, b );
  11226. target.cross( _v0$2 );
  11227. const targetLengthSq = target.lengthSq();
  11228. if ( targetLengthSq > 0 ) {
  11229. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11230. }
  11231. return target.set( 0, 0, 0 );
  11232. }
  11233. /**
  11234. * Computes a barycentric coordinates from the given vector.
  11235. * Returns `null` if the triangle is degenerate.
  11236. *
  11237. * @param {Vector3} point - A point in 3D space.
  11238. * @param {Vector3} a - The first corner of the triangle.
  11239. * @param {Vector3} b - The second corner of the triangle.
  11240. * @param {Vector3} c - The third corner of the triangle.
  11241. * @param {Vector3} target - The target vector that is used to store the method's result.
  11242. * @return {?Vector3} The barycentric coordinates for the given point
  11243. */
  11244. static getBarycoord( point, a, b, c, target ) {
  11245. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11246. _v0$2.subVectors( c, a );
  11247. _v1$3.subVectors( b, a );
  11248. _v2$2.subVectors( point, a );
  11249. const dot00 = _v0$2.dot( _v0$2 );
  11250. const dot01 = _v0$2.dot( _v1$3 );
  11251. const dot02 = _v0$2.dot( _v2$2 );
  11252. const dot11 = _v1$3.dot( _v1$3 );
  11253. const dot12 = _v1$3.dot( _v2$2 );
  11254. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11255. // collinear or singular triangle
  11256. if ( denom === 0 ) {
  11257. target.set( 0, 0, 0 );
  11258. return null;
  11259. }
  11260. const invDenom = 1 / denom;
  11261. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11262. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11263. // barycentric coordinates must always sum to 1
  11264. return target.set( 1 - u - v, v, u );
  11265. }
  11266. /**
  11267. * Returns `true` if the given point, when projected onto the plane of the
  11268. * triangle, lies within the triangle.
  11269. *
  11270. * @param {Vector3} point - The point in 3D space to test.
  11271. * @param {Vector3} a - The first corner of the triangle.
  11272. * @param {Vector3} b - The second corner of the triangle.
  11273. * @param {Vector3} c - The third corner of the triangle.
  11274. * @return {boolean} Whether the given point, when projected onto the plane of the
  11275. * triangle, lies within the triangle or not.
  11276. */
  11277. static containsPoint( point, a, b, c ) {
  11278. // if the triangle is degenerate then we can't contain a point
  11279. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11280. return false;
  11281. }
  11282. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11283. }
  11284. /**
  11285. * Computes the value barycentrically interpolated for the given point on the
  11286. * triangle. Returns `null` if the triangle is degenerate.
  11287. *
  11288. * @param {Vector3} point - Position of interpolated point.
  11289. * @param {Vector3} p1 - The first corner of the triangle.
  11290. * @param {Vector3} p2 - The second corner of the triangle.
  11291. * @param {Vector3} p3 - The third corner of the triangle.
  11292. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11293. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11294. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11295. * @param {Vector3} target - The target vector that is used to store the method's result.
  11296. * @return {?Vector3} The interpolated value.
  11297. */
  11298. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11299. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11300. target.x = 0;
  11301. target.y = 0;
  11302. if ( 'z' in target ) target.z = 0;
  11303. if ( 'w' in target ) target.w = 0;
  11304. return null;
  11305. }
  11306. target.setScalar( 0 );
  11307. target.addScaledVector( v1, _v3$2.x );
  11308. target.addScaledVector( v2, _v3$2.y );
  11309. target.addScaledVector( v3, _v3$2.z );
  11310. return target;
  11311. }
  11312. /**
  11313. * Computes the value barycentrically interpolated for the given attribute and indices.
  11314. *
  11315. * @param {BufferAttribute} attr - The attribute to interpolate.
  11316. * @param {number} i1 - Index of first vertex.
  11317. * @param {number} i2 - Index of second vertex.
  11318. * @param {number} i3 - Index of third vertex.
  11319. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11320. * @param {Vector3} target - The target vector that is used to store the method's result.
  11321. * @return {Vector3} The interpolated attribute value.
  11322. */
  11323. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11324. _v40.setScalar( 0 );
  11325. _v41.setScalar( 0 );
  11326. _v42.setScalar( 0 );
  11327. _v40.fromBufferAttribute( attr, i1 );
  11328. _v41.fromBufferAttribute( attr, i2 );
  11329. _v42.fromBufferAttribute( attr, i3 );
  11330. target.setScalar( 0 );
  11331. target.addScaledVector( _v40, barycoord.x );
  11332. target.addScaledVector( _v41, barycoord.y );
  11333. target.addScaledVector( _v42, barycoord.z );
  11334. return target;
  11335. }
  11336. /**
  11337. * Returns `true` if the triangle is oriented towards the given direction.
  11338. *
  11339. * @param {Vector3} a - The first corner of the triangle.
  11340. * @param {Vector3} b - The second corner of the triangle.
  11341. * @param {Vector3} c - The third corner of the triangle.
  11342. * @param {Vector3} direction - The (normalized) direction vector.
  11343. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11344. */
  11345. static isFrontFacing( a, b, c, direction ) {
  11346. _v0$2.subVectors( c, b );
  11347. _v1$3.subVectors( a, b );
  11348. // strictly front facing
  11349. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11350. }
  11351. /**
  11352. * Sets the triangle's vertices by copying the given values.
  11353. *
  11354. * @param {Vector3} a - The first corner of the triangle.
  11355. * @param {Vector3} b - The second corner of the triangle.
  11356. * @param {Vector3} c - The third corner of the triangle.
  11357. * @return {Triangle} A reference to this triangle.
  11358. */
  11359. set( a, b, c ) {
  11360. this.a.copy( a );
  11361. this.b.copy( b );
  11362. this.c.copy( c );
  11363. return this;
  11364. }
  11365. /**
  11366. * Sets the triangle's vertices by copying the given array values.
  11367. *
  11368. * @param {Array<Vector3>} points - An array with 3D points.
  11369. * @param {number} i0 - The array index representing the first corner of the triangle.
  11370. * @param {number} i1 - The array index representing the second corner of the triangle.
  11371. * @param {number} i2 - The array index representing the third corner of the triangle.
  11372. * @return {Triangle} A reference to this triangle.
  11373. */
  11374. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11375. this.a.copy( points[ i0 ] );
  11376. this.b.copy( points[ i1 ] );
  11377. this.c.copy( points[ i2 ] );
  11378. return this;
  11379. }
  11380. /**
  11381. * Sets the triangle's vertices by copying the given attribute values.
  11382. *
  11383. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11384. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11385. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11386. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11387. * @return {Triangle} A reference to this triangle.
  11388. */
  11389. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11390. this.a.fromBufferAttribute( attribute, i0 );
  11391. this.b.fromBufferAttribute( attribute, i1 );
  11392. this.c.fromBufferAttribute( attribute, i2 );
  11393. return this;
  11394. }
  11395. /**
  11396. * Returns a new triangle with copied values from this instance.
  11397. *
  11398. * @return {Triangle} A clone of this instance.
  11399. */
  11400. clone() {
  11401. return new this.constructor().copy( this );
  11402. }
  11403. /**
  11404. * Copies the values of the given triangle to this instance.
  11405. *
  11406. * @param {Triangle} triangle - The triangle to copy.
  11407. * @return {Triangle} A reference to this triangle.
  11408. */
  11409. copy( triangle ) {
  11410. this.a.copy( triangle.a );
  11411. this.b.copy( triangle.b );
  11412. this.c.copy( triangle.c );
  11413. return this;
  11414. }
  11415. /**
  11416. * Computes the area of the triangle.
  11417. *
  11418. * @return {number} The triangle's area.
  11419. */
  11420. getArea() {
  11421. _v0$2.subVectors( this.c, this.b );
  11422. _v1$3.subVectors( this.a, this.b );
  11423. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11424. }
  11425. /**
  11426. * Computes the midpoint of the triangle.
  11427. *
  11428. * @param {Vector3} target - The target vector that is used to store the method's result.
  11429. * @return {Vector3} The triangle's midpoint.
  11430. */
  11431. getMidpoint( target ) {
  11432. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11433. }
  11434. /**
  11435. * Computes the normal of the triangle.
  11436. *
  11437. * @param {Vector3} target - The target vector that is used to store the method's result.
  11438. * @return {Vector3} The triangle's normal.
  11439. */
  11440. getNormal( target ) {
  11441. return Triangle.getNormal( this.a, this.b, this.c, target );
  11442. }
  11443. /**
  11444. * Computes a plane the triangle lies within.
  11445. *
  11446. * @param {Plane} target - The target vector that is used to store the method's result.
  11447. * @return {Plane} The plane the triangle lies within.
  11448. */
  11449. getPlane( target ) {
  11450. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11451. }
  11452. /**
  11453. * Computes a barycentric coordinates from the given vector.
  11454. * Returns `null` if the triangle is degenerate.
  11455. *
  11456. * @param {Vector3} point - A point in 3D space.
  11457. * @param {Vector3} target - The target vector that is used to store the method's result.
  11458. * @return {?Vector3} The barycentric coordinates for the given point
  11459. */
  11460. getBarycoord( point, target ) {
  11461. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11462. }
  11463. /**
  11464. * Computes the value barycentrically interpolated for the given point on the
  11465. * triangle. Returns `null` if the triangle is degenerate.
  11466. *
  11467. * @param {Vector3} point - Position of interpolated point.
  11468. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11469. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11470. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11471. * @param {Vector3} target - The target vector that is used to store the method's result.
  11472. * @return {?Vector3} The interpolated value.
  11473. */
  11474. getInterpolation( point, v1, v2, v3, target ) {
  11475. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11476. }
  11477. /**
  11478. * Returns `true` if the given point, when projected onto the plane of the
  11479. * triangle, lies within the triangle.
  11480. *
  11481. * @param {Vector3} point - The point in 3D space to test.
  11482. * @return {boolean} Whether the given point, when projected onto the plane of the
  11483. * triangle, lies within the triangle or not.
  11484. */
  11485. containsPoint( point ) {
  11486. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11487. }
  11488. /**
  11489. * Returns `true` if the triangle is oriented towards the given direction.
  11490. *
  11491. * @param {Vector3} direction - The (normalized) direction vector.
  11492. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11493. */
  11494. isFrontFacing( direction ) {
  11495. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11496. }
  11497. /**
  11498. * Returns `true` if this triangle intersects with the given box.
  11499. *
  11500. * @param {Box3} box - The box to intersect.
  11501. * @return {boolean} Whether this triangle intersects with the given box or not.
  11502. */
  11503. intersectsBox( box ) {
  11504. return box.intersectsTriangle( this );
  11505. }
  11506. /**
  11507. * Returns the closest point on the triangle to the given point.
  11508. *
  11509. * @param {Vector3} p - The point to compute the closest point for.
  11510. * @param {Vector3} target - The target vector that is used to store the method's result.
  11511. * @return {Vector3} The closest point on the triangle.
  11512. */
  11513. closestPointToPoint( p, target ) {
  11514. const a = this.a, b = this.b, c = this.c;
  11515. let v, w;
  11516. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11517. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11518. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11519. // basically, we're distinguishing which of the voronoi regions of the triangle
  11520. // the point lies in with the minimum amount of redundant computation.
  11521. _vab.subVectors( b, a );
  11522. _vac.subVectors( c, a );
  11523. _vap.subVectors( p, a );
  11524. const d1 = _vab.dot( _vap );
  11525. const d2 = _vac.dot( _vap );
  11526. if ( d1 <= 0 && d2 <= 0 ) {
  11527. // vertex region of A; barycentric coords (1, 0, 0)
  11528. return target.copy( a );
  11529. }
  11530. _vbp.subVectors( p, b );
  11531. const d3 = _vab.dot( _vbp );
  11532. const d4 = _vac.dot( _vbp );
  11533. if ( d3 >= 0 && d4 <= d3 ) {
  11534. // vertex region of B; barycentric coords (0, 1, 0)
  11535. return target.copy( b );
  11536. }
  11537. const vc = d1 * d4 - d3 * d2;
  11538. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11539. v = d1 / ( d1 - d3 );
  11540. // edge region of AB; barycentric coords (1-v, v, 0)
  11541. return target.copy( a ).addScaledVector( _vab, v );
  11542. }
  11543. _vcp.subVectors( p, c );
  11544. const d5 = _vab.dot( _vcp );
  11545. const d6 = _vac.dot( _vcp );
  11546. if ( d6 >= 0 && d5 <= d6 ) {
  11547. // vertex region of C; barycentric coords (0, 0, 1)
  11548. return target.copy( c );
  11549. }
  11550. const vb = d5 * d2 - d1 * d6;
  11551. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11552. w = d2 / ( d2 - d6 );
  11553. // edge region of AC; barycentric coords (1-w, 0, w)
  11554. return target.copy( a ).addScaledVector( _vac, w );
  11555. }
  11556. const va = d3 * d6 - d5 * d4;
  11557. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11558. _vbc.subVectors( c, b );
  11559. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11560. // edge region of BC; barycentric coords (0, 1-w, w)
  11561. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11562. }
  11563. // face region
  11564. const denom = 1 / ( va + vb + vc );
  11565. // u = va * denom
  11566. v = vb * denom;
  11567. w = vc * denom;
  11568. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11569. }
  11570. /**
  11571. * Returns `true` if this triangle is equal with the given one.
  11572. *
  11573. * @param {Triangle} triangle - The triangle to test for equality.
  11574. * @return {boolean} Whether this triangle is equal with the given one.
  11575. */
  11576. equals( triangle ) {
  11577. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11578. }
  11579. }
  11580. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11581. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11582. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11583. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11584. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11585. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11586. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11587. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11588. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11589. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11590. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11591. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11592. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11593. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11594. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11595. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11596. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11597. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11598. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11599. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11600. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11601. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11602. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11603. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11604. const _hslA = { h: 0, s: 0, l: 0 };
  11605. const _hslB = { h: 0, s: 0, l: 0 };
  11606. function hue2rgb( p, q, t ) {
  11607. if ( t < 0 ) t += 1;
  11608. if ( t > 1 ) t -= 1;
  11609. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11610. if ( t < 1 / 2 ) return q;
  11611. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11612. return p;
  11613. }
  11614. /**
  11615. * A Color instance is represented by RGB components in the linear <i>working
  11616. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11617. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11618. * strings) are converted to the working color space automatically.
  11619. *
  11620. * ```js
  11621. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11622. * const color = new THREE.Color().setHex( 0x112233 );
  11623. * ```
  11624. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11625. * ```js
  11626. * // assumed already LinearSRGBColorSpace; no conversion
  11627. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11628. *
  11629. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11630. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11631. * ```
  11632. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11633. * see <i>Color management</i>. Iterating through a Color instance will yield
  11634. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11635. * in any of the following ways:
  11636. * ```js
  11637. * //empty constructor - will default white
  11638. * const color1 = new THREE.Color();
  11639. *
  11640. * //Hexadecimal color (recommended)
  11641. * const color2 = new THREE.Color( 0xff0000 );
  11642. *
  11643. * //RGB string
  11644. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11645. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11646. *
  11647. * //X11 color name - all 140 color names are supported.
  11648. * //Note the lack of CamelCase in the name
  11649. * const color5 = new THREE.Color( 'skyblue' );
  11650. * //HSL string
  11651. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11652. *
  11653. * //Separate RGB values between 0 and 1
  11654. * const color7 = new THREE.Color( 1, 0, 0 );
  11655. * ```
  11656. */
  11657. class Color {
  11658. /**
  11659. * Constructs a new color.
  11660. *
  11661. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11662. * and that method is used throughout the rest of the documentation.
  11663. *
  11664. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11665. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11666. * @param {number} [g] - The green component.
  11667. * @param {number} [b] - The blue component.
  11668. */
  11669. constructor( r, g, b ) {
  11670. /**
  11671. * This flag can be used for type testing.
  11672. *
  11673. * @type {boolean}
  11674. * @readonly
  11675. * @default true
  11676. */
  11677. this.isColor = true;
  11678. /**
  11679. * The red component.
  11680. *
  11681. * @type {number}
  11682. * @default 1
  11683. */
  11684. this.r = 1;
  11685. /**
  11686. * The green component.
  11687. *
  11688. * @type {number}
  11689. * @default 1
  11690. */
  11691. this.g = 1;
  11692. /**
  11693. * The blue component.
  11694. *
  11695. * @type {number}
  11696. * @default 1
  11697. */
  11698. this.b = 1;
  11699. return this.set( r, g, b );
  11700. }
  11701. /**
  11702. * Sets the colors's components from the given values.
  11703. *
  11704. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11705. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11706. * @param {number} [g] - The green component.
  11707. * @param {number} [b] - The blue component.
  11708. * @return {Color} A reference to this color.
  11709. */
  11710. set( r, g, b ) {
  11711. if ( g === undefined && b === undefined ) {
  11712. // r is THREE.Color, hex or string
  11713. const value = r;
  11714. if ( value && value.isColor ) {
  11715. this.copy( value );
  11716. } else if ( typeof value === 'number' ) {
  11717. this.setHex( value );
  11718. } else if ( typeof value === 'string' ) {
  11719. this.setStyle( value );
  11720. }
  11721. } else {
  11722. this.setRGB( r, g, b );
  11723. }
  11724. return this;
  11725. }
  11726. /**
  11727. * Sets the colors's components to the given scalar value.
  11728. *
  11729. * @param {number} scalar - The scalar value.
  11730. * @return {Color} A reference to this color.
  11731. */
  11732. setScalar( scalar ) {
  11733. this.r = scalar;
  11734. this.g = scalar;
  11735. this.b = scalar;
  11736. return this;
  11737. }
  11738. /**
  11739. * Sets this color from a hexadecimal value.
  11740. *
  11741. * @param {number} hex - The hexadecimal value.
  11742. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11743. * @return {Color} A reference to this color.
  11744. */
  11745. setHex( hex, colorSpace = SRGBColorSpace ) {
  11746. hex = Math.floor( hex );
  11747. this.r = ( hex >> 16 & 255 ) / 255;
  11748. this.g = ( hex >> 8 & 255 ) / 255;
  11749. this.b = ( hex & 255 ) / 255;
  11750. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11751. return this;
  11752. }
  11753. /**
  11754. * Sets this color from RGB values.
  11755. *
  11756. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11757. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11758. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11759. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11760. * @return {Color} A reference to this color.
  11761. */
  11762. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11763. this.r = r;
  11764. this.g = g;
  11765. this.b = b;
  11766. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11767. return this;
  11768. }
  11769. /**
  11770. * Sets this color from RGB values.
  11771. *
  11772. * @param {number} h - Hue value between `0.0` and `1.0`.
  11773. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11774. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11775. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11776. * @return {Color} A reference to this color.
  11777. */
  11778. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11779. // h,s,l ranges are in 0.0 - 1.0
  11780. h = euclideanModulo( h, 1 );
  11781. s = clamp( s, 0, 1 );
  11782. l = clamp( l, 0, 1 );
  11783. if ( s === 0 ) {
  11784. this.r = this.g = this.b = l;
  11785. } else {
  11786. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11787. const q = ( 2 * l ) - p;
  11788. this.r = hue2rgb( q, p, h + 1 / 3 );
  11789. this.g = hue2rgb( q, p, h );
  11790. this.b = hue2rgb( q, p, h - 1 / 3 );
  11791. }
  11792. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11793. return this;
  11794. }
  11795. /**
  11796. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11797. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11798. * any [X11 color name]{@link https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart} -
  11799. * all 140 color names are supported).
  11800. *
  11801. * @param {string} style - Color as a CSS-style string.
  11802. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11803. * @return {Color} A reference to this color.
  11804. */
  11805. setStyle( style, colorSpace = SRGBColorSpace ) {
  11806. function handleAlpha( string ) {
  11807. if ( string === undefined ) return;
  11808. if ( parseFloat( string ) < 1 ) {
  11809. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11810. }
  11811. }
  11812. let m;
  11813. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11814. // rgb / hsl
  11815. let color;
  11816. const name = m[ 1 ];
  11817. const components = m[ 2 ];
  11818. switch ( name ) {
  11819. case 'rgb':
  11820. case 'rgba':
  11821. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11822. // rgb(255,0,0) rgba(255,0,0,0.5)
  11823. handleAlpha( color[ 4 ] );
  11824. return this.setRGB(
  11825. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11826. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11827. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11828. colorSpace
  11829. );
  11830. }
  11831. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11832. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11833. handleAlpha( color[ 4 ] );
  11834. return this.setRGB(
  11835. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11836. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11837. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11838. colorSpace
  11839. );
  11840. }
  11841. break;
  11842. case 'hsl':
  11843. case 'hsla':
  11844. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11845. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11846. handleAlpha( color[ 4 ] );
  11847. return this.setHSL(
  11848. parseFloat( color[ 1 ] ) / 360,
  11849. parseFloat( color[ 2 ] ) / 100,
  11850. parseFloat( color[ 3 ] ) / 100,
  11851. colorSpace
  11852. );
  11853. }
  11854. break;
  11855. default:
  11856. warn( 'Color: Unknown color model ' + style );
  11857. }
  11858. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11859. // hex color
  11860. const hex = m[ 1 ];
  11861. const size = hex.length;
  11862. if ( size === 3 ) {
  11863. // #ff0
  11864. return this.setRGB(
  11865. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11866. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11867. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11868. colorSpace
  11869. );
  11870. } else if ( size === 6 ) {
  11871. // #ff0000
  11872. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11873. } else {
  11874. warn( 'Color: Invalid hex color ' + style );
  11875. }
  11876. } else if ( style && style.length > 0 ) {
  11877. return this.setColorName( style, colorSpace );
  11878. }
  11879. return this;
  11880. }
  11881. /**
  11882. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11883. * you don't need the other CSS-style formats.
  11884. *
  11885. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11886. * ```js
  11887. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11888. * ```
  11889. *
  11890. * @param {string} style - The color name.
  11891. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11892. * @return {Color} A reference to this color.
  11893. */
  11894. setColorName( style, colorSpace = SRGBColorSpace ) {
  11895. // color keywords
  11896. const hex = _colorKeywords[ style.toLowerCase() ];
  11897. if ( hex !== undefined ) {
  11898. // red
  11899. this.setHex( hex, colorSpace );
  11900. } else {
  11901. // unknown color
  11902. warn( 'Color: Unknown color ' + style );
  11903. }
  11904. return this;
  11905. }
  11906. /**
  11907. * Returns a new color with copied values from this instance.
  11908. *
  11909. * @return {Color} A clone of this instance.
  11910. */
  11911. clone() {
  11912. return new this.constructor( this.r, this.g, this.b );
  11913. }
  11914. /**
  11915. * Copies the values of the given color to this instance.
  11916. *
  11917. * @param {Color} color - The color to copy.
  11918. * @return {Color} A reference to this color.
  11919. */
  11920. copy( color ) {
  11921. this.r = color.r;
  11922. this.g = color.g;
  11923. this.b = color.b;
  11924. return this;
  11925. }
  11926. /**
  11927. * Copies the given color into this color, and then converts this color from
  11928. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11929. *
  11930. * @param {Color} color - The color to copy/convert.
  11931. * @return {Color} A reference to this color.
  11932. */
  11933. copySRGBToLinear( color ) {
  11934. this.r = SRGBToLinear( color.r );
  11935. this.g = SRGBToLinear( color.g );
  11936. this.b = SRGBToLinear( color.b );
  11937. return this;
  11938. }
  11939. /**
  11940. * Copies the given color into this color, and then converts this color from
  11941. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11942. *
  11943. * @param {Color} color - The color to copy/convert.
  11944. * @return {Color} A reference to this color.
  11945. */
  11946. copyLinearToSRGB( color ) {
  11947. this.r = LinearToSRGB( color.r );
  11948. this.g = LinearToSRGB( color.g );
  11949. this.b = LinearToSRGB( color.b );
  11950. return this;
  11951. }
  11952. /**
  11953. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11954. *
  11955. * @return {Color} A reference to this color.
  11956. */
  11957. convertSRGBToLinear() {
  11958. this.copySRGBToLinear( this );
  11959. return this;
  11960. }
  11961. /**
  11962. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11963. *
  11964. * @return {Color} A reference to this color.
  11965. */
  11966. convertLinearToSRGB() {
  11967. this.copyLinearToSRGB( this );
  11968. return this;
  11969. }
  11970. /**
  11971. * Returns the hexadecimal value of this color.
  11972. *
  11973. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11974. * @return {number} The hexadecimal value.
  11975. */
  11976. getHex( colorSpace = SRGBColorSpace ) {
  11977. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  11978. 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 ) );
  11979. }
  11980. /**
  11981. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  11982. *
  11983. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11984. * @return {string} The hexadecimal value as a string.
  11985. */
  11986. getHexString( colorSpace = SRGBColorSpace ) {
  11987. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  11988. }
  11989. /**
  11990. * Converts the colors RGB values into the HSL format and stores them into the
  11991. * given target object.
  11992. *
  11993. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  11994. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11995. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  11996. */
  11997. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  11998. // h,s,l ranges are in 0.0 - 1.0
  11999. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12000. const r = _color.r, g = _color.g, b = _color.b;
  12001. const max = Math.max( r, g, b );
  12002. const min = Math.min( r, g, b );
  12003. let hue, saturation;
  12004. const lightness = ( min + max ) / 2.0;
  12005. if ( min === max ) {
  12006. hue = 0;
  12007. saturation = 0;
  12008. } else {
  12009. const delta = max - min;
  12010. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12011. switch ( max ) {
  12012. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12013. case g: hue = ( b - r ) / delta + 2; break;
  12014. case b: hue = ( r - g ) / delta + 4; break;
  12015. }
  12016. hue /= 6;
  12017. }
  12018. target.h = hue;
  12019. target.s = saturation;
  12020. target.l = lightness;
  12021. return target;
  12022. }
  12023. /**
  12024. * Returns the RGB values of this color and stores them into the given target object.
  12025. *
  12026. * @param {Color} target - The target color that is used to store the method's result.
  12027. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12028. * @return {Color} The RGB representation of this color.
  12029. */
  12030. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12031. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12032. target.r = _color.r;
  12033. target.g = _color.g;
  12034. target.b = _color.b;
  12035. return target;
  12036. }
  12037. /**
  12038. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12039. *
  12040. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12041. * @return {string} The CSS representation of this color.
  12042. */
  12043. getStyle( colorSpace = SRGBColorSpace ) {
  12044. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12045. const r = _color.r, g = _color.g, b = _color.b;
  12046. if ( colorSpace !== SRGBColorSpace ) {
  12047. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12048. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12049. }
  12050. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12051. }
  12052. /**
  12053. * Adds the given HSL values to this color's values.
  12054. * Internally, this converts the color's RGB values to HSL, adds HSL
  12055. * and then converts the color back to RGB.
  12056. *
  12057. * @param {number} h - Hue value between `0.0` and `1.0`.
  12058. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12059. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12060. * @return {Color} A reference to this color.
  12061. */
  12062. offsetHSL( h, s, l ) {
  12063. this.getHSL( _hslA );
  12064. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12065. }
  12066. /**
  12067. * Adds the RGB values of the given color to the RGB values of this color.
  12068. *
  12069. * @param {Color} color - The color to add.
  12070. * @return {Color} A reference to this color.
  12071. */
  12072. add( color ) {
  12073. this.r += color.r;
  12074. this.g += color.g;
  12075. this.b += color.b;
  12076. return this;
  12077. }
  12078. /**
  12079. * Adds the RGB values of the given colors and stores the result in this instance.
  12080. *
  12081. * @param {Color} color1 - The first color.
  12082. * @param {Color} color2 - The second color.
  12083. * @return {Color} A reference to this color.
  12084. */
  12085. addColors( color1, color2 ) {
  12086. this.r = color1.r + color2.r;
  12087. this.g = color1.g + color2.g;
  12088. this.b = color1.b + color2.b;
  12089. return this;
  12090. }
  12091. /**
  12092. * Adds the given scalar value to the RGB values of this color.
  12093. *
  12094. * @param {number} s - The scalar to add.
  12095. * @return {Color} A reference to this color.
  12096. */
  12097. addScalar( s ) {
  12098. this.r += s;
  12099. this.g += s;
  12100. this.b += s;
  12101. return this;
  12102. }
  12103. /**
  12104. * Subtracts the RGB values of the given color from the RGB values of this color.
  12105. *
  12106. * @param {Color} color - The color to subtract.
  12107. * @return {Color} A reference to this color.
  12108. */
  12109. sub( color ) {
  12110. this.r = Math.max( 0, this.r - color.r );
  12111. this.g = Math.max( 0, this.g - color.g );
  12112. this.b = Math.max( 0, this.b - color.b );
  12113. return this;
  12114. }
  12115. /**
  12116. * Multiplies the RGB values of the given color with the RGB values of this color.
  12117. *
  12118. * @param {Color} color - The color to multiply.
  12119. * @return {Color} A reference to this color.
  12120. */
  12121. multiply( color ) {
  12122. this.r *= color.r;
  12123. this.g *= color.g;
  12124. this.b *= color.b;
  12125. return this;
  12126. }
  12127. /**
  12128. * Multiplies the given scalar value with the RGB values of this color.
  12129. *
  12130. * @param {number} s - The scalar to multiply.
  12131. * @return {Color} A reference to this color.
  12132. */
  12133. multiplyScalar( s ) {
  12134. this.r *= s;
  12135. this.g *= s;
  12136. this.b *= s;
  12137. return this;
  12138. }
  12139. /**
  12140. * Linearly interpolates this color's RGB values toward the RGB values of the
  12141. * given color. The alpha argument can be thought of as the ratio between
  12142. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12143. *
  12144. * @param {Color} color - The color to converge on.
  12145. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12146. * @return {Color} A reference to this color.
  12147. */
  12148. lerp( color, alpha ) {
  12149. this.r += ( color.r - this.r ) * alpha;
  12150. this.g += ( color.g - this.g ) * alpha;
  12151. this.b += ( color.b - this.b ) * alpha;
  12152. return this;
  12153. }
  12154. /**
  12155. * Linearly interpolates between the given colors and stores the result in this instance.
  12156. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12157. * is the first and `1.0` is the second color.
  12158. *
  12159. * @param {Color} color1 - The first color.
  12160. * @param {Color} color2 - The second color.
  12161. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12162. * @return {Color} A reference to this color.
  12163. */
  12164. lerpColors( color1, color2, alpha ) {
  12165. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12166. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12167. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12168. return this;
  12169. }
  12170. /**
  12171. * Linearly interpolates this color's HSL values toward the HSL values of the
  12172. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12173. * from one color to the other, but instead going through all the hues in between
  12174. * those two colors. The alpha argument can be thought of as the ratio between
  12175. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12176. *
  12177. * @param {Color} color - The color to converge on.
  12178. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12179. * @return {Color} A reference to this color.
  12180. */
  12181. lerpHSL( color, alpha ) {
  12182. this.getHSL( _hslA );
  12183. color.getHSL( _hslB );
  12184. const h = lerp( _hslA.h, _hslB.h, alpha );
  12185. const s = lerp( _hslA.s, _hslB.s, alpha );
  12186. const l = lerp( _hslA.l, _hslB.l, alpha );
  12187. this.setHSL( h, s, l );
  12188. return this;
  12189. }
  12190. /**
  12191. * Sets the color's RGB components from the given 3D vector.
  12192. *
  12193. * @param {Vector3} v - The vector to set.
  12194. * @return {Color} A reference to this color.
  12195. */
  12196. setFromVector3( v ) {
  12197. this.r = v.x;
  12198. this.g = v.y;
  12199. this.b = v.z;
  12200. return this;
  12201. }
  12202. /**
  12203. * Transforms this color with the given 3x3 matrix.
  12204. *
  12205. * @param {Matrix3} m - The matrix.
  12206. * @return {Color} A reference to this color.
  12207. */
  12208. applyMatrix3( m ) {
  12209. const r = this.r, g = this.g, b = this.b;
  12210. const e = m.elements;
  12211. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12212. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12213. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12214. return this;
  12215. }
  12216. /**
  12217. * Returns `true` if this color is equal with the given one.
  12218. *
  12219. * @param {Color} c - The color to test for equality.
  12220. * @return {boolean} Whether this bounding color is equal with the given one.
  12221. */
  12222. equals( c ) {
  12223. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12224. }
  12225. /**
  12226. * Sets this color's RGB components from the given array.
  12227. *
  12228. * @param {Array<number>} array - An array holding the RGB values.
  12229. * @param {number} [offset=0] - The offset into the array.
  12230. * @return {Color} A reference to this color.
  12231. */
  12232. fromArray( array, offset = 0 ) {
  12233. this.r = array[ offset ];
  12234. this.g = array[ offset + 1 ];
  12235. this.b = array[ offset + 2 ];
  12236. return this;
  12237. }
  12238. /**
  12239. * Writes the RGB components of this color to the given array. If no array is provided,
  12240. * the method returns a new instance.
  12241. *
  12242. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12243. * @param {number} [offset=0] - Index of the first element in the array.
  12244. * @return {Array<number>} The color components.
  12245. */
  12246. toArray( array = [], offset = 0 ) {
  12247. array[ offset ] = this.r;
  12248. array[ offset + 1 ] = this.g;
  12249. array[ offset + 2 ] = this.b;
  12250. return array;
  12251. }
  12252. /**
  12253. * Sets the components of this color from the given buffer attribute.
  12254. *
  12255. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12256. * @param {number} index - The index into the attribute.
  12257. * @return {Color} A reference to this color.
  12258. */
  12259. fromBufferAttribute( attribute, index ) {
  12260. this.r = attribute.getX( index );
  12261. this.g = attribute.getY( index );
  12262. this.b = attribute.getZ( index );
  12263. return this;
  12264. }
  12265. /**
  12266. * This methods defines the serialization result of this class. Returns the color
  12267. * as a hexadecimal value.
  12268. *
  12269. * @return {number} The hexadecimal value.
  12270. */
  12271. toJSON() {
  12272. return this.getHex();
  12273. }
  12274. *[ Symbol.iterator ]() {
  12275. yield this.r;
  12276. yield this.g;
  12277. yield this.b;
  12278. }
  12279. }
  12280. const _color = /*@__PURE__*/ new Color();
  12281. /**
  12282. * A dictionary with X11 color names.
  12283. *
  12284. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12285. *
  12286. * @static
  12287. * @type {Object}
  12288. */
  12289. Color.NAMES = _colorKeywords;
  12290. let _materialId = 0;
  12291. /**
  12292. * Abstract base class for materials.
  12293. *
  12294. * Materials define the appearance of renderable 3D objects.
  12295. *
  12296. * @abstract
  12297. * @augments EventDispatcher
  12298. */
  12299. class Material extends EventDispatcher {
  12300. /**
  12301. * Constructs a new material.
  12302. */
  12303. constructor() {
  12304. super();
  12305. /**
  12306. * This flag can be used for type testing.
  12307. *
  12308. * @type {boolean}
  12309. * @readonly
  12310. * @default true
  12311. */
  12312. this.isMaterial = true;
  12313. /**
  12314. * The ID of the material.
  12315. *
  12316. * @name Material#id
  12317. * @type {number}
  12318. * @readonly
  12319. */
  12320. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12321. /**
  12322. * The UUID of the material.
  12323. *
  12324. * @type {string}
  12325. * @readonly
  12326. */
  12327. this.uuid = generateUUID();
  12328. /**
  12329. * The name of the material.
  12330. *
  12331. * @type {string}
  12332. */
  12333. this.name = '';
  12334. /**
  12335. * The type property is used for detecting the object type
  12336. * in context of serialization/deserialization.
  12337. *
  12338. * @type {string}
  12339. * @readonly
  12340. */
  12341. this.type = 'Material';
  12342. /**
  12343. * Defines the blending type of the material.
  12344. *
  12345. * It must be set to `CustomBlending` if custom blending properties like
  12346. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12347. * should have any effect.
  12348. *
  12349. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12350. * @default NormalBlending
  12351. */
  12352. this.blending = NormalBlending;
  12353. /**
  12354. * Defines which side of faces will be rendered - front, back or both.
  12355. *
  12356. * @type {(FrontSide|BackSide|DoubleSide)}
  12357. * @default FrontSide
  12358. */
  12359. this.side = FrontSide;
  12360. /**
  12361. * If set to `true`, vertex colors should be used.
  12362. *
  12363. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12364. * four (RGBA) component color buffer attribute is used.
  12365. *
  12366. * @type {boolean}
  12367. * @default false
  12368. */
  12369. this.vertexColors = false;
  12370. /**
  12371. * Defines how transparent the material is.
  12372. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12373. *
  12374. * If the {@link Material#transparent} is not set to `true`,
  12375. * the material will remain fully opaque and this value will only affect its color.
  12376. *
  12377. * @type {number}
  12378. * @default 1
  12379. */
  12380. this.opacity = 1;
  12381. /**
  12382. * Defines whether this material is transparent. This has an effect on
  12383. * rendering as transparent objects need special treatment and are rendered
  12384. * after non-transparent objects.
  12385. *
  12386. * When set to true, the extent to which the material is transparent is
  12387. * controlled by {@link Material#opacity}.
  12388. *
  12389. * @type {boolean}
  12390. * @default false
  12391. */
  12392. this.transparent = false;
  12393. /**
  12394. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12395. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12396. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12397. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12398. *
  12399. * @type {boolean}
  12400. * @default false
  12401. */
  12402. this.alphaHash = false;
  12403. /**
  12404. * Defines the blending source factor.
  12405. *
  12406. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12407. * @default SrcAlphaFactor
  12408. */
  12409. this.blendSrc = SrcAlphaFactor;
  12410. /**
  12411. * Defines the blending destination factor.
  12412. *
  12413. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12414. * @default OneMinusSrcAlphaFactor
  12415. */
  12416. this.blendDst = OneMinusSrcAlphaFactor;
  12417. /**
  12418. * Defines the blending equation.
  12419. *
  12420. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12421. * @default AddEquation
  12422. */
  12423. this.blendEquation = AddEquation;
  12424. /**
  12425. * Defines the blending source alpha factor.
  12426. *
  12427. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12428. * @default null
  12429. */
  12430. this.blendSrcAlpha = null;
  12431. /**
  12432. * Defines the blending destination alpha factor.
  12433. *
  12434. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12435. * @default null
  12436. */
  12437. this.blendDstAlpha = null;
  12438. /**
  12439. * Defines the blending equation of the alpha channel.
  12440. *
  12441. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12442. * @default null
  12443. */
  12444. this.blendEquationAlpha = null;
  12445. /**
  12446. * Represents the RGB values of the constant blend color.
  12447. *
  12448. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12449. *
  12450. * @type {Color}
  12451. * @default (0,0,0)
  12452. */
  12453. this.blendColor = new Color( 0, 0, 0 );
  12454. /**
  12455. * Represents the alpha value of the constant blend color.
  12456. *
  12457. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12458. *
  12459. * @type {number}
  12460. * @default 0
  12461. */
  12462. this.blendAlpha = 0;
  12463. /**
  12464. * Defines the depth function.
  12465. *
  12466. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12467. * @default LessEqualDepth
  12468. */
  12469. this.depthFunc = LessEqualDepth;
  12470. /**
  12471. * Whether to have depth test enabled when rendering this material.
  12472. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12473. *
  12474. * @type {boolean}
  12475. * @default true
  12476. */
  12477. this.depthTest = true;
  12478. /**
  12479. * Whether rendering this material has any effect on the depth buffer.
  12480. *
  12481. * When drawing 2D overlays it can be useful to disable the depth writing in
  12482. * order to layer several things together without creating z-index artifacts.
  12483. *
  12484. * @type {boolean}
  12485. * @default true
  12486. */
  12487. this.depthWrite = true;
  12488. /**
  12489. * The bit mask to use when writing to the stencil buffer.
  12490. *
  12491. * @type {number}
  12492. * @default 0xff
  12493. */
  12494. this.stencilWriteMask = 0xff;
  12495. /**
  12496. * The stencil comparison function to use.
  12497. *
  12498. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12499. * @default AlwaysStencilFunc
  12500. */
  12501. this.stencilFunc = AlwaysStencilFunc;
  12502. /**
  12503. * The value to use when performing stencil comparisons or stencil operations.
  12504. *
  12505. * @type {number}
  12506. * @default 0
  12507. */
  12508. this.stencilRef = 0;
  12509. /**
  12510. * The bit mask to use when comparing against the stencil buffer.
  12511. *
  12512. * @type {number}
  12513. * @default 0xff
  12514. */
  12515. this.stencilFuncMask = 0xff;
  12516. /**
  12517. * Which stencil operation to perform when the comparison function returns `false`.
  12518. *
  12519. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12520. * @default KeepStencilOp
  12521. */
  12522. this.stencilFail = KeepStencilOp;
  12523. /**
  12524. * Which stencil operation to perform when the comparison function returns
  12525. * `true` but the depth test fails.
  12526. *
  12527. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12528. * @default KeepStencilOp
  12529. */
  12530. this.stencilZFail = KeepStencilOp;
  12531. /**
  12532. * Which stencil operation to perform when the comparison function returns
  12533. * `true` and the depth test passes.
  12534. *
  12535. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12536. * @default KeepStencilOp
  12537. */
  12538. this.stencilZPass = KeepStencilOp;
  12539. /**
  12540. * Whether stencil operations are performed against the stencil buffer. In
  12541. * order to perform writes or comparisons against the stencil buffer this
  12542. * value must be `true`.
  12543. *
  12544. * @type {boolean}
  12545. * @default false
  12546. */
  12547. this.stencilWrite = false;
  12548. /**
  12549. * User-defined clipping planes specified as THREE.Plane objects in world
  12550. * space. These planes apply to the objects this material is attached to.
  12551. * Points in space whose signed distance to the plane is negative are clipped
  12552. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12553. * be `true`.
  12554. *
  12555. * @type {?Array<Plane>}
  12556. * @default null
  12557. */
  12558. this.clippingPlanes = null;
  12559. /**
  12560. * Changes the behavior of clipping planes so that only their intersection is
  12561. * clipped, rather than their union.
  12562. *
  12563. * @type {boolean}
  12564. * @default false
  12565. */
  12566. this.clipIntersection = false;
  12567. /**
  12568. * Defines whether to clip shadows according to the clipping planes specified
  12569. * on this material.
  12570. *
  12571. * @type {boolean}
  12572. * @default false
  12573. */
  12574. this.clipShadows = false;
  12575. /**
  12576. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12577. * is determined as follows:
  12578. *
  12579. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12580. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12581. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12582. *
  12583. * @type {?(FrontSide|BackSide|DoubleSide)}
  12584. * @default null
  12585. */
  12586. this.shadowSide = null;
  12587. /**
  12588. * Whether to render the material's color.
  12589. *
  12590. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12591. * objects that occlude other objects.
  12592. *
  12593. * @type {boolean}
  12594. * @default true
  12595. */
  12596. this.colorWrite = true;
  12597. /**
  12598. * Override the renderer's default precision for this material.
  12599. *
  12600. * @type {?('highp'|'mediump'|'lowp')}
  12601. * @default null
  12602. */
  12603. this.precision = null;
  12604. /**
  12605. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12606. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12607. * The offset is added before the depth test is performed and before the value is written
  12608. * into the depth buffer.
  12609. *
  12610. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12611. * rendering solids with highlighted edges.
  12612. *
  12613. * @type {boolean}
  12614. * @default false
  12615. */
  12616. this.polygonOffset = false;
  12617. /**
  12618. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12619. *
  12620. * @type {number}
  12621. * @default 0
  12622. */
  12623. this.polygonOffsetFactor = 0;
  12624. /**
  12625. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12626. *
  12627. * @type {number}
  12628. * @default 0
  12629. */
  12630. this.polygonOffsetUnits = 0;
  12631. /**
  12632. * Whether to apply dithering to the color to remove the appearance of banding.
  12633. *
  12634. * @type {boolean}
  12635. * @default false
  12636. */
  12637. this.dithering = false;
  12638. /**
  12639. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12640. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12641. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12642. *
  12643. * @type {boolean}
  12644. * @default false
  12645. */
  12646. this.alphaToCoverage = false;
  12647. /**
  12648. * Whether to premultiply the alpha (transparency) value.
  12649. *
  12650. * @type {boolean}
  12651. * @default false
  12652. */
  12653. this.premultipliedAlpha = false;
  12654. /**
  12655. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12656. *
  12657. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12658. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12659. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12660. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12661. * disable the two pass rendering to avoid performance issues.
  12662. *
  12663. * @type {boolean}
  12664. * @default false
  12665. */
  12666. this.forceSinglePass = false;
  12667. /**
  12668. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12669. *
  12670. * @type {boolean}
  12671. * @default true
  12672. */
  12673. this.allowOverride = true;
  12674. /**
  12675. * Defines whether 3D objects using this material are visible.
  12676. *
  12677. * @type {boolean}
  12678. * @default true
  12679. */
  12680. this.visible = true;
  12681. /**
  12682. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12683. *
  12684. * It is ignored when rendering to a render target or using post processing or when using
  12685. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12686. *
  12687. * @type {boolean}
  12688. * @default true
  12689. */
  12690. this.toneMapped = true;
  12691. /**
  12692. * An object that can be used to store custom data about the Material. It
  12693. * should not hold references to functions as these will not be cloned.
  12694. *
  12695. * @type {Object}
  12696. */
  12697. this.userData = {};
  12698. /**
  12699. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12700. *
  12701. * @type {number}
  12702. * @readonly
  12703. * @default 0
  12704. */
  12705. this.version = 0;
  12706. this._alphaTest = 0;
  12707. }
  12708. /**
  12709. * Sets the alpha value to be used when running an alpha test. The material
  12710. * will not be rendered if the opacity is lower than this value.
  12711. *
  12712. * @type {number}
  12713. * @readonly
  12714. * @default 0
  12715. */
  12716. get alphaTest() {
  12717. return this._alphaTest;
  12718. }
  12719. set alphaTest( value ) {
  12720. if ( this._alphaTest > 0 !== value > 0 ) {
  12721. this.version ++;
  12722. }
  12723. this._alphaTest = value;
  12724. }
  12725. /**
  12726. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12727. *
  12728. * This method can only be used when rendering with {@link WebGLRenderer}.
  12729. *
  12730. * @param {WebGLRenderer} renderer - The renderer.
  12731. * @param {Scene} scene - The scene.
  12732. * @param {Camera} camera - The camera that is used to render the scene.
  12733. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12734. * @param {Object3D} object - The 3D object.
  12735. * @param {Object} group - The geometry group data.
  12736. */
  12737. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12738. /**
  12739. * An optional callback that is executed immediately before the shader
  12740. * program is compiled. This function is called with the shader source code
  12741. * as a parameter. Useful for the modification of built-in materials.
  12742. *
  12743. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12744. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12745. * Node Material system and [TSL]{@link https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language}.
  12746. *
  12747. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12748. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12749. */
  12750. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12751. /**
  12752. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12753. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12754. * shader or recompile the shader for this material as needed.
  12755. *
  12756. * This method can only be used when rendering with {@link WebGLRenderer}.
  12757. *
  12758. * @return {string} The custom program cache key.
  12759. */
  12760. customProgramCacheKey() {
  12761. return this.onBeforeCompile.toString();
  12762. }
  12763. /**
  12764. * This method can be used to set default values from parameter objects.
  12765. * It is a generic implementation so it can be used with different types
  12766. * of materials.
  12767. *
  12768. * @param {Object} [values] - The material values to set.
  12769. */
  12770. setValues( values ) {
  12771. if ( values === undefined ) return;
  12772. for ( const key in values ) {
  12773. const newValue = values[ key ];
  12774. if ( newValue === undefined ) {
  12775. warn( `Material: parameter '${ key }' has value of undefined.` );
  12776. continue;
  12777. }
  12778. const currentValue = this[ key ];
  12779. if ( currentValue === undefined ) {
  12780. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12781. continue;
  12782. }
  12783. if ( currentValue && currentValue.isColor ) {
  12784. currentValue.set( newValue );
  12785. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12786. currentValue.copy( newValue );
  12787. } else {
  12788. this[ key ] = newValue;
  12789. }
  12790. }
  12791. }
  12792. /**
  12793. * Serializes the material into JSON.
  12794. *
  12795. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12796. * @return {Object} A JSON object representing the serialized material.
  12797. * @see {@link ObjectLoader#parse}
  12798. */
  12799. toJSON( meta ) {
  12800. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12801. if ( isRootObject ) {
  12802. meta = {
  12803. textures: {},
  12804. images: {}
  12805. };
  12806. }
  12807. const data = {
  12808. metadata: {
  12809. version: 4.7,
  12810. type: 'Material',
  12811. generator: 'Material.toJSON'
  12812. }
  12813. };
  12814. // standard Material serialization
  12815. data.uuid = this.uuid;
  12816. data.type = this.type;
  12817. if ( this.name !== '' ) data.name = this.name;
  12818. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12819. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12820. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12821. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12822. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12823. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12824. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12825. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12826. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12827. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12828. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12829. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12830. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12831. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12832. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12833. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12834. }
  12835. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12836. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12837. }
  12838. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12839. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12840. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12841. }
  12842. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12843. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12844. }
  12845. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12846. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12847. }
  12848. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12849. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12850. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12851. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12852. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12853. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12854. }
  12855. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12856. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12857. }
  12858. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12859. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12860. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12861. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12862. }
  12863. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12864. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12865. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12866. if ( this.lightMap && this.lightMap.isTexture ) {
  12867. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12868. data.lightMapIntensity = this.lightMapIntensity;
  12869. }
  12870. if ( this.aoMap && this.aoMap.isTexture ) {
  12871. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12872. data.aoMapIntensity = this.aoMapIntensity;
  12873. }
  12874. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12875. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12876. data.bumpScale = this.bumpScale;
  12877. }
  12878. if ( this.normalMap && this.normalMap.isTexture ) {
  12879. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12880. data.normalMapType = this.normalMapType;
  12881. data.normalScale = this.normalScale.toArray();
  12882. }
  12883. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12884. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12885. data.displacementScale = this.displacementScale;
  12886. data.displacementBias = this.displacementBias;
  12887. }
  12888. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12889. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12890. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12891. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12892. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12893. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12894. if ( this.envMap && this.envMap.isTexture ) {
  12895. data.envMap = this.envMap.toJSON( meta ).uuid;
  12896. if ( this.combine !== undefined ) data.combine = this.combine;
  12897. }
  12898. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12899. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12900. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12901. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12902. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12903. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12904. }
  12905. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12906. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12907. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12908. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12909. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12910. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12911. if ( this.size !== undefined ) data.size = this.size;
  12912. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12913. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12914. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12915. if ( this.side !== FrontSide ) data.side = this.side;
  12916. if ( this.vertexColors === true ) data.vertexColors = true;
  12917. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12918. if ( this.transparent === true ) data.transparent = true;
  12919. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12920. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12921. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12922. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12923. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12924. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12925. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12926. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12927. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12928. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12929. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12930. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12931. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12932. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12933. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12934. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12935. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12936. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12937. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12938. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12939. // rotation (SpriteMaterial)
  12940. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12941. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12942. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12943. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12944. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12945. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12946. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12947. if ( this.scale !== undefined ) data.scale = this.scale;
  12948. if ( this.dithering === true ) data.dithering = true;
  12949. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12950. if ( this.alphaHash === true ) data.alphaHash = true;
  12951. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12952. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12953. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12954. if ( this.wireframe === true ) data.wireframe = true;
  12955. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12956. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12957. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12958. if ( this.flatShading === true ) data.flatShading = true;
  12959. if ( this.visible === false ) data.visible = false;
  12960. if ( this.toneMapped === false ) data.toneMapped = false;
  12961. if ( this.fog === false ) data.fog = false;
  12962. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12963. // TODO: Copied from Object3D.toJSON
  12964. function extractFromCache( cache ) {
  12965. const values = [];
  12966. for ( const key in cache ) {
  12967. const data = cache[ key ];
  12968. delete data.metadata;
  12969. values.push( data );
  12970. }
  12971. return values;
  12972. }
  12973. if ( isRootObject ) {
  12974. const textures = extractFromCache( meta.textures );
  12975. const images = extractFromCache( meta.images );
  12976. if ( textures.length > 0 ) data.textures = textures;
  12977. if ( images.length > 0 ) data.images = images;
  12978. }
  12979. return data;
  12980. }
  12981. /**
  12982. * Returns a new material with copied values from this instance.
  12983. *
  12984. * @return {Material} A clone of this instance.
  12985. */
  12986. clone() {
  12987. return new this.constructor().copy( this );
  12988. }
  12989. /**
  12990. * Copies the values of the given material to this instance.
  12991. *
  12992. * @param {Material} source - The material to copy.
  12993. * @return {Material} A reference to this instance.
  12994. */
  12995. copy( source ) {
  12996. this.name = source.name;
  12997. this.blending = source.blending;
  12998. this.side = source.side;
  12999. this.vertexColors = source.vertexColors;
  13000. this.opacity = source.opacity;
  13001. this.transparent = source.transparent;
  13002. this.blendSrc = source.blendSrc;
  13003. this.blendDst = source.blendDst;
  13004. this.blendEquation = source.blendEquation;
  13005. this.blendSrcAlpha = source.blendSrcAlpha;
  13006. this.blendDstAlpha = source.blendDstAlpha;
  13007. this.blendEquationAlpha = source.blendEquationAlpha;
  13008. this.blendColor.copy( source.blendColor );
  13009. this.blendAlpha = source.blendAlpha;
  13010. this.depthFunc = source.depthFunc;
  13011. this.depthTest = source.depthTest;
  13012. this.depthWrite = source.depthWrite;
  13013. this.stencilWriteMask = source.stencilWriteMask;
  13014. this.stencilFunc = source.stencilFunc;
  13015. this.stencilRef = source.stencilRef;
  13016. this.stencilFuncMask = source.stencilFuncMask;
  13017. this.stencilFail = source.stencilFail;
  13018. this.stencilZFail = source.stencilZFail;
  13019. this.stencilZPass = source.stencilZPass;
  13020. this.stencilWrite = source.stencilWrite;
  13021. const srcPlanes = source.clippingPlanes;
  13022. let dstPlanes = null;
  13023. if ( srcPlanes !== null ) {
  13024. const n = srcPlanes.length;
  13025. dstPlanes = new Array( n );
  13026. for ( let i = 0; i !== n; ++ i ) {
  13027. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13028. }
  13029. }
  13030. this.clippingPlanes = dstPlanes;
  13031. this.clipIntersection = source.clipIntersection;
  13032. this.clipShadows = source.clipShadows;
  13033. this.shadowSide = source.shadowSide;
  13034. this.colorWrite = source.colorWrite;
  13035. this.precision = source.precision;
  13036. this.polygonOffset = source.polygonOffset;
  13037. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13038. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13039. this.dithering = source.dithering;
  13040. this.alphaTest = source.alphaTest;
  13041. this.alphaHash = source.alphaHash;
  13042. this.alphaToCoverage = source.alphaToCoverage;
  13043. this.premultipliedAlpha = source.premultipliedAlpha;
  13044. this.forceSinglePass = source.forceSinglePass;
  13045. this.visible = source.visible;
  13046. this.toneMapped = source.toneMapped;
  13047. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13048. return this;
  13049. }
  13050. /**
  13051. * Frees the GPU-related resources allocated by this instance. Call this
  13052. * method whenever this instance is no longer used in your app.
  13053. *
  13054. * @fires Material#dispose
  13055. */
  13056. dispose() {
  13057. /**
  13058. * Fires when the material has been disposed of.
  13059. *
  13060. * @event Material#dispose
  13061. * @type {Object}
  13062. */
  13063. this.dispatchEvent( { type: 'dispose' } );
  13064. }
  13065. /**
  13066. * Setting this property to `true` indicates the engine the material
  13067. * needs to be recompiled.
  13068. *
  13069. * @type {boolean}
  13070. * @default false
  13071. * @param {boolean} value
  13072. */
  13073. set needsUpdate( value ) {
  13074. if ( value === true ) this.version ++;
  13075. }
  13076. }
  13077. /**
  13078. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13079. *
  13080. * This material is not affected by lights.
  13081. *
  13082. * @augments Material
  13083. */
  13084. class MeshBasicMaterial extends Material {
  13085. /**
  13086. * Constructs a new mesh basic material.
  13087. *
  13088. * @param {Object} [parameters] - An object with one or more properties
  13089. * defining the material's appearance. Any property of the material
  13090. * (including any property from inherited materials) can be passed
  13091. * in here. Color values can be passed any type of value accepted
  13092. * by {@link Color#set}.
  13093. */
  13094. constructor( parameters ) {
  13095. super();
  13096. /**
  13097. * This flag can be used for type testing.
  13098. *
  13099. * @type {boolean}
  13100. * @readonly
  13101. * @default true
  13102. */
  13103. this.isMeshBasicMaterial = true;
  13104. this.type = 'MeshBasicMaterial';
  13105. /**
  13106. * Color of the material.
  13107. *
  13108. * @type {Color}
  13109. * @default (1,1,1)
  13110. */
  13111. this.color = new Color( 0xffffff ); // diffuse
  13112. /**
  13113. * The color map. May optionally include an alpha channel, typically combined
  13114. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13115. * color is modulated by the diffuse `color`.
  13116. *
  13117. * @type {?Texture}
  13118. * @default null
  13119. */
  13120. this.map = null;
  13121. /**
  13122. * The light map. Requires a second set of UVs.
  13123. *
  13124. * @type {?Texture}
  13125. * @default null
  13126. */
  13127. this.lightMap = null;
  13128. /**
  13129. * Intensity of the baked light.
  13130. *
  13131. * @type {number}
  13132. * @default 1
  13133. */
  13134. this.lightMapIntensity = 1.0;
  13135. /**
  13136. * The red channel of this texture is used as the ambient occlusion map.
  13137. * Requires a second set of UVs.
  13138. *
  13139. * @type {?Texture}
  13140. * @default null
  13141. */
  13142. this.aoMap = null;
  13143. /**
  13144. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13145. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13146. * red channel is also `1`, ambient light is fully occluded on a surface.
  13147. *
  13148. * @type {number}
  13149. * @default 1
  13150. */
  13151. this.aoMapIntensity = 1.0;
  13152. /**
  13153. * Specular map used by the material.
  13154. *
  13155. * @type {?Texture}
  13156. * @default null
  13157. */
  13158. this.specularMap = null;
  13159. /**
  13160. * The alpha map is a grayscale texture that controls the opacity across the
  13161. * surface (black: fully transparent; white: fully opaque).
  13162. *
  13163. * Only the color of the texture is used, ignoring the alpha channel if one
  13164. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13165. * when sampling this texture due to the extra bit of precision provided for
  13166. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13167. * luminance/alpha textures will also still work as expected.
  13168. *
  13169. * @type {?Texture}
  13170. * @default null
  13171. */
  13172. this.alphaMap = null;
  13173. /**
  13174. * The environment map.
  13175. *
  13176. * @type {?Texture}
  13177. * @default null
  13178. */
  13179. this.envMap = null;
  13180. /**
  13181. * The rotation of the environment map in radians.
  13182. *
  13183. * @type {Euler}
  13184. * @default (0,0,0)
  13185. */
  13186. this.envMapRotation = new Euler();
  13187. /**
  13188. * How to combine the result of the surface's color with the environment map, if any.
  13189. *
  13190. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13191. * blend between the two colors.
  13192. *
  13193. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13194. * @default MultiplyOperation
  13195. */
  13196. this.combine = MultiplyOperation;
  13197. /**
  13198. * How much the environment map affects the surface.
  13199. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13200. *
  13201. * @type {number}
  13202. * @default 1
  13203. */
  13204. this.reflectivity = 1;
  13205. /**
  13206. * The index of refraction (IOR) of air (approximately 1) divided by the
  13207. * index of refraction of the material. It is used with environment mapping
  13208. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13209. * The refraction ratio should not exceed `1`.
  13210. *
  13211. * @type {number}
  13212. * @default 0.98
  13213. */
  13214. this.refractionRatio = 0.98;
  13215. /**
  13216. * Renders the geometry as a wireframe.
  13217. *
  13218. * @type {boolean}
  13219. * @default false
  13220. */
  13221. this.wireframe = false;
  13222. /**
  13223. * Controls the thickness of the wireframe.
  13224. *
  13225. * Can only be used with {@link SVGRenderer}.
  13226. *
  13227. * @type {number}
  13228. * @default 1
  13229. */
  13230. this.wireframeLinewidth = 1;
  13231. /**
  13232. * Defines appearance of wireframe ends.
  13233. *
  13234. * Can only be used with {@link SVGRenderer}.
  13235. *
  13236. * @type {('round'|'bevel'|'miter')}
  13237. * @default 'round'
  13238. */
  13239. this.wireframeLinecap = 'round';
  13240. /**
  13241. * Defines appearance of wireframe joints.
  13242. *
  13243. * Can only be used with {@link SVGRenderer}.
  13244. *
  13245. * @type {('round'|'bevel'|'miter')}
  13246. * @default 'round'
  13247. */
  13248. this.wireframeLinejoin = 'round';
  13249. /**
  13250. * Whether the material is affected by fog or not.
  13251. *
  13252. * @type {boolean}
  13253. * @default true
  13254. */
  13255. this.fog = true;
  13256. this.setValues( parameters );
  13257. }
  13258. copy( source ) {
  13259. super.copy( source );
  13260. this.color.copy( source.color );
  13261. this.map = source.map;
  13262. this.lightMap = source.lightMap;
  13263. this.lightMapIntensity = source.lightMapIntensity;
  13264. this.aoMap = source.aoMap;
  13265. this.aoMapIntensity = source.aoMapIntensity;
  13266. this.specularMap = source.specularMap;
  13267. this.alphaMap = source.alphaMap;
  13268. this.envMap = source.envMap;
  13269. this.envMapRotation.copy( source.envMapRotation );
  13270. this.combine = source.combine;
  13271. this.reflectivity = source.reflectivity;
  13272. this.refractionRatio = source.refractionRatio;
  13273. this.wireframe = source.wireframe;
  13274. this.wireframeLinewidth = source.wireframeLinewidth;
  13275. this.wireframeLinecap = source.wireframeLinecap;
  13276. this.wireframeLinejoin = source.wireframeLinejoin;
  13277. this.fog = source.fog;
  13278. return this;
  13279. }
  13280. }
  13281. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13282. const _tables = /*@__PURE__*/ _generateTables();
  13283. function _generateTables() {
  13284. // float32 to float16 helpers
  13285. const buffer = new ArrayBuffer( 4 );
  13286. const floatView = new Float32Array( buffer );
  13287. const uint32View = new Uint32Array( buffer );
  13288. const baseTable = new Uint32Array( 512 );
  13289. const shiftTable = new Uint32Array( 512 );
  13290. for ( let i = 0; i < 256; ++ i ) {
  13291. const e = i - 127;
  13292. // very small number (0, -0)
  13293. if ( e < -27 ) {
  13294. baseTable[ i ] = 0x0000;
  13295. baseTable[ i | 0x100 ] = 0x8000;
  13296. shiftTable[ i ] = 24;
  13297. shiftTable[ i | 0x100 ] = 24;
  13298. // small number (denorm)
  13299. } else if ( e < -14 ) {
  13300. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13301. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13302. shiftTable[ i ] = - e - 1;
  13303. shiftTable[ i | 0x100 ] = - e - 1;
  13304. // normal number
  13305. } else if ( e <= 15 ) {
  13306. baseTable[ i ] = ( e + 15 ) << 10;
  13307. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13308. shiftTable[ i ] = 13;
  13309. shiftTable[ i | 0x100 ] = 13;
  13310. // large number (Infinity, -Infinity)
  13311. } else if ( e < 128 ) {
  13312. baseTable[ i ] = 0x7c00;
  13313. baseTable[ i | 0x100 ] = 0xfc00;
  13314. shiftTable[ i ] = 24;
  13315. shiftTable[ i | 0x100 ] = 24;
  13316. // stay (NaN, Infinity, -Infinity)
  13317. } else {
  13318. baseTable[ i ] = 0x7c00;
  13319. baseTable[ i | 0x100 ] = 0xfc00;
  13320. shiftTable[ i ] = 13;
  13321. shiftTable[ i | 0x100 ] = 13;
  13322. }
  13323. }
  13324. // float16 to float32 helpers
  13325. const mantissaTable = new Uint32Array( 2048 );
  13326. const exponentTable = new Uint32Array( 64 );
  13327. const offsetTable = new Uint32Array( 64 );
  13328. for ( let i = 1; i < 1024; ++ i ) {
  13329. let m = i << 13; // zero pad mantissa bits
  13330. let e = 0; // zero exponent
  13331. // normalized
  13332. while ( ( m & 0x00800000 ) === 0 ) {
  13333. m <<= 1;
  13334. e -= 0x00800000; // decrement exponent
  13335. }
  13336. m &= -8388609; // clear leading 1 bit
  13337. e += 0x38800000; // adjust bias
  13338. mantissaTable[ i ] = m | e;
  13339. }
  13340. for ( let i = 1024; i < 2048; ++ i ) {
  13341. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13342. }
  13343. for ( let i = 1; i < 31; ++ i ) {
  13344. exponentTable[ i ] = i << 23;
  13345. }
  13346. exponentTable[ 31 ] = 0x47800000;
  13347. exponentTable[ 32 ] = 0x80000000;
  13348. for ( let i = 33; i < 63; ++ i ) {
  13349. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13350. }
  13351. exponentTable[ 63 ] = 0xc7800000;
  13352. for ( let i = 1; i < 64; ++ i ) {
  13353. if ( i !== 32 ) {
  13354. offsetTable[ i ] = 1024;
  13355. }
  13356. }
  13357. return {
  13358. floatView: floatView,
  13359. uint32View: uint32View,
  13360. baseTable: baseTable,
  13361. shiftTable: shiftTable,
  13362. mantissaTable: mantissaTable,
  13363. exponentTable: exponentTable,
  13364. offsetTable: offsetTable
  13365. };
  13366. }
  13367. /**
  13368. * Returns a half precision floating point value (FP16) from the given single
  13369. * precision floating point value (FP32).
  13370. *
  13371. * @param {number} val - A single precision floating point value.
  13372. * @return {number} The FP16 value.
  13373. */
  13374. function toHalfFloat( val ) {
  13375. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13376. val = clamp( val, -65504, 65504 );
  13377. _tables.floatView[ 0 ] = val;
  13378. const f = _tables.uint32View[ 0 ];
  13379. const e = ( f >> 23 ) & 0x1ff;
  13380. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13381. }
  13382. /**
  13383. * Returns a single precision floating point value (FP32) from the given half
  13384. * precision floating point value (FP16).
  13385. *
  13386. * @param {number} val - A half precision floating point value.
  13387. * @return {number} The FP32 value.
  13388. */
  13389. function fromHalfFloat( val ) {
  13390. const m = val >> 10;
  13391. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13392. return _tables.floatView[ 0 ];
  13393. }
  13394. /**
  13395. * A class containing utility functions for data.
  13396. *
  13397. * @hideconstructor
  13398. */
  13399. class DataUtils {
  13400. /**
  13401. * Returns a half precision floating point value (FP16) from the given single
  13402. * precision floating point value (FP32).
  13403. *
  13404. * @param {number} val - A single precision floating point value.
  13405. * @return {number} The FP16 value.
  13406. */
  13407. static toHalfFloat( val ) {
  13408. return toHalfFloat( val );
  13409. }
  13410. /**
  13411. * Returns a single precision floating point value (FP32) from the given half
  13412. * precision floating point value (FP16).
  13413. *
  13414. * @param {number} val - A half precision floating point value.
  13415. * @return {number} The FP32 value.
  13416. */
  13417. static fromHalfFloat( val ) {
  13418. return fromHalfFloat( val );
  13419. }
  13420. }
  13421. const _vector$9 = /*@__PURE__*/ new Vector3();
  13422. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13423. let _id$3 = 0;
  13424. /**
  13425. * This class stores data for an attribute (such as vertex positions, face
  13426. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13427. * a geometry, which allows for more efficient passing of data to the GPU.
  13428. *
  13429. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13430. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13431. */
  13432. class BufferAttribute {
  13433. /**
  13434. * Constructs a new buffer attribute.
  13435. *
  13436. * @param {TypedArray} array - The array holding the attribute data.
  13437. * @param {number} itemSize - The item size.
  13438. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13439. */
  13440. constructor( array, itemSize, normalized = false ) {
  13441. if ( Array.isArray( array ) ) {
  13442. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13443. }
  13444. /**
  13445. * This flag can be used for type testing.
  13446. *
  13447. * @type {boolean}
  13448. * @readonly
  13449. * @default true
  13450. */
  13451. this.isBufferAttribute = true;
  13452. /**
  13453. * The ID of the buffer attribute.
  13454. *
  13455. * @name BufferAttribute#id
  13456. * @type {number}
  13457. * @readonly
  13458. */
  13459. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13460. /**
  13461. * The name of the buffer attribute.
  13462. *
  13463. * @type {string}
  13464. */
  13465. this.name = '';
  13466. /**
  13467. * The array holding the attribute data. It should have `itemSize * numVertices`
  13468. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13469. *
  13470. * @type {TypedArray}
  13471. */
  13472. this.array = array;
  13473. /**
  13474. * The number of values of the array that should be associated with a particular vertex.
  13475. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13476. * normal, or color), then the value should be `3`.
  13477. *
  13478. * @type {number}
  13479. */
  13480. this.itemSize = itemSize;
  13481. /**
  13482. * Represents the number of items this buffer attribute stores. It is internally computed
  13483. * by dividing the `array` length by the `itemSize`.
  13484. *
  13485. * @type {number}
  13486. * @readonly
  13487. */
  13488. this.count = array !== undefined ? array.length / itemSize : 0;
  13489. /**
  13490. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13491. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13492. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13493. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13494. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13495. *
  13496. * @type {boolean}
  13497. */
  13498. this.normalized = normalized;
  13499. /**
  13500. * Defines the intended usage pattern of the data store for optimization purposes.
  13501. *
  13502. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13503. * instantiate a new one and set the desired usage before the next render.
  13504. *
  13505. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13506. * @default StaticDrawUsage
  13507. */
  13508. this.usage = StaticDrawUsage;
  13509. /**
  13510. * This can be used to only update some components of stored vectors (for example, just the
  13511. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13512. *
  13513. * @type {Array<Object>}
  13514. */
  13515. this.updateRanges = [];
  13516. /**
  13517. * Configures the bound GPU type for use in shaders.
  13518. *
  13519. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13520. * For lower precision float types, use `Float16BufferAttribute`.
  13521. *
  13522. * @type {(FloatType|IntType)}
  13523. * @default FloatType
  13524. */
  13525. this.gpuType = FloatType;
  13526. /**
  13527. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13528. *
  13529. * @type {number}
  13530. */
  13531. this.version = 0;
  13532. }
  13533. /**
  13534. * A callback function that is executed after the renderer has transferred the attribute
  13535. * array data to the GPU.
  13536. */
  13537. onUploadCallback() {}
  13538. /**
  13539. * Flag to indicate that this attribute has changed and should be re-sent to
  13540. * the GPU. Set this to `true` when you modify the value of the array.
  13541. *
  13542. * @type {number}
  13543. * @default false
  13544. * @param {boolean} value
  13545. */
  13546. set needsUpdate( value ) {
  13547. if ( value === true ) this.version ++;
  13548. }
  13549. /**
  13550. * Sets the usage of this buffer attribute.
  13551. *
  13552. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13553. * @return {BufferAttribute} A reference to this buffer attribute.
  13554. */
  13555. setUsage( value ) {
  13556. this.usage = value;
  13557. return this;
  13558. }
  13559. /**
  13560. * Adds a range of data in the data array to be updated on the GPU.
  13561. *
  13562. * @param {number} start - Position at which to start update.
  13563. * @param {number} count - The number of components to update.
  13564. */
  13565. addUpdateRange( start, count ) {
  13566. this.updateRanges.push( { start, count } );
  13567. }
  13568. /**
  13569. * Clears the update ranges.
  13570. */
  13571. clearUpdateRanges() {
  13572. this.updateRanges.length = 0;
  13573. }
  13574. /**
  13575. * Copies the values of the given buffer attribute to this instance.
  13576. *
  13577. * @param {BufferAttribute} source - The buffer attribute to copy.
  13578. * @return {BufferAttribute} A reference to this instance.
  13579. */
  13580. copy( source ) {
  13581. this.name = source.name;
  13582. this.array = new source.array.constructor( source.array );
  13583. this.itemSize = source.itemSize;
  13584. this.count = source.count;
  13585. this.normalized = source.normalized;
  13586. this.usage = source.usage;
  13587. this.gpuType = source.gpuType;
  13588. return this;
  13589. }
  13590. /**
  13591. * Copies a vector from the given buffer attribute to this one. The start
  13592. * and destination position in the attribute buffers are represented by the
  13593. * given indices.
  13594. *
  13595. * @param {number} index1 - The destination index into this buffer attribute.
  13596. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13597. * @param {number} index2 - The source index into the given buffer attribute.
  13598. * @return {BufferAttribute} A reference to this instance.
  13599. */
  13600. copyAt( index1, attribute, index2 ) {
  13601. index1 *= this.itemSize;
  13602. index2 *= attribute.itemSize;
  13603. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13604. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13605. }
  13606. return this;
  13607. }
  13608. /**
  13609. * Copies the given array data into this buffer attribute.
  13610. *
  13611. * @param {(TypedArray|Array)} array - The array to copy.
  13612. * @return {BufferAttribute} A reference to this instance.
  13613. */
  13614. copyArray( array ) {
  13615. this.array.set( array );
  13616. return this;
  13617. }
  13618. /**
  13619. * Applies the given 3x3 matrix to the given attribute. Works with
  13620. * item size `2` and `3`.
  13621. *
  13622. * @param {Matrix3} m - The matrix to apply.
  13623. * @return {BufferAttribute} A reference to this instance.
  13624. */
  13625. applyMatrix3( m ) {
  13626. if ( this.itemSize === 2 ) {
  13627. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13628. _vector2$1.fromBufferAttribute( this, i );
  13629. _vector2$1.applyMatrix3( m );
  13630. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13631. }
  13632. } else if ( this.itemSize === 3 ) {
  13633. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13634. _vector$9.fromBufferAttribute( this, i );
  13635. _vector$9.applyMatrix3( m );
  13636. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13637. }
  13638. }
  13639. return this;
  13640. }
  13641. /**
  13642. * Applies the given 4x4 matrix to the given attribute. Only works with
  13643. * item size `3`.
  13644. *
  13645. * @param {Matrix4} m - The matrix to apply.
  13646. * @return {BufferAttribute} A reference to this instance.
  13647. */
  13648. applyMatrix4( m ) {
  13649. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13650. _vector$9.fromBufferAttribute( this, i );
  13651. _vector$9.applyMatrix4( m );
  13652. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13653. }
  13654. return this;
  13655. }
  13656. /**
  13657. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13658. * item size `3`.
  13659. *
  13660. * @param {Matrix3} m - The normal matrix to apply.
  13661. * @return {BufferAttribute} A reference to this instance.
  13662. */
  13663. applyNormalMatrix( m ) {
  13664. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13665. _vector$9.fromBufferAttribute( this, i );
  13666. _vector$9.applyNormalMatrix( m );
  13667. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13668. }
  13669. return this;
  13670. }
  13671. /**
  13672. * Applies the given 4x4 matrix to the given attribute. Only works with
  13673. * item size `3` and with direction vectors.
  13674. *
  13675. * @param {Matrix4} m - The matrix to apply.
  13676. * @return {BufferAttribute} A reference to this instance.
  13677. */
  13678. transformDirection( m ) {
  13679. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13680. _vector$9.fromBufferAttribute( this, i );
  13681. _vector$9.transformDirection( m );
  13682. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13683. }
  13684. return this;
  13685. }
  13686. /**
  13687. * Sets the given array data in the buffer attribute.
  13688. *
  13689. * @param {(TypedArray|Array)} value - The array data to set.
  13690. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13691. * @return {BufferAttribute} A reference to this instance.
  13692. */
  13693. set( value, offset = 0 ) {
  13694. // Matching BufferAttribute constructor, do not normalize the array.
  13695. this.array.set( value, offset );
  13696. return this;
  13697. }
  13698. /**
  13699. * Returns the given component of the vector at the given index.
  13700. *
  13701. * @param {number} index - The index into the buffer attribute.
  13702. * @param {number} component - The component index.
  13703. * @return {number} The returned value.
  13704. */
  13705. getComponent( index, component ) {
  13706. let value = this.array[ index * this.itemSize + component ];
  13707. if ( this.normalized ) value = denormalize( value, this.array );
  13708. return value;
  13709. }
  13710. /**
  13711. * Sets the given value to the given component of the vector at the given index.
  13712. *
  13713. * @param {number} index - The index into the buffer attribute.
  13714. * @param {number} component - The component index.
  13715. * @param {number} value - The value to set.
  13716. * @return {BufferAttribute} A reference to this instance.
  13717. */
  13718. setComponent( index, component, value ) {
  13719. if ( this.normalized ) value = normalize( value, this.array );
  13720. this.array[ index * this.itemSize + component ] = value;
  13721. return this;
  13722. }
  13723. /**
  13724. * Returns the x component of the vector at the given index.
  13725. *
  13726. * @param {number} index - The index into the buffer attribute.
  13727. * @return {number} The x component.
  13728. */
  13729. getX( index ) {
  13730. let x = this.array[ index * this.itemSize ];
  13731. if ( this.normalized ) x = denormalize( x, this.array );
  13732. return x;
  13733. }
  13734. /**
  13735. * Sets the x component of the vector at the given index.
  13736. *
  13737. * @param {number} index - The index into the buffer attribute.
  13738. * @param {number} x - The value to set.
  13739. * @return {BufferAttribute} A reference to this instance.
  13740. */
  13741. setX( index, x ) {
  13742. if ( this.normalized ) x = normalize( x, this.array );
  13743. this.array[ index * this.itemSize ] = x;
  13744. return this;
  13745. }
  13746. /**
  13747. * Returns the y component of the vector at the given index.
  13748. *
  13749. * @param {number} index - The index into the buffer attribute.
  13750. * @return {number} The y component.
  13751. */
  13752. getY( index ) {
  13753. let y = this.array[ index * this.itemSize + 1 ];
  13754. if ( this.normalized ) y = denormalize( y, this.array );
  13755. return y;
  13756. }
  13757. /**
  13758. * Sets the y component of the vector at the given index.
  13759. *
  13760. * @param {number} index - The index into the buffer attribute.
  13761. * @param {number} y - The value to set.
  13762. * @return {BufferAttribute} A reference to this instance.
  13763. */
  13764. setY( index, y ) {
  13765. if ( this.normalized ) y = normalize( y, this.array );
  13766. this.array[ index * this.itemSize + 1 ] = y;
  13767. return this;
  13768. }
  13769. /**
  13770. * Returns the z component of the vector at the given index.
  13771. *
  13772. * @param {number} index - The index into the buffer attribute.
  13773. * @return {number} The z component.
  13774. */
  13775. getZ( index ) {
  13776. let z = this.array[ index * this.itemSize + 2 ];
  13777. if ( this.normalized ) z = denormalize( z, this.array );
  13778. return z;
  13779. }
  13780. /**
  13781. * Sets the z component of the vector at the given index.
  13782. *
  13783. * @param {number} index - The index into the buffer attribute.
  13784. * @param {number} z - The value to set.
  13785. * @return {BufferAttribute} A reference to this instance.
  13786. */
  13787. setZ( index, z ) {
  13788. if ( this.normalized ) z = normalize( z, this.array );
  13789. this.array[ index * this.itemSize + 2 ] = z;
  13790. return this;
  13791. }
  13792. /**
  13793. * Returns the w component of the vector at the given index.
  13794. *
  13795. * @param {number} index - The index into the buffer attribute.
  13796. * @return {number} The w component.
  13797. */
  13798. getW( index ) {
  13799. let w = this.array[ index * this.itemSize + 3 ];
  13800. if ( this.normalized ) w = denormalize( w, this.array );
  13801. return w;
  13802. }
  13803. /**
  13804. * Sets the w component of the vector at the given index.
  13805. *
  13806. * @param {number} index - The index into the buffer attribute.
  13807. * @param {number} w - The value to set.
  13808. * @return {BufferAttribute} A reference to this instance.
  13809. */
  13810. setW( index, w ) {
  13811. if ( this.normalized ) w = normalize( w, this.array );
  13812. this.array[ index * this.itemSize + 3 ] = w;
  13813. return this;
  13814. }
  13815. /**
  13816. * Sets the x and y component of the vector at the given index.
  13817. *
  13818. * @param {number} index - The index into the buffer attribute.
  13819. * @param {number} x - The value for the x component to set.
  13820. * @param {number} y - The value for the y component to set.
  13821. * @return {BufferAttribute} A reference to this instance.
  13822. */
  13823. setXY( index, x, y ) {
  13824. index *= this.itemSize;
  13825. if ( this.normalized ) {
  13826. x = normalize( x, this.array );
  13827. y = normalize( y, this.array );
  13828. }
  13829. this.array[ index + 0 ] = x;
  13830. this.array[ index + 1 ] = y;
  13831. return this;
  13832. }
  13833. /**
  13834. * Sets the x, y and z component of the vector at the given index.
  13835. *
  13836. * @param {number} index - The index into the buffer attribute.
  13837. * @param {number} x - The value for the x component to set.
  13838. * @param {number} y - The value for the y component to set.
  13839. * @param {number} z - The value for the z component to set.
  13840. * @return {BufferAttribute} A reference to this instance.
  13841. */
  13842. setXYZ( index, x, y, z ) {
  13843. index *= this.itemSize;
  13844. if ( this.normalized ) {
  13845. x = normalize( x, this.array );
  13846. y = normalize( y, this.array );
  13847. z = normalize( z, this.array );
  13848. }
  13849. this.array[ index + 0 ] = x;
  13850. this.array[ index + 1 ] = y;
  13851. this.array[ index + 2 ] = z;
  13852. return this;
  13853. }
  13854. /**
  13855. * Sets the x, y, z and w component of the vector at the given index.
  13856. *
  13857. * @param {number} index - The index into the buffer attribute.
  13858. * @param {number} x - The value for the x component to set.
  13859. * @param {number} y - The value for the y component to set.
  13860. * @param {number} z - The value for the z component to set.
  13861. * @param {number} w - The value for the w component to set.
  13862. * @return {BufferAttribute} A reference to this instance.
  13863. */
  13864. setXYZW( index, x, y, z, w ) {
  13865. index *= this.itemSize;
  13866. if ( this.normalized ) {
  13867. x = normalize( x, this.array );
  13868. y = normalize( y, this.array );
  13869. z = normalize( z, this.array );
  13870. w = normalize( w, this.array );
  13871. }
  13872. this.array[ index + 0 ] = x;
  13873. this.array[ index + 1 ] = y;
  13874. this.array[ index + 2 ] = z;
  13875. this.array[ index + 3 ] = w;
  13876. return this;
  13877. }
  13878. /**
  13879. * Sets the given callback function that is executed after the Renderer has transferred
  13880. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13881. * the upload when attribute data are not needed anymore on the CPU side.
  13882. *
  13883. * @param {Function} callback - The `onUpload()` callback.
  13884. * @return {BufferAttribute} A reference to this instance.
  13885. */
  13886. onUpload( callback ) {
  13887. this.onUploadCallback = callback;
  13888. return this;
  13889. }
  13890. /**
  13891. * Returns a new buffer attribute with copied values from this instance.
  13892. *
  13893. * @return {BufferAttribute} A clone of this instance.
  13894. */
  13895. clone() {
  13896. return new this.constructor( this.array, this.itemSize ).copy( this );
  13897. }
  13898. /**
  13899. * Serializes the buffer attribute into JSON.
  13900. *
  13901. * @return {Object} A JSON object representing the serialized buffer attribute.
  13902. */
  13903. toJSON() {
  13904. const data = {
  13905. itemSize: this.itemSize,
  13906. type: this.array.constructor.name,
  13907. array: Array.from( this.array ),
  13908. normalized: this.normalized
  13909. };
  13910. if ( this.name !== '' ) data.name = this.name;
  13911. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13912. return data;
  13913. }
  13914. }
  13915. /**
  13916. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13917. * a plain `Array` instance.
  13918. *
  13919. * @augments BufferAttribute
  13920. */
  13921. class Int8BufferAttribute extends BufferAttribute {
  13922. /**
  13923. * Constructs a new buffer attribute.
  13924. *
  13925. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13926. * @param {number} itemSize - The item size.
  13927. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13928. */
  13929. constructor( array, itemSize, normalized ) {
  13930. super( new Int8Array( array ), itemSize, normalized );
  13931. }
  13932. }
  13933. /**
  13934. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13935. * a plain `Array` instance.
  13936. *
  13937. * @augments BufferAttribute
  13938. */
  13939. class Uint8BufferAttribute extends BufferAttribute {
  13940. /**
  13941. * Constructs a new buffer attribute.
  13942. *
  13943. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13944. * @param {number} itemSize - The item size.
  13945. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13946. */
  13947. constructor( array, itemSize, normalized ) {
  13948. super( new Uint8Array( array ), itemSize, normalized );
  13949. }
  13950. }
  13951. /**
  13952. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13953. * a plain `Array` instance.
  13954. *
  13955. * @augments BufferAttribute
  13956. */
  13957. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13958. /**
  13959. * Constructs a new buffer attribute.
  13960. *
  13961. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13962. * @param {number} itemSize - The item size.
  13963. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13964. */
  13965. constructor( array, itemSize, normalized ) {
  13966. super( new Uint8ClampedArray( array ), itemSize, normalized );
  13967. }
  13968. }
  13969. /**
  13970. * Convenient class that can be used when creating a `Int16` buffer attribute with
  13971. * a plain `Array` instance.
  13972. *
  13973. * @augments BufferAttribute
  13974. */
  13975. class Int16BufferAttribute extends BufferAttribute {
  13976. /**
  13977. * Constructs a new buffer attribute.
  13978. *
  13979. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  13980. * @param {number} itemSize - The item size.
  13981. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13982. */
  13983. constructor( array, itemSize, normalized ) {
  13984. super( new Int16Array( array ), itemSize, normalized );
  13985. }
  13986. }
  13987. /**
  13988. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  13989. * a plain `Array` instance.
  13990. *
  13991. * @augments BufferAttribute
  13992. */
  13993. class Uint16BufferAttribute extends BufferAttribute {
  13994. /**
  13995. * Constructs a new buffer attribute.
  13996. *
  13997. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  13998. * @param {number} itemSize - The item size.
  13999. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14000. */
  14001. constructor( array, itemSize, normalized ) {
  14002. super( new Uint16Array( array ), itemSize, normalized );
  14003. }
  14004. }
  14005. /**
  14006. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14007. * a plain `Array` instance.
  14008. *
  14009. * @augments BufferAttribute
  14010. */
  14011. class Int32BufferAttribute extends BufferAttribute {
  14012. /**
  14013. * Constructs a new buffer attribute.
  14014. *
  14015. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14016. * @param {number} itemSize - The item size.
  14017. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14018. */
  14019. constructor( array, itemSize, normalized ) {
  14020. super( new Int32Array( array ), itemSize, normalized );
  14021. }
  14022. }
  14023. /**
  14024. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14025. * a plain `Array` instance.
  14026. *
  14027. * @augments BufferAttribute
  14028. */
  14029. class Uint32BufferAttribute extends BufferAttribute {
  14030. /**
  14031. * Constructs a new buffer attribute.
  14032. *
  14033. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14034. * @param {number} itemSize - The item size.
  14035. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14036. */
  14037. constructor( array, itemSize, normalized ) {
  14038. super( new Uint32Array( array ), itemSize, normalized );
  14039. }
  14040. }
  14041. /**
  14042. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14043. * a plain `Array` instance.
  14044. *
  14045. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14046. * browser support is still problematic.
  14047. *
  14048. * @augments BufferAttribute
  14049. */
  14050. class Float16BufferAttribute extends BufferAttribute {
  14051. /**
  14052. * Constructs a new buffer attribute.
  14053. *
  14054. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14055. * @param {number} itemSize - The item size.
  14056. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14057. */
  14058. constructor( array, itemSize, normalized ) {
  14059. super( new Uint16Array( array ), itemSize, normalized );
  14060. this.isFloat16BufferAttribute = true;
  14061. }
  14062. getX( index ) {
  14063. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14064. if ( this.normalized ) x = denormalize( x, this.array );
  14065. return x;
  14066. }
  14067. setX( index, x ) {
  14068. if ( this.normalized ) x = normalize( x, this.array );
  14069. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14070. return this;
  14071. }
  14072. getY( index ) {
  14073. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14074. if ( this.normalized ) y = denormalize( y, this.array );
  14075. return y;
  14076. }
  14077. setY( index, y ) {
  14078. if ( this.normalized ) y = normalize( y, this.array );
  14079. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14080. return this;
  14081. }
  14082. getZ( index ) {
  14083. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14084. if ( this.normalized ) z = denormalize( z, this.array );
  14085. return z;
  14086. }
  14087. setZ( index, z ) {
  14088. if ( this.normalized ) z = normalize( z, this.array );
  14089. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14090. return this;
  14091. }
  14092. getW( index ) {
  14093. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14094. if ( this.normalized ) w = denormalize( w, this.array );
  14095. return w;
  14096. }
  14097. setW( index, w ) {
  14098. if ( this.normalized ) w = normalize( w, this.array );
  14099. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14100. return this;
  14101. }
  14102. setXY( index, x, y ) {
  14103. index *= this.itemSize;
  14104. if ( this.normalized ) {
  14105. x = normalize( x, this.array );
  14106. y = normalize( y, this.array );
  14107. }
  14108. this.array[ index + 0 ] = toHalfFloat( x );
  14109. this.array[ index + 1 ] = toHalfFloat( y );
  14110. return this;
  14111. }
  14112. setXYZ( index, x, y, z ) {
  14113. index *= this.itemSize;
  14114. if ( this.normalized ) {
  14115. x = normalize( x, this.array );
  14116. y = normalize( y, this.array );
  14117. z = normalize( z, this.array );
  14118. }
  14119. this.array[ index + 0 ] = toHalfFloat( x );
  14120. this.array[ index + 1 ] = toHalfFloat( y );
  14121. this.array[ index + 2 ] = toHalfFloat( z );
  14122. return this;
  14123. }
  14124. setXYZW( index, x, y, z, w ) {
  14125. index *= this.itemSize;
  14126. if ( this.normalized ) {
  14127. x = normalize( x, this.array );
  14128. y = normalize( y, this.array );
  14129. z = normalize( z, this.array );
  14130. w = normalize( w, this.array );
  14131. }
  14132. this.array[ index + 0 ] = toHalfFloat( x );
  14133. this.array[ index + 1 ] = toHalfFloat( y );
  14134. this.array[ index + 2 ] = toHalfFloat( z );
  14135. this.array[ index + 3 ] = toHalfFloat( w );
  14136. return this;
  14137. }
  14138. }
  14139. /**
  14140. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14141. * a plain `Array` instance.
  14142. *
  14143. * @augments BufferAttribute
  14144. */
  14145. class Float32BufferAttribute extends BufferAttribute {
  14146. /**
  14147. * Constructs a new buffer attribute.
  14148. *
  14149. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14150. * @param {number} itemSize - The item size.
  14151. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14152. */
  14153. constructor( array, itemSize, normalized ) {
  14154. super( new Float32Array( array ), itemSize, normalized );
  14155. }
  14156. }
  14157. let _id$2 = 0;
  14158. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14159. const _obj = /*@__PURE__*/ new Object3D();
  14160. const _offset = /*@__PURE__*/ new Vector3();
  14161. const _box$2 = /*@__PURE__*/ new Box3();
  14162. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14163. const _vector$8 = /*@__PURE__*/ new Vector3();
  14164. /**
  14165. * A representation of mesh, line, or point geometry. Includes vertex
  14166. * positions, face indices, normals, colors, UVs, and custom attributes
  14167. * within buffers, reducing the cost of passing all this data to the GPU.
  14168. *
  14169. * ```js
  14170. * const geometry = new THREE.BufferGeometry();
  14171. * // create a simple square shape. We duplicate the top left and bottom right
  14172. * // vertices because each vertex needs to appear once per triangle.
  14173. * const vertices = new Float32Array( [
  14174. * -1.0, -1.0, 1.0, // v0
  14175. * 1.0, -1.0, 1.0, // v1
  14176. * 1.0, 1.0, 1.0, // v2
  14177. *
  14178. * 1.0, 1.0, 1.0, // v3
  14179. * -1.0, 1.0, 1.0, // v4
  14180. * -1.0, -1.0, 1.0 // v5
  14181. * ] );
  14182. * // itemSize = 3 because there are 3 values (components) per vertex
  14183. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14184. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14185. * const mesh = new THREE.Mesh( geometry, material );
  14186. * ```
  14187. *
  14188. * @augments EventDispatcher
  14189. */
  14190. class BufferGeometry extends EventDispatcher {
  14191. /**
  14192. * Constructs a new geometry.
  14193. */
  14194. constructor() {
  14195. super();
  14196. /**
  14197. * This flag can be used for type testing.
  14198. *
  14199. * @type {boolean}
  14200. * @readonly
  14201. * @default true
  14202. */
  14203. this.isBufferGeometry = true;
  14204. /**
  14205. * The ID of the geometry.
  14206. *
  14207. * @name BufferGeometry#id
  14208. * @type {number}
  14209. * @readonly
  14210. */
  14211. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14212. /**
  14213. * The UUID of the geometry.
  14214. *
  14215. * @type {string}
  14216. * @readonly
  14217. */
  14218. this.uuid = generateUUID();
  14219. /**
  14220. * The name of the geometry.
  14221. *
  14222. * @type {string}
  14223. */
  14224. this.name = '';
  14225. this.type = 'BufferGeometry';
  14226. /**
  14227. * Allows for vertices to be re-used across multiple triangles; this is
  14228. * called using "indexed triangles". Each triangle is associated with the
  14229. * indices of three vertices. This attribute therefore stores the index of
  14230. * each vertex for each triangular face. If this attribute is not set, the
  14231. * renderer assumes that each three contiguous positions represent a single triangle.
  14232. *
  14233. * @type {?BufferAttribute}
  14234. * @default null
  14235. */
  14236. this.index = null;
  14237. /**
  14238. * A (storage) buffer attribute which was generated with a compute shader and
  14239. * now defines indirect draw calls.
  14240. *
  14241. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14242. *
  14243. * @type {?BufferAttribute}
  14244. * @default null
  14245. */
  14246. this.indirect = null;
  14247. /**
  14248. * This dictionary has as id the name of the attribute to be set and as value
  14249. * the buffer attribute to set it to. Rather than accessing this property directly,
  14250. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14251. *
  14252. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14253. */
  14254. this.attributes = {};
  14255. /**
  14256. * This dictionary holds the morph targets of the geometry.
  14257. *
  14258. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14259. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14260. *
  14261. * @type {Object}
  14262. */
  14263. this.morphAttributes = {};
  14264. /**
  14265. * Used to control the morph target behavior; when set to `true`, the morph
  14266. * target data is treated as relative offsets, rather than as absolute
  14267. * positions/normals.
  14268. *
  14269. * @type {boolean}
  14270. * @default false
  14271. */
  14272. this.morphTargetsRelative = false;
  14273. /**
  14274. * Split the geometry into groups, each of which will be rendered in a
  14275. * separate draw call. This allows an array of materials to be used with the geometry.
  14276. *
  14277. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14278. *
  14279. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14280. * indices, and must not leave vertices or indices unused.
  14281. *
  14282. * @type {Array<Object>}
  14283. */
  14284. this.groups = [];
  14285. /**
  14286. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14287. *
  14288. * @type {?Box3}
  14289. * @default null
  14290. */
  14291. this.boundingBox = null;
  14292. /**
  14293. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14294. *
  14295. * @type {?Sphere}
  14296. * @default null
  14297. */
  14298. this.boundingSphere = null;
  14299. /**
  14300. * Determines the part of the geometry to render. This should not be set directly,
  14301. * instead use `setDrawRange()`.
  14302. *
  14303. * @type {{start:number,count:number}}
  14304. */
  14305. this.drawRange = { start: 0, count: Infinity };
  14306. /**
  14307. * An object that can be used to store custom data about the geometry.
  14308. * It should not hold references to functions as these will not be cloned.
  14309. *
  14310. * @type {Object}
  14311. */
  14312. this.userData = {};
  14313. }
  14314. /**
  14315. * Returns the index of this geometry.
  14316. *
  14317. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14318. */
  14319. getIndex() {
  14320. return this.index;
  14321. }
  14322. /**
  14323. * Sets the given index to this geometry.
  14324. *
  14325. * @param {Array<number>|BufferAttribute} index - The index to set.
  14326. * @return {BufferGeometry} A reference to this instance.
  14327. */
  14328. setIndex( index ) {
  14329. if ( Array.isArray( index ) ) {
  14330. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14331. } else {
  14332. this.index = index;
  14333. }
  14334. return this;
  14335. }
  14336. /**
  14337. * Sets the given indirect attribute to this geometry.
  14338. *
  14339. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14340. * @return {BufferGeometry} A reference to this instance.
  14341. */
  14342. setIndirect( indirect ) {
  14343. this.indirect = indirect;
  14344. return this;
  14345. }
  14346. /**
  14347. * Returns the indirect attribute of this geometry.
  14348. *
  14349. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14350. */
  14351. getIndirect() {
  14352. return this.indirect;
  14353. }
  14354. /**
  14355. * Returns the buffer attribute for the given name.
  14356. *
  14357. * @param {string} name - The attribute name.
  14358. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14359. * Returns `undefined` if not attribute has been found.
  14360. */
  14361. getAttribute( name ) {
  14362. return this.attributes[ name ];
  14363. }
  14364. /**
  14365. * Sets the given attribute for the given name.
  14366. *
  14367. * @param {string} name - The attribute name.
  14368. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14369. * @return {BufferGeometry} A reference to this instance.
  14370. */
  14371. setAttribute( name, attribute ) {
  14372. this.attributes[ name ] = attribute;
  14373. return this;
  14374. }
  14375. /**
  14376. * Deletes the attribute for the given name.
  14377. *
  14378. * @param {string} name - The attribute name to delete.
  14379. * @return {BufferGeometry} A reference to this instance.
  14380. */
  14381. deleteAttribute( name ) {
  14382. delete this.attributes[ name ];
  14383. return this;
  14384. }
  14385. /**
  14386. * Returns `true` if this geometry has an attribute for the given name.
  14387. *
  14388. * @param {string} name - The attribute name.
  14389. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14390. */
  14391. hasAttribute( name ) {
  14392. return this.attributes[ name ] !== undefined;
  14393. }
  14394. /**
  14395. * Adds a group to this geometry.
  14396. *
  14397. * @param {number} start - The first element in this draw call. That is the first
  14398. * vertex for non-indexed geometry, otherwise the first triangle index.
  14399. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14400. * @param {number} [materialIndex=0] - The material array index to use.
  14401. */
  14402. addGroup( start, count, materialIndex = 0 ) {
  14403. this.groups.push( {
  14404. start: start,
  14405. count: count,
  14406. materialIndex: materialIndex
  14407. } );
  14408. }
  14409. /**
  14410. * Clears all groups.
  14411. */
  14412. clearGroups() {
  14413. this.groups = [];
  14414. }
  14415. /**
  14416. * Sets the draw range for this geometry.
  14417. *
  14418. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14419. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14420. * For indexed BufferGeometry, `count` is the number of indices to render.
  14421. */
  14422. setDrawRange( start, count ) {
  14423. this.drawRange.start = start;
  14424. this.drawRange.count = count;
  14425. }
  14426. /**
  14427. * Applies the given 4x4 transformation matrix to the geometry.
  14428. *
  14429. * @param {Matrix4} matrix - The matrix to apply.
  14430. * @return {BufferGeometry} A reference to this instance.
  14431. */
  14432. applyMatrix4( matrix ) {
  14433. const position = this.attributes.position;
  14434. if ( position !== undefined ) {
  14435. position.applyMatrix4( matrix );
  14436. position.needsUpdate = true;
  14437. }
  14438. const normal = this.attributes.normal;
  14439. if ( normal !== undefined ) {
  14440. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14441. normal.applyNormalMatrix( normalMatrix );
  14442. normal.needsUpdate = true;
  14443. }
  14444. const tangent = this.attributes.tangent;
  14445. if ( tangent !== undefined ) {
  14446. tangent.transformDirection( matrix );
  14447. tangent.needsUpdate = true;
  14448. }
  14449. if ( this.boundingBox !== null ) {
  14450. this.computeBoundingBox();
  14451. }
  14452. if ( this.boundingSphere !== null ) {
  14453. this.computeBoundingSphere();
  14454. }
  14455. return this;
  14456. }
  14457. /**
  14458. * Applies the rotation represented by the Quaternion to the geometry.
  14459. *
  14460. * @param {Quaternion} q - The Quaternion to apply.
  14461. * @return {BufferGeometry} A reference to this instance.
  14462. */
  14463. applyQuaternion( q ) {
  14464. _m1$2.makeRotationFromQuaternion( q );
  14465. this.applyMatrix4( _m1$2 );
  14466. return this;
  14467. }
  14468. /**
  14469. * Rotates the geometry about the X axis. This is typically done as a one time
  14470. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14471. * real-time mesh rotation.
  14472. *
  14473. * @param {number} angle - The angle in radians.
  14474. * @return {BufferGeometry} A reference to this instance.
  14475. */
  14476. rotateX( angle ) {
  14477. // rotate geometry around world x-axis
  14478. _m1$2.makeRotationX( angle );
  14479. this.applyMatrix4( _m1$2 );
  14480. return this;
  14481. }
  14482. /**
  14483. * Rotates the geometry about the Y axis. This is typically done as a one time
  14484. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14485. * real-time mesh rotation.
  14486. *
  14487. * @param {number} angle - The angle in radians.
  14488. * @return {BufferGeometry} A reference to this instance.
  14489. */
  14490. rotateY( angle ) {
  14491. // rotate geometry around world y-axis
  14492. _m1$2.makeRotationY( angle );
  14493. this.applyMatrix4( _m1$2 );
  14494. return this;
  14495. }
  14496. /**
  14497. * Rotates the geometry about the Z axis. This is typically done as a one time
  14498. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14499. * real-time mesh rotation.
  14500. *
  14501. * @param {number} angle - The angle in radians.
  14502. * @return {BufferGeometry} A reference to this instance.
  14503. */
  14504. rotateZ( angle ) {
  14505. // rotate geometry around world z-axis
  14506. _m1$2.makeRotationZ( angle );
  14507. this.applyMatrix4( _m1$2 );
  14508. return this;
  14509. }
  14510. /**
  14511. * Translates the geometry. This is typically done as a one time
  14512. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14513. * real-time mesh rotation.
  14514. *
  14515. * @param {number} x - The x offset.
  14516. * @param {number} y - The y offset.
  14517. * @param {number} z - The z offset.
  14518. * @return {BufferGeometry} A reference to this instance.
  14519. */
  14520. translate( x, y, z ) {
  14521. // translate geometry
  14522. _m1$2.makeTranslation( x, y, z );
  14523. this.applyMatrix4( _m1$2 );
  14524. return this;
  14525. }
  14526. /**
  14527. * Scales the geometry. This is typically done as a one time
  14528. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14529. * real-time mesh rotation.
  14530. *
  14531. * @param {number} x - The x scale.
  14532. * @param {number} y - The y scale.
  14533. * @param {number} z - The z scale.
  14534. * @return {BufferGeometry} A reference to this instance.
  14535. */
  14536. scale( x, y, z ) {
  14537. // scale geometry
  14538. _m1$2.makeScale( x, y, z );
  14539. this.applyMatrix4( _m1$2 );
  14540. return this;
  14541. }
  14542. /**
  14543. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14544. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14545. * real-time mesh rotation.
  14546. *
  14547. * @param {Vector3} vector - The target point.
  14548. * @return {BufferGeometry} A reference to this instance.
  14549. */
  14550. lookAt( vector ) {
  14551. _obj.lookAt( vector );
  14552. _obj.updateMatrix();
  14553. this.applyMatrix4( _obj.matrix );
  14554. return this;
  14555. }
  14556. /**
  14557. * Center the geometry based on its bounding box.
  14558. *
  14559. * @return {BufferGeometry} A reference to this instance.
  14560. */
  14561. center() {
  14562. this.computeBoundingBox();
  14563. this.boundingBox.getCenter( _offset ).negate();
  14564. this.translate( _offset.x, _offset.y, _offset.z );
  14565. return this;
  14566. }
  14567. /**
  14568. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14569. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14570. * set to `0`.
  14571. *
  14572. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14573. * data from the array. The length of the array must match the vertex count.
  14574. *
  14575. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14576. * @return {BufferGeometry} A reference to this instance.
  14577. */
  14578. setFromPoints( points ) {
  14579. const positionAttribute = this.getAttribute( 'position' );
  14580. if ( positionAttribute === undefined ) {
  14581. const position = [];
  14582. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14583. const point = points[ i ];
  14584. position.push( point.x, point.y, point.z || 0 );
  14585. }
  14586. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14587. } else {
  14588. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14589. for ( let i = 0; i < l; i ++ ) {
  14590. const point = points[ i ];
  14591. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14592. }
  14593. if ( points.length > positionAttribute.count ) {
  14594. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14595. }
  14596. positionAttribute.needsUpdate = true;
  14597. }
  14598. return this;
  14599. }
  14600. /**
  14601. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14602. * The bounding box is not computed by the engine; it must be computed by your app.
  14603. * You may need to recompute the bounding box if the geometry vertices are modified.
  14604. */
  14605. computeBoundingBox() {
  14606. if ( this.boundingBox === null ) {
  14607. this.boundingBox = new Box3();
  14608. }
  14609. const position = this.attributes.position;
  14610. const morphAttributesPosition = this.morphAttributes.position;
  14611. if ( position && position.isGLBufferAttribute ) {
  14612. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14613. this.boundingBox.set(
  14614. new Vector3( - Infinity, - Infinity, - Infinity ),
  14615. new Vector3( + Infinity, + Infinity, + Infinity )
  14616. );
  14617. return;
  14618. }
  14619. if ( position !== undefined ) {
  14620. this.boundingBox.setFromBufferAttribute( position );
  14621. // process morph attributes if present
  14622. if ( morphAttributesPosition ) {
  14623. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14624. const morphAttribute = morphAttributesPosition[ i ];
  14625. _box$2.setFromBufferAttribute( morphAttribute );
  14626. if ( this.morphTargetsRelative ) {
  14627. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14628. this.boundingBox.expandByPoint( _vector$8 );
  14629. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14630. this.boundingBox.expandByPoint( _vector$8 );
  14631. } else {
  14632. this.boundingBox.expandByPoint( _box$2.min );
  14633. this.boundingBox.expandByPoint( _box$2.max );
  14634. }
  14635. }
  14636. }
  14637. } else {
  14638. this.boundingBox.makeEmpty();
  14639. }
  14640. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14641. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14642. }
  14643. }
  14644. /**
  14645. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14646. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14647. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14648. */
  14649. computeBoundingSphere() {
  14650. if ( this.boundingSphere === null ) {
  14651. this.boundingSphere = new Sphere();
  14652. }
  14653. const position = this.attributes.position;
  14654. const morphAttributesPosition = this.morphAttributes.position;
  14655. if ( position && position.isGLBufferAttribute ) {
  14656. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14657. this.boundingSphere.set( new Vector3(), Infinity );
  14658. return;
  14659. }
  14660. if ( position ) {
  14661. // first, find the center of the bounding sphere
  14662. const center = this.boundingSphere.center;
  14663. _box$2.setFromBufferAttribute( position );
  14664. // process morph attributes if present
  14665. if ( morphAttributesPosition ) {
  14666. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14667. const morphAttribute = morphAttributesPosition[ i ];
  14668. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14669. if ( this.morphTargetsRelative ) {
  14670. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14671. _box$2.expandByPoint( _vector$8 );
  14672. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14673. _box$2.expandByPoint( _vector$8 );
  14674. } else {
  14675. _box$2.expandByPoint( _boxMorphTargets.min );
  14676. _box$2.expandByPoint( _boxMorphTargets.max );
  14677. }
  14678. }
  14679. }
  14680. _box$2.getCenter( center );
  14681. // second, try to find a boundingSphere with a radius smaller than the
  14682. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14683. let maxRadiusSq = 0;
  14684. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14685. _vector$8.fromBufferAttribute( position, i );
  14686. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14687. }
  14688. // process morph attributes if present
  14689. if ( morphAttributesPosition ) {
  14690. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14691. const morphAttribute = morphAttributesPosition[ i ];
  14692. const morphTargetsRelative = this.morphTargetsRelative;
  14693. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14694. _vector$8.fromBufferAttribute( morphAttribute, j );
  14695. if ( morphTargetsRelative ) {
  14696. _offset.fromBufferAttribute( position, j );
  14697. _vector$8.add( _offset );
  14698. }
  14699. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14700. }
  14701. }
  14702. }
  14703. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14704. if ( isNaN( this.boundingSphere.radius ) ) {
  14705. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14706. }
  14707. }
  14708. }
  14709. /**
  14710. * Calculates and adds a tangent attribute to this geometry.
  14711. *
  14712. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14713. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14714. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14715. */
  14716. computeTangents() {
  14717. const index = this.index;
  14718. const attributes = this.attributes;
  14719. // based on http://www.terathon.com/code/tangent.html
  14720. // (per vertex tangents)
  14721. if ( index === null ||
  14722. attributes.position === undefined ||
  14723. attributes.normal === undefined ||
  14724. attributes.uv === undefined ) {
  14725. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14726. return;
  14727. }
  14728. const positionAttribute = attributes.position;
  14729. const normalAttribute = attributes.normal;
  14730. const uvAttribute = attributes.uv;
  14731. if ( this.hasAttribute( 'tangent' ) === false ) {
  14732. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14733. }
  14734. const tangentAttribute = this.getAttribute( 'tangent' );
  14735. const tan1 = [], tan2 = [];
  14736. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14737. tan1[ i ] = new Vector3();
  14738. tan2[ i ] = new Vector3();
  14739. }
  14740. const vA = new Vector3(),
  14741. vB = new Vector3(),
  14742. vC = new Vector3(),
  14743. uvA = new Vector2(),
  14744. uvB = new Vector2(),
  14745. uvC = new Vector2(),
  14746. sdir = new Vector3(),
  14747. tdir = new Vector3();
  14748. function handleTriangle( a, b, c ) {
  14749. vA.fromBufferAttribute( positionAttribute, a );
  14750. vB.fromBufferAttribute( positionAttribute, b );
  14751. vC.fromBufferAttribute( positionAttribute, c );
  14752. uvA.fromBufferAttribute( uvAttribute, a );
  14753. uvB.fromBufferAttribute( uvAttribute, b );
  14754. uvC.fromBufferAttribute( uvAttribute, c );
  14755. vB.sub( vA );
  14756. vC.sub( vA );
  14757. uvB.sub( uvA );
  14758. uvC.sub( uvA );
  14759. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14760. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14761. if ( ! isFinite( r ) ) return;
  14762. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14763. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14764. tan1[ a ].add( sdir );
  14765. tan1[ b ].add( sdir );
  14766. tan1[ c ].add( sdir );
  14767. tan2[ a ].add( tdir );
  14768. tan2[ b ].add( tdir );
  14769. tan2[ c ].add( tdir );
  14770. }
  14771. let groups = this.groups;
  14772. if ( groups.length === 0 ) {
  14773. groups = [ {
  14774. start: 0,
  14775. count: index.count
  14776. } ];
  14777. }
  14778. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14779. const group = groups[ i ];
  14780. const start = group.start;
  14781. const count = group.count;
  14782. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14783. handleTriangle(
  14784. index.getX( j + 0 ),
  14785. index.getX( j + 1 ),
  14786. index.getX( j + 2 )
  14787. );
  14788. }
  14789. }
  14790. const tmp = new Vector3(), tmp2 = new Vector3();
  14791. const n = new Vector3(), n2 = new Vector3();
  14792. function handleVertex( v ) {
  14793. n.fromBufferAttribute( normalAttribute, v );
  14794. n2.copy( n );
  14795. const t = tan1[ v ];
  14796. // Gram-Schmidt orthogonalize
  14797. tmp.copy( t );
  14798. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14799. // Calculate handedness
  14800. tmp2.crossVectors( n2, t );
  14801. const test = tmp2.dot( tan2[ v ] );
  14802. const w = ( test < 0.0 ) ? -1 : 1.0;
  14803. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14804. }
  14805. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14806. const group = groups[ i ];
  14807. const start = group.start;
  14808. const count = group.count;
  14809. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14810. handleVertex( index.getX( j + 0 ) );
  14811. handleVertex( index.getX( j + 1 ) );
  14812. handleVertex( index.getX( j + 2 ) );
  14813. }
  14814. }
  14815. }
  14816. /**
  14817. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14818. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14819. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14820. * to be the same as the face normal.
  14821. */
  14822. computeVertexNormals() {
  14823. const index = this.index;
  14824. const positionAttribute = this.getAttribute( 'position' );
  14825. if ( positionAttribute !== undefined ) {
  14826. let normalAttribute = this.getAttribute( 'normal' );
  14827. if ( normalAttribute === undefined ) {
  14828. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14829. this.setAttribute( 'normal', normalAttribute );
  14830. } else {
  14831. // reset existing normals to zero
  14832. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14833. normalAttribute.setXYZ( i, 0, 0, 0 );
  14834. }
  14835. }
  14836. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14837. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14838. const cb = new Vector3(), ab = new Vector3();
  14839. // indexed elements
  14840. if ( index ) {
  14841. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14842. const vA = index.getX( i + 0 );
  14843. const vB = index.getX( i + 1 );
  14844. const vC = index.getX( i + 2 );
  14845. pA.fromBufferAttribute( positionAttribute, vA );
  14846. pB.fromBufferAttribute( positionAttribute, vB );
  14847. pC.fromBufferAttribute( positionAttribute, vC );
  14848. cb.subVectors( pC, pB );
  14849. ab.subVectors( pA, pB );
  14850. cb.cross( ab );
  14851. nA.fromBufferAttribute( normalAttribute, vA );
  14852. nB.fromBufferAttribute( normalAttribute, vB );
  14853. nC.fromBufferAttribute( normalAttribute, vC );
  14854. nA.add( cb );
  14855. nB.add( cb );
  14856. nC.add( cb );
  14857. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14858. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14859. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14860. }
  14861. } else {
  14862. // non-indexed elements (unconnected triangle soup)
  14863. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14864. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14865. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14866. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14867. cb.subVectors( pC, pB );
  14868. ab.subVectors( pA, pB );
  14869. cb.cross( ab );
  14870. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14871. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14872. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14873. }
  14874. }
  14875. this.normalizeNormals();
  14876. normalAttribute.needsUpdate = true;
  14877. }
  14878. }
  14879. /**
  14880. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14881. * correct lighting on the geometry surfaces.
  14882. */
  14883. normalizeNormals() {
  14884. const normals = this.attributes.normal;
  14885. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14886. _vector$8.fromBufferAttribute( normals, i );
  14887. _vector$8.normalize();
  14888. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14889. }
  14890. }
  14891. /**
  14892. * Return a new non-index version of this indexed geometry. If the geometry
  14893. * is already non-indexed, the method is a NOOP.
  14894. *
  14895. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14896. */
  14897. toNonIndexed() {
  14898. function convertBufferAttribute( attribute, indices ) {
  14899. const array = attribute.array;
  14900. const itemSize = attribute.itemSize;
  14901. const normalized = attribute.normalized;
  14902. const array2 = new array.constructor( indices.length * itemSize );
  14903. let index = 0, index2 = 0;
  14904. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14905. if ( attribute.isInterleavedBufferAttribute ) {
  14906. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14907. } else {
  14908. index = indices[ i ] * itemSize;
  14909. }
  14910. for ( let j = 0; j < itemSize; j ++ ) {
  14911. array2[ index2 ++ ] = array[ index ++ ];
  14912. }
  14913. }
  14914. return new BufferAttribute( array2, itemSize, normalized );
  14915. }
  14916. //
  14917. if ( this.index === null ) {
  14918. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14919. return this;
  14920. }
  14921. const geometry2 = new BufferGeometry();
  14922. const indices = this.index.array;
  14923. const attributes = this.attributes;
  14924. // attributes
  14925. for ( const name in attributes ) {
  14926. const attribute = attributes[ name ];
  14927. const newAttribute = convertBufferAttribute( attribute, indices );
  14928. geometry2.setAttribute( name, newAttribute );
  14929. }
  14930. // morph attributes
  14931. const morphAttributes = this.morphAttributes;
  14932. for ( const name in morphAttributes ) {
  14933. const morphArray = [];
  14934. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14935. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14936. const attribute = morphAttribute[ i ];
  14937. const newAttribute = convertBufferAttribute( attribute, indices );
  14938. morphArray.push( newAttribute );
  14939. }
  14940. geometry2.morphAttributes[ name ] = morphArray;
  14941. }
  14942. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14943. // groups
  14944. const groups = this.groups;
  14945. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14946. const group = groups[ i ];
  14947. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14948. }
  14949. return geometry2;
  14950. }
  14951. /**
  14952. * Serializes the geometry into JSON.
  14953. *
  14954. * @return {Object} A JSON object representing the serialized geometry.
  14955. */
  14956. toJSON() {
  14957. const data = {
  14958. metadata: {
  14959. version: 4.7,
  14960. type: 'BufferGeometry',
  14961. generator: 'BufferGeometry.toJSON'
  14962. }
  14963. };
  14964. // standard BufferGeometry serialization
  14965. data.uuid = this.uuid;
  14966. data.type = this.type;
  14967. if ( this.name !== '' ) data.name = this.name;
  14968. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  14969. if ( this.parameters !== undefined ) {
  14970. const parameters = this.parameters;
  14971. for ( const key in parameters ) {
  14972. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  14973. }
  14974. return data;
  14975. }
  14976. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  14977. data.data = { attributes: {} };
  14978. const index = this.index;
  14979. if ( index !== null ) {
  14980. data.data.index = {
  14981. type: index.array.constructor.name,
  14982. array: Array.prototype.slice.call( index.array )
  14983. };
  14984. }
  14985. const attributes = this.attributes;
  14986. for ( const key in attributes ) {
  14987. const attribute = attributes[ key ];
  14988. data.data.attributes[ key ] = attribute.toJSON( data.data );
  14989. }
  14990. const morphAttributes = {};
  14991. let hasMorphAttributes = false;
  14992. for ( const key in this.morphAttributes ) {
  14993. const attributeArray = this.morphAttributes[ key ];
  14994. const array = [];
  14995. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  14996. const attribute = attributeArray[ i ];
  14997. array.push( attribute.toJSON( data.data ) );
  14998. }
  14999. if ( array.length > 0 ) {
  15000. morphAttributes[ key ] = array;
  15001. hasMorphAttributes = true;
  15002. }
  15003. }
  15004. if ( hasMorphAttributes ) {
  15005. data.data.morphAttributes = morphAttributes;
  15006. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15007. }
  15008. const groups = this.groups;
  15009. if ( groups.length > 0 ) {
  15010. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15011. }
  15012. const boundingSphere = this.boundingSphere;
  15013. if ( boundingSphere !== null ) {
  15014. data.data.boundingSphere = boundingSphere.toJSON();
  15015. }
  15016. return data;
  15017. }
  15018. /**
  15019. * Returns a new geometry with copied values from this instance.
  15020. *
  15021. * @return {BufferGeometry} A clone of this instance.
  15022. */
  15023. clone() {
  15024. return new this.constructor().copy( this );
  15025. }
  15026. /**
  15027. * Copies the values of the given geometry to this instance.
  15028. *
  15029. * @param {BufferGeometry} source - The geometry to copy.
  15030. * @return {BufferGeometry} A reference to this instance.
  15031. */
  15032. copy( source ) {
  15033. // reset
  15034. this.index = null;
  15035. this.attributes = {};
  15036. this.morphAttributes = {};
  15037. this.groups = [];
  15038. this.boundingBox = null;
  15039. this.boundingSphere = null;
  15040. // used for storing cloned, shared data
  15041. const data = {};
  15042. // name
  15043. this.name = source.name;
  15044. // index
  15045. const index = source.index;
  15046. if ( index !== null ) {
  15047. this.setIndex( index.clone() );
  15048. }
  15049. // attributes
  15050. const attributes = source.attributes;
  15051. for ( const name in attributes ) {
  15052. const attribute = attributes[ name ];
  15053. this.setAttribute( name, attribute.clone( data ) );
  15054. }
  15055. // morph attributes
  15056. const morphAttributes = source.morphAttributes;
  15057. for ( const name in morphAttributes ) {
  15058. const array = [];
  15059. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15060. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15061. array.push( morphAttribute[ i ].clone( data ) );
  15062. }
  15063. this.morphAttributes[ name ] = array;
  15064. }
  15065. this.morphTargetsRelative = source.morphTargetsRelative;
  15066. // groups
  15067. const groups = source.groups;
  15068. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15069. const group = groups[ i ];
  15070. this.addGroup( group.start, group.count, group.materialIndex );
  15071. }
  15072. // bounding box
  15073. const boundingBox = source.boundingBox;
  15074. if ( boundingBox !== null ) {
  15075. this.boundingBox = boundingBox.clone();
  15076. }
  15077. // bounding sphere
  15078. const boundingSphere = source.boundingSphere;
  15079. if ( boundingSphere !== null ) {
  15080. this.boundingSphere = boundingSphere.clone();
  15081. }
  15082. // draw range
  15083. this.drawRange.start = source.drawRange.start;
  15084. this.drawRange.count = source.drawRange.count;
  15085. // user data
  15086. this.userData = source.userData;
  15087. return this;
  15088. }
  15089. /**
  15090. * Frees the GPU-related resources allocated by this instance. Call this
  15091. * method whenever this instance is no longer used in your app.
  15092. *
  15093. * @fires BufferGeometry#dispose
  15094. */
  15095. dispose() {
  15096. this.dispatchEvent( { type: 'dispose' } );
  15097. }
  15098. }
  15099. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15100. const _ray$3 = /*@__PURE__*/ new Ray();
  15101. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15102. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15103. const _vA$1 = /*@__PURE__*/ new Vector3();
  15104. const _vB$1 = /*@__PURE__*/ new Vector3();
  15105. const _vC$1 = /*@__PURE__*/ new Vector3();
  15106. const _tempA = /*@__PURE__*/ new Vector3();
  15107. const _morphA = /*@__PURE__*/ new Vector3();
  15108. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15109. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15110. /**
  15111. * Class representing triangular polygon mesh based objects.
  15112. *
  15113. * ```js
  15114. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15115. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15116. * const mesh = new THREE.Mesh( geometry, material );
  15117. * scene.add( mesh );
  15118. * ```
  15119. *
  15120. * @augments Object3D
  15121. */
  15122. class Mesh extends Object3D {
  15123. /**
  15124. * Constructs a new mesh.
  15125. *
  15126. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15127. * @param {Material|Array<Material>} [material] - The mesh material.
  15128. */
  15129. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15130. super();
  15131. /**
  15132. * This flag can be used for type testing.
  15133. *
  15134. * @type {boolean}
  15135. * @readonly
  15136. * @default true
  15137. */
  15138. this.isMesh = true;
  15139. this.type = 'Mesh';
  15140. /**
  15141. * The mesh geometry.
  15142. *
  15143. * @type {BufferGeometry}
  15144. */
  15145. this.geometry = geometry;
  15146. /**
  15147. * The mesh material.
  15148. *
  15149. * @type {Material|Array<Material>}
  15150. * @default MeshBasicMaterial
  15151. */
  15152. this.material = material;
  15153. /**
  15154. * A dictionary representing the morph targets in the geometry. The key is the
  15155. * morph targets name, the value its attribute index. This member is `undefined`
  15156. * by default and only set when morph targets are detected in the geometry.
  15157. *
  15158. * @type {Object<String,number>|undefined}
  15159. * @default undefined
  15160. */
  15161. this.morphTargetDictionary = undefined;
  15162. /**
  15163. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15164. * is applied. This member is `undefined` by default and only set when morph targets are
  15165. * detected in the geometry.
  15166. *
  15167. * @type {Array<number>|undefined}
  15168. * @default undefined
  15169. */
  15170. this.morphTargetInfluences = undefined;
  15171. /**
  15172. * The number of instances of this mesh.
  15173. * Can only be used with {@link WebGPURenderer}.
  15174. *
  15175. * @type {number}
  15176. * @default 1
  15177. */
  15178. this.count = 1;
  15179. this.updateMorphTargets();
  15180. }
  15181. copy( source, recursive ) {
  15182. super.copy( source, recursive );
  15183. if ( source.morphTargetInfluences !== undefined ) {
  15184. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15185. }
  15186. if ( source.morphTargetDictionary !== undefined ) {
  15187. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15188. }
  15189. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15190. this.geometry = source.geometry;
  15191. return this;
  15192. }
  15193. /**
  15194. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15195. * to make sure existing morph targets can influence this 3D object.
  15196. */
  15197. updateMorphTargets() {
  15198. const geometry = this.geometry;
  15199. const morphAttributes = geometry.morphAttributes;
  15200. const keys = Object.keys( morphAttributes );
  15201. if ( keys.length > 0 ) {
  15202. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15203. if ( morphAttribute !== undefined ) {
  15204. this.morphTargetInfluences = [];
  15205. this.morphTargetDictionary = {};
  15206. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15207. const name = morphAttribute[ m ].name || String( m );
  15208. this.morphTargetInfluences.push( 0 );
  15209. this.morphTargetDictionary[ name ] = m;
  15210. }
  15211. }
  15212. }
  15213. }
  15214. /**
  15215. * Returns the local-space position of the vertex at the given index, taking into
  15216. * account the current animation state of both morph targets and skinning.
  15217. *
  15218. * @param {number} index - The vertex index.
  15219. * @param {Vector3} target - The target object that is used to store the method's result.
  15220. * @return {Vector3} The vertex position in local space.
  15221. */
  15222. getVertexPosition( index, target ) {
  15223. const geometry = this.geometry;
  15224. const position = geometry.attributes.position;
  15225. const morphPosition = geometry.morphAttributes.position;
  15226. const morphTargetsRelative = geometry.morphTargetsRelative;
  15227. target.fromBufferAttribute( position, index );
  15228. const morphInfluences = this.morphTargetInfluences;
  15229. if ( morphPosition && morphInfluences ) {
  15230. _morphA.set( 0, 0, 0 );
  15231. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15232. const influence = morphInfluences[ i ];
  15233. const morphAttribute = morphPosition[ i ];
  15234. if ( influence === 0 ) continue;
  15235. _tempA.fromBufferAttribute( morphAttribute, index );
  15236. if ( morphTargetsRelative ) {
  15237. _morphA.addScaledVector( _tempA, influence );
  15238. } else {
  15239. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15240. }
  15241. }
  15242. target.add( _morphA );
  15243. }
  15244. return target;
  15245. }
  15246. /**
  15247. * Computes intersection points between a casted ray and this line.
  15248. *
  15249. * @param {Raycaster} raycaster - The raycaster.
  15250. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15251. */
  15252. raycast( raycaster, intersects ) {
  15253. const geometry = this.geometry;
  15254. const material = this.material;
  15255. const matrixWorld = this.matrixWorld;
  15256. if ( material === undefined ) return;
  15257. // test with bounding sphere in world space
  15258. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15259. _sphere$6.copy( geometry.boundingSphere );
  15260. _sphere$6.applyMatrix4( matrixWorld );
  15261. // check distance from ray origin to bounding sphere
  15262. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15263. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15264. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15265. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15266. }
  15267. // convert ray to local space of mesh
  15268. _inverseMatrix$3.copy( matrixWorld ).invert();
  15269. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15270. // test with bounding box in local space
  15271. if ( geometry.boundingBox !== null ) {
  15272. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15273. }
  15274. // test for intersections with geometry
  15275. this._computeIntersections( raycaster, intersects, _ray$3 );
  15276. }
  15277. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15278. let intersection;
  15279. const geometry = this.geometry;
  15280. const material = this.material;
  15281. const index = geometry.index;
  15282. const position = geometry.attributes.position;
  15283. const uv = geometry.attributes.uv;
  15284. const uv1 = geometry.attributes.uv1;
  15285. const normal = geometry.attributes.normal;
  15286. const groups = geometry.groups;
  15287. const drawRange = geometry.drawRange;
  15288. if ( index !== null ) {
  15289. // indexed buffer geometry
  15290. if ( Array.isArray( material ) ) {
  15291. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15292. const group = groups[ i ];
  15293. const groupMaterial = material[ group.materialIndex ];
  15294. const start = Math.max( group.start, drawRange.start );
  15295. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15296. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15297. const a = index.getX( j );
  15298. const b = index.getX( j + 1 );
  15299. const c = index.getX( j + 2 );
  15300. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15301. if ( intersection ) {
  15302. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15303. intersection.face.materialIndex = group.materialIndex;
  15304. intersects.push( intersection );
  15305. }
  15306. }
  15307. }
  15308. } else {
  15309. const start = Math.max( 0, drawRange.start );
  15310. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15311. for ( let i = start, il = end; i < il; i += 3 ) {
  15312. const a = index.getX( i );
  15313. const b = index.getX( i + 1 );
  15314. const c = index.getX( i + 2 );
  15315. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15316. if ( intersection ) {
  15317. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15318. intersects.push( intersection );
  15319. }
  15320. }
  15321. }
  15322. } else if ( position !== undefined ) {
  15323. // non-indexed buffer geometry
  15324. if ( Array.isArray( material ) ) {
  15325. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15326. const group = groups[ i ];
  15327. const groupMaterial = material[ group.materialIndex ];
  15328. const start = Math.max( group.start, drawRange.start );
  15329. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15330. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15331. const a = j;
  15332. const b = j + 1;
  15333. const c = j + 2;
  15334. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15335. if ( intersection ) {
  15336. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15337. intersection.face.materialIndex = group.materialIndex;
  15338. intersects.push( intersection );
  15339. }
  15340. }
  15341. }
  15342. } else {
  15343. const start = Math.max( 0, drawRange.start );
  15344. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15345. for ( let i = start, il = end; i < il; i += 3 ) {
  15346. const a = i;
  15347. const b = i + 1;
  15348. const c = i + 2;
  15349. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15350. if ( intersection ) {
  15351. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15352. intersects.push( intersection );
  15353. }
  15354. }
  15355. }
  15356. }
  15357. }
  15358. }
  15359. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15360. let intersect;
  15361. if ( material.side === BackSide ) {
  15362. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15363. } else {
  15364. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15365. }
  15366. if ( intersect === null ) return null;
  15367. _intersectionPointWorld.copy( point );
  15368. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15369. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15370. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15371. return {
  15372. distance: distance,
  15373. point: _intersectionPointWorld.clone(),
  15374. object: object
  15375. };
  15376. }
  15377. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15378. object.getVertexPosition( a, _vA$1 );
  15379. object.getVertexPosition( b, _vB$1 );
  15380. object.getVertexPosition( c, _vC$1 );
  15381. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15382. if ( intersection ) {
  15383. const barycoord = new Vector3();
  15384. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15385. if ( uv ) {
  15386. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15387. }
  15388. if ( uv1 ) {
  15389. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15390. }
  15391. if ( normal ) {
  15392. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15393. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15394. intersection.normal.multiplyScalar( -1 );
  15395. }
  15396. }
  15397. const face = {
  15398. a: a,
  15399. b: b,
  15400. c: c,
  15401. normal: new Vector3(),
  15402. materialIndex: 0
  15403. };
  15404. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15405. intersection.face = face;
  15406. intersection.barycoord = barycoord;
  15407. }
  15408. return intersection;
  15409. }
  15410. /**
  15411. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15412. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15413. * of the axes.
  15414. *
  15415. * ```js
  15416. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15417. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15418. * const cube = new THREE.Mesh( geometry, material );
  15419. * scene.add( cube );
  15420. * ```
  15421. *
  15422. * @augments BufferGeometry
  15423. */
  15424. class BoxGeometry extends BufferGeometry {
  15425. /**
  15426. * Constructs a new box geometry.
  15427. *
  15428. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15429. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15430. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15431. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15432. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15433. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15434. */
  15435. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15436. super();
  15437. this.type = 'BoxGeometry';
  15438. /**
  15439. * Holds the constructor parameters that have been
  15440. * used to generate the geometry. Any modification
  15441. * after instantiation does not change the geometry.
  15442. *
  15443. * @type {Object}
  15444. */
  15445. this.parameters = {
  15446. width: width,
  15447. height: height,
  15448. depth: depth,
  15449. widthSegments: widthSegments,
  15450. heightSegments: heightSegments,
  15451. depthSegments: depthSegments
  15452. };
  15453. const scope = this;
  15454. // segments
  15455. widthSegments = Math.floor( widthSegments );
  15456. heightSegments = Math.floor( heightSegments );
  15457. depthSegments = Math.floor( depthSegments );
  15458. // buffers
  15459. const indices = [];
  15460. const vertices = [];
  15461. const normals = [];
  15462. const uvs = [];
  15463. // helper variables
  15464. let numberOfVertices = 0;
  15465. let groupStart = 0;
  15466. // build each side of the box geometry
  15467. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15468. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15469. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15470. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15471. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15472. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15473. // build geometry
  15474. this.setIndex( indices );
  15475. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15476. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15477. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15478. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15479. const segmentWidth = width / gridX;
  15480. const segmentHeight = height / gridY;
  15481. const widthHalf = width / 2;
  15482. const heightHalf = height / 2;
  15483. const depthHalf = depth / 2;
  15484. const gridX1 = gridX + 1;
  15485. const gridY1 = gridY + 1;
  15486. let vertexCounter = 0;
  15487. let groupCount = 0;
  15488. const vector = new Vector3();
  15489. // generate vertices, normals and uvs
  15490. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15491. const y = iy * segmentHeight - heightHalf;
  15492. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15493. const x = ix * segmentWidth - widthHalf;
  15494. // set values to correct vector component
  15495. vector[ u ] = x * udir;
  15496. vector[ v ] = y * vdir;
  15497. vector[ w ] = depthHalf;
  15498. // now apply vector to vertex buffer
  15499. vertices.push( vector.x, vector.y, vector.z );
  15500. // set values to correct vector component
  15501. vector[ u ] = 0;
  15502. vector[ v ] = 0;
  15503. vector[ w ] = depth > 0 ? 1 : -1;
  15504. // now apply vector to normal buffer
  15505. normals.push( vector.x, vector.y, vector.z );
  15506. // uvs
  15507. uvs.push( ix / gridX );
  15508. uvs.push( 1 - ( iy / gridY ) );
  15509. // counters
  15510. vertexCounter += 1;
  15511. }
  15512. }
  15513. // indices
  15514. // 1. you need three indices to draw a single face
  15515. // 2. a single segment consists of two faces
  15516. // 3. so we need to generate six (2*3) indices per segment
  15517. for ( let iy = 0; iy < gridY; iy ++ ) {
  15518. for ( let ix = 0; ix < gridX; ix ++ ) {
  15519. const a = numberOfVertices + ix + gridX1 * iy;
  15520. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15521. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15522. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15523. // faces
  15524. indices.push( a, b, d );
  15525. indices.push( b, c, d );
  15526. // increase counter
  15527. groupCount += 6;
  15528. }
  15529. }
  15530. // add a group to the geometry. this will ensure multi material support
  15531. scope.addGroup( groupStart, groupCount, materialIndex );
  15532. // calculate new start value for groups
  15533. groupStart += groupCount;
  15534. // update total number of vertices
  15535. numberOfVertices += vertexCounter;
  15536. }
  15537. }
  15538. copy( source ) {
  15539. super.copy( source );
  15540. this.parameters = Object.assign( {}, source.parameters );
  15541. return this;
  15542. }
  15543. /**
  15544. * Factory method for creating an instance of this class from the given
  15545. * JSON object.
  15546. *
  15547. * @param {Object} data - A JSON object representing the serialized geometry.
  15548. * @return {BoxGeometry} A new instance.
  15549. */
  15550. static fromJSON( data ) {
  15551. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15552. }
  15553. }
  15554. // Uniform Utilities
  15555. function cloneUniforms( src ) {
  15556. const dst = {};
  15557. for ( const u in src ) {
  15558. dst[ u ] = {};
  15559. for ( const p in src[ u ] ) {
  15560. const property = src[ u ][ p ];
  15561. if ( property && ( property.isColor ||
  15562. property.isMatrix3 || property.isMatrix4 ||
  15563. property.isVector2 || property.isVector3 || property.isVector4 ||
  15564. property.isTexture || property.isQuaternion ) ) {
  15565. if ( property.isRenderTargetTexture ) {
  15566. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15567. dst[ u ][ p ] = null;
  15568. } else {
  15569. dst[ u ][ p ] = property.clone();
  15570. }
  15571. } else if ( Array.isArray( property ) ) {
  15572. dst[ u ][ p ] = property.slice();
  15573. } else {
  15574. dst[ u ][ p ] = property;
  15575. }
  15576. }
  15577. }
  15578. return dst;
  15579. }
  15580. function mergeUniforms( uniforms ) {
  15581. const merged = {};
  15582. for ( let u = 0; u < uniforms.length; u ++ ) {
  15583. const tmp = cloneUniforms( uniforms[ u ] );
  15584. for ( const p in tmp ) {
  15585. merged[ p ] = tmp[ p ];
  15586. }
  15587. }
  15588. return merged;
  15589. }
  15590. function cloneUniformsGroups( src ) {
  15591. const dst = [];
  15592. for ( let u = 0; u < src.length; u ++ ) {
  15593. dst.push( src[ u ].clone() );
  15594. }
  15595. return dst;
  15596. }
  15597. function getUnlitUniformColorSpace( renderer ) {
  15598. const currentRenderTarget = renderer.getRenderTarget();
  15599. if ( currentRenderTarget === null ) {
  15600. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15601. return renderer.outputColorSpace;
  15602. }
  15603. // https://github.com/mrdoob/three.js/issues/27868
  15604. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15605. return currentRenderTarget.texture.colorSpace;
  15606. }
  15607. return ColorManagement.workingColorSpace;
  15608. }
  15609. // Legacy
  15610. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15611. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15612. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15613. /**
  15614. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15615. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15616. * effect not included with any of the built-in materials.
  15617. *
  15618. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15619. *
  15620. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15621. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15622. * you don't want that, use {@link RawShaderMaterial} instead.
  15623. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15624. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15625. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15626. * - The loop has to be [normalized]{@link https://en.wikipedia.org/wiki/Normalized_loop}.
  15627. * - The loop variable has to be *i*.
  15628. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15629. * value of *i* for the given iteration and can be used in preprocessor
  15630. * statements.
  15631. *
  15632. * ```js
  15633. * const material = new THREE.ShaderMaterial( {
  15634. * uniforms: {
  15635. * time: { value: 1.0 },
  15636. * resolution: { value: new THREE.Vector2() }
  15637. * },
  15638. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15639. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15640. * } );
  15641. * ```
  15642. *
  15643. * @augments Material
  15644. */
  15645. class ShaderMaterial extends Material {
  15646. /**
  15647. * Constructs a new shader material.
  15648. *
  15649. * @param {Object} [parameters] - An object with one or more properties
  15650. * defining the material's appearance. Any property of the material
  15651. * (including any property from inherited materials) can be passed
  15652. * in here. Color values can be passed any type of value accepted
  15653. * by {@link Color#set}.
  15654. */
  15655. constructor( parameters ) {
  15656. super();
  15657. /**
  15658. * This flag can be used for type testing.
  15659. *
  15660. * @type {boolean}
  15661. * @readonly
  15662. * @default true
  15663. */
  15664. this.isShaderMaterial = true;
  15665. this.type = 'ShaderMaterial';
  15666. /**
  15667. * Defines custom constants using `#define` directives within the GLSL code
  15668. * for both the vertex shader and the fragment shader; each key/value pair
  15669. * yields another directive.
  15670. * ```js
  15671. * defines: {
  15672. * FOO: 15,
  15673. * BAR: true
  15674. * }
  15675. * ```
  15676. * Yields the lines:
  15677. * ```
  15678. * #define FOO 15
  15679. * #define BAR true
  15680. * ```
  15681. *
  15682. * @type {Object}
  15683. */
  15684. this.defines = {};
  15685. /**
  15686. * An object of the form:
  15687. * ```js
  15688. * {
  15689. * "uniform1": { value: 1.0 },
  15690. * "uniform2": { value: 2 }
  15691. * }
  15692. * ```
  15693. * specifying the uniforms to be passed to the shader code; keys are uniform
  15694. * names, values are definitions of the form
  15695. * ```
  15696. * {
  15697. * value: 1.0
  15698. * }
  15699. * ```
  15700. * where `value` is the value of the uniform. Names must match the name of
  15701. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15702. * on every frame, so updating the value of the uniform will immediately
  15703. * update the value available to the GLSL code.
  15704. *
  15705. * @type {Object}
  15706. */
  15707. this.uniforms = {};
  15708. /**
  15709. * An array holding uniforms groups for configuring UBOs.
  15710. *
  15711. * @type {Array<UniformsGroup>}
  15712. */
  15713. this.uniformsGroups = [];
  15714. /**
  15715. * Vertex shader GLSL code. This is the actual code for the shader.
  15716. *
  15717. * @type {string}
  15718. */
  15719. this.vertexShader = default_vertex;
  15720. /**
  15721. * Fragment shader GLSL code. This is the actual code for the shader.
  15722. *
  15723. * @type {string}
  15724. */
  15725. this.fragmentShader = default_fragment;
  15726. /**
  15727. * Controls line thickness or lines.
  15728. *
  15729. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15730. * width of one pixel.
  15731. *
  15732. * @type {number}
  15733. * @default 1
  15734. */
  15735. this.linewidth = 1;
  15736. /**
  15737. * Renders the geometry as a wireframe.
  15738. *
  15739. * @type {boolean}
  15740. * @default false
  15741. */
  15742. this.wireframe = false;
  15743. /**
  15744. * Controls the thickness of the wireframe.
  15745. *
  15746. * WebGL and WebGPU ignore this property and always render
  15747. * 1 pixel wide lines.
  15748. *
  15749. * @type {number}
  15750. * @default 1
  15751. */
  15752. this.wireframeLinewidth = 1;
  15753. /**
  15754. * Define whether the material color is affected by global fog settings; `true`
  15755. * to pass fog uniforms to the shader.
  15756. *
  15757. * @type {boolean}
  15758. * @default false
  15759. */
  15760. this.fog = false;
  15761. /**
  15762. * Defines whether this material uses lighting; `true` to pass uniform data
  15763. * related to lighting to this shader.
  15764. *
  15765. * @type {boolean}
  15766. * @default false
  15767. */
  15768. this.lights = false;
  15769. /**
  15770. * Defines whether this material supports clipping; `true` to let the renderer
  15771. * pass the clippingPlanes uniform.
  15772. *
  15773. * @type {boolean}
  15774. * @default false
  15775. */
  15776. this.clipping = false;
  15777. /**
  15778. * Overwritten and set to `true` by default.
  15779. *
  15780. * @type {boolean}
  15781. * @default true
  15782. */
  15783. this.forceSinglePass = true;
  15784. /**
  15785. * This object allows to enable certain WebGL 2 extensions.
  15786. *
  15787. * - clipCullDistance: set to `true` to use vertex shader clipping
  15788. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15789. *
  15790. * @type {{clipCullDistance:false,multiDraw:false}}
  15791. */
  15792. this.extensions = {
  15793. clipCullDistance: false, // set to use vertex shader clipping
  15794. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15795. };
  15796. /**
  15797. * When the rendered geometry doesn't include these attributes but the
  15798. * material does, these default values will be passed to the shaders. This
  15799. * avoids errors when buffer data is missing.
  15800. *
  15801. * - color: [ 1, 1, 1 ]
  15802. * - uv: [ 0, 0 ]
  15803. * - uv1: [ 0, 0 ]
  15804. *
  15805. * @type {Object}
  15806. */
  15807. this.defaultAttributeValues = {
  15808. 'color': [ 1, 1, 1 ],
  15809. 'uv': [ 0, 0 ],
  15810. 'uv1': [ 0, 0 ]
  15811. };
  15812. /**
  15813. * If set, this calls [gl.bindAttribLocation]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation}
  15814. * to bind a generic vertex index to an attribute variable.
  15815. *
  15816. * @type {string|undefined}
  15817. * @default undefined
  15818. */
  15819. this.index0AttributeName = undefined;
  15820. /**
  15821. * Can be used to force a uniform update while changing uniforms in
  15822. * {@link Object3D#onBeforeRender}.
  15823. *
  15824. * @type {boolean}
  15825. * @default false
  15826. */
  15827. this.uniformsNeedUpdate = false;
  15828. /**
  15829. * Defines the GLSL version of custom shader code.
  15830. *
  15831. * @type {?(GLSL1|GLSL3)}
  15832. * @default null
  15833. */
  15834. this.glslVersion = null;
  15835. if ( parameters !== undefined ) {
  15836. this.setValues( parameters );
  15837. }
  15838. }
  15839. copy( source ) {
  15840. super.copy( source );
  15841. this.fragmentShader = source.fragmentShader;
  15842. this.vertexShader = source.vertexShader;
  15843. this.uniforms = cloneUniforms( source.uniforms );
  15844. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15845. this.defines = Object.assign( {}, source.defines );
  15846. this.wireframe = source.wireframe;
  15847. this.wireframeLinewidth = source.wireframeLinewidth;
  15848. this.fog = source.fog;
  15849. this.lights = source.lights;
  15850. this.clipping = source.clipping;
  15851. this.extensions = Object.assign( {}, source.extensions );
  15852. this.glslVersion = source.glslVersion;
  15853. return this;
  15854. }
  15855. toJSON( meta ) {
  15856. const data = super.toJSON( meta );
  15857. data.glslVersion = this.glslVersion;
  15858. data.uniforms = {};
  15859. for ( const name in this.uniforms ) {
  15860. const uniform = this.uniforms[ name ];
  15861. const value = uniform.value;
  15862. if ( value && value.isTexture ) {
  15863. data.uniforms[ name ] = {
  15864. type: 't',
  15865. value: value.toJSON( meta ).uuid
  15866. };
  15867. } else if ( value && value.isColor ) {
  15868. data.uniforms[ name ] = {
  15869. type: 'c',
  15870. value: value.getHex()
  15871. };
  15872. } else if ( value && value.isVector2 ) {
  15873. data.uniforms[ name ] = {
  15874. type: 'v2',
  15875. value: value.toArray()
  15876. };
  15877. } else if ( value && value.isVector3 ) {
  15878. data.uniforms[ name ] = {
  15879. type: 'v3',
  15880. value: value.toArray()
  15881. };
  15882. } else if ( value && value.isVector4 ) {
  15883. data.uniforms[ name ] = {
  15884. type: 'v4',
  15885. value: value.toArray()
  15886. };
  15887. } else if ( value && value.isMatrix3 ) {
  15888. data.uniforms[ name ] = {
  15889. type: 'm3',
  15890. value: value.toArray()
  15891. };
  15892. } else if ( value && value.isMatrix4 ) {
  15893. data.uniforms[ name ] = {
  15894. type: 'm4',
  15895. value: value.toArray()
  15896. };
  15897. } else {
  15898. data.uniforms[ name ] = {
  15899. value: value
  15900. };
  15901. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15902. }
  15903. }
  15904. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15905. data.vertexShader = this.vertexShader;
  15906. data.fragmentShader = this.fragmentShader;
  15907. data.lights = this.lights;
  15908. data.clipping = this.clipping;
  15909. const extensions = {};
  15910. for ( const key in this.extensions ) {
  15911. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15912. }
  15913. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15914. return data;
  15915. }
  15916. }
  15917. /**
  15918. * Abstract base class for cameras. This class should always be inherited
  15919. * when you build a new camera.
  15920. *
  15921. * @abstract
  15922. * @augments Object3D
  15923. */
  15924. class Camera extends Object3D {
  15925. /**
  15926. * Constructs a new camera.
  15927. */
  15928. constructor() {
  15929. super();
  15930. /**
  15931. * This flag can be used for type testing.
  15932. *
  15933. * @type {boolean}
  15934. * @readonly
  15935. * @default true
  15936. */
  15937. this.isCamera = true;
  15938. this.type = 'Camera';
  15939. /**
  15940. * The inverse of the camera's world matrix.
  15941. *
  15942. * @type {Matrix4}
  15943. */
  15944. this.matrixWorldInverse = new Matrix4();
  15945. /**
  15946. * The camera's projection matrix.
  15947. *
  15948. * @type {Matrix4}
  15949. */
  15950. this.projectionMatrix = new Matrix4();
  15951. /**
  15952. * The inverse of the camera's projection matrix.
  15953. *
  15954. * @type {Matrix4}
  15955. */
  15956. this.projectionMatrixInverse = new Matrix4();
  15957. /**
  15958. * The coordinate system in which the camera is used.
  15959. *
  15960. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  15961. */
  15962. this.coordinateSystem = WebGLCoordinateSystem;
  15963. this._reversedDepth = false;
  15964. }
  15965. /**
  15966. * The flag that indicates whether the camera uses a reversed depth buffer.
  15967. *
  15968. * @type {boolean}
  15969. * @default false
  15970. */
  15971. get reversedDepth() {
  15972. return this._reversedDepth;
  15973. }
  15974. copy( source, recursive ) {
  15975. super.copy( source, recursive );
  15976. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  15977. this.projectionMatrix.copy( source.projectionMatrix );
  15978. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  15979. this.coordinateSystem = source.coordinateSystem;
  15980. return this;
  15981. }
  15982. /**
  15983. * Returns a vector representing the ("look") direction of the 3D object in world space.
  15984. *
  15985. * This method is overwritten since cameras have a different forward vector compared to other
  15986. * 3D objects. A camera looks down its local, negative z-axis by default.
  15987. *
  15988. * @param {Vector3} target - The target vector the result is stored to.
  15989. * @return {Vector3} The 3D object's direction in world space.
  15990. */
  15991. getWorldDirection( target ) {
  15992. return super.getWorldDirection( target ).negate();
  15993. }
  15994. updateMatrixWorld( force ) {
  15995. super.updateMatrixWorld( force );
  15996. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  15997. }
  15998. updateWorldMatrix( updateParents, updateChildren ) {
  15999. super.updateWorldMatrix( updateParents, updateChildren );
  16000. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16001. }
  16002. clone() {
  16003. return new this.constructor().copy( this );
  16004. }
  16005. }
  16006. const _v3$1 = /*@__PURE__*/ new Vector3();
  16007. const _minTarget = /*@__PURE__*/ new Vector2();
  16008. const _maxTarget = /*@__PURE__*/ new Vector2();
  16009. /**
  16010. * Camera that uses [perspective projection]{@link https://en.wikipedia.org/wiki/Perspective_(graphical)}.
  16011. *
  16012. * This projection mode is designed to mimic the way the human eye sees. It
  16013. * is the most common projection mode used for rendering a 3D scene.
  16014. *
  16015. * ```js
  16016. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16017. * scene.add( camera );
  16018. * ```
  16019. *
  16020. * @augments Camera
  16021. */
  16022. class PerspectiveCamera extends Camera {
  16023. /**
  16024. * Constructs a new perspective camera.
  16025. *
  16026. * @param {number} [fov=50] - The vertical field of view.
  16027. * @param {number} [aspect=1] - The aspect ratio.
  16028. * @param {number} [near=0.1] - The camera's near plane.
  16029. * @param {number} [far=2000] - The camera's far plane.
  16030. */
  16031. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16032. super();
  16033. /**
  16034. * This flag can be used for type testing.
  16035. *
  16036. * @type {boolean}
  16037. * @readonly
  16038. * @default true
  16039. */
  16040. this.isPerspectiveCamera = true;
  16041. this.type = 'PerspectiveCamera';
  16042. /**
  16043. * The vertical field of view, from bottom to top of view,
  16044. * in degrees.
  16045. *
  16046. * @type {number}
  16047. * @default 50
  16048. */
  16049. this.fov = fov;
  16050. /**
  16051. * The zoom factor of the camera.
  16052. *
  16053. * @type {number}
  16054. * @default 1
  16055. */
  16056. this.zoom = 1;
  16057. /**
  16058. * The camera's near plane. The valid range is greater than `0`
  16059. * and less than the current value of {@link PerspectiveCamera#far}.
  16060. *
  16061. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16062. * valid value for a perspective camera's near plane.
  16063. *
  16064. * @type {number}
  16065. * @default 0.1
  16066. */
  16067. this.near = near;
  16068. /**
  16069. * The camera's far plane. Must be greater than the
  16070. * current value of {@link PerspectiveCamera#near}.
  16071. *
  16072. * @type {number}
  16073. * @default 2000
  16074. */
  16075. this.far = far;
  16076. /**
  16077. * Object distance used for stereoscopy and depth-of-field effects. This
  16078. * parameter does not influence the projection matrix unless a
  16079. * {@link StereoCamera} is being used.
  16080. *
  16081. * @type {number}
  16082. * @default 10
  16083. */
  16084. this.focus = 10;
  16085. /**
  16086. * The aspect ratio, usually the canvas width / canvas height.
  16087. *
  16088. * @type {number}
  16089. * @default 1
  16090. */
  16091. this.aspect = aspect;
  16092. /**
  16093. * Represents the frustum window specification. This property should not be edited
  16094. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16095. *
  16096. * @type {?Object}
  16097. * @default null
  16098. */
  16099. this.view = null;
  16100. /**
  16101. * Film size used for the larger axis. Default is `35` (millimeters). This
  16102. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16103. * is set to a nonzero value.
  16104. *
  16105. * @type {number}
  16106. * @default 35
  16107. */
  16108. this.filmGauge = 35;
  16109. /**
  16110. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16111. *
  16112. * @type {number}
  16113. * @default 0
  16114. */
  16115. this.filmOffset = 0;
  16116. this.updateProjectionMatrix();
  16117. }
  16118. copy( source, recursive ) {
  16119. super.copy( source, recursive );
  16120. this.fov = source.fov;
  16121. this.zoom = source.zoom;
  16122. this.near = source.near;
  16123. this.far = source.far;
  16124. this.focus = source.focus;
  16125. this.aspect = source.aspect;
  16126. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16127. this.filmGauge = source.filmGauge;
  16128. this.filmOffset = source.filmOffset;
  16129. return this;
  16130. }
  16131. /**
  16132. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16133. *
  16134. * The default film gauge is 35, so that the focal length can be specified for
  16135. * a 35mm (full frame) camera.
  16136. *
  16137. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16138. */
  16139. setFocalLength( focalLength ) {
  16140. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16141. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16142. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16143. this.updateProjectionMatrix();
  16144. }
  16145. /**
  16146. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16147. * {@link PerspectiveCamera#filmGauge}.
  16148. *
  16149. * @return {number} The computed focal length.
  16150. */
  16151. getFocalLength() {
  16152. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16153. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16154. }
  16155. /**
  16156. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16157. *
  16158. * @return {number} The effective FOV.
  16159. */
  16160. getEffectiveFOV() {
  16161. return RAD2DEG * 2 * Math.atan(
  16162. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16163. }
  16164. /**
  16165. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16166. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16167. *
  16168. * @return {number} The film width.
  16169. */
  16170. getFilmWidth() {
  16171. // film not completely covered in portrait format (aspect < 1)
  16172. return this.filmGauge * Math.min( this.aspect, 1 );
  16173. }
  16174. /**
  16175. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16176. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16177. *
  16178. * @return {number} The film width.
  16179. */
  16180. getFilmHeight() {
  16181. // film not completely covered in landscape format (aspect > 1)
  16182. return this.filmGauge / Math.max( this.aspect, 1 );
  16183. }
  16184. /**
  16185. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16186. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16187. *
  16188. * @param {number} distance - The viewing distance.
  16189. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16190. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16191. */
  16192. getViewBounds( distance, minTarget, maxTarget ) {
  16193. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16194. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16195. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16196. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16197. }
  16198. /**
  16199. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16200. *
  16201. * @param {number} distance - The viewing distance.
  16202. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16203. * @returns {Vector2} The view size.
  16204. */
  16205. getViewSize( distance, target ) {
  16206. this.getViewBounds( distance, _minTarget, _maxTarget );
  16207. return target.subVectors( _maxTarget, _minTarget );
  16208. }
  16209. /**
  16210. * Sets an offset in a larger frustum. This is useful for multi-window or
  16211. * multi-monitor/multi-machine setups.
  16212. *
  16213. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16214. * the monitors are in grid like this
  16215. *```
  16216. * +---+---+---+
  16217. * | A | B | C |
  16218. * +---+---+---+
  16219. * | D | E | F |
  16220. * +---+---+---+
  16221. *```
  16222. * then for each monitor you would call it like this:
  16223. *```js
  16224. * const w = 1920;
  16225. * const h = 1080;
  16226. * const fullWidth = w * 3;
  16227. * const fullHeight = h * 2;
  16228. *
  16229. * // --A--
  16230. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16231. * // --B--
  16232. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16233. * // --C--
  16234. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16235. * // --D--
  16236. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16237. * // --E--
  16238. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16239. * // --F--
  16240. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16241. * ```
  16242. *
  16243. * Note there is no reason monitors have to be the same size or in a grid.
  16244. *
  16245. * @param {number} fullWidth - The full width of multiview setup.
  16246. * @param {number} fullHeight - The full height of multiview setup.
  16247. * @param {number} x - The horizontal offset of the subcamera.
  16248. * @param {number} y - The vertical offset of the subcamera.
  16249. * @param {number} width - The width of subcamera.
  16250. * @param {number} height - The height of subcamera.
  16251. */
  16252. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16253. this.aspect = fullWidth / fullHeight;
  16254. if ( this.view === null ) {
  16255. this.view = {
  16256. enabled: true,
  16257. fullWidth: 1,
  16258. fullHeight: 1,
  16259. offsetX: 0,
  16260. offsetY: 0,
  16261. width: 1,
  16262. height: 1
  16263. };
  16264. }
  16265. this.view.enabled = true;
  16266. this.view.fullWidth = fullWidth;
  16267. this.view.fullHeight = fullHeight;
  16268. this.view.offsetX = x;
  16269. this.view.offsetY = y;
  16270. this.view.width = width;
  16271. this.view.height = height;
  16272. this.updateProjectionMatrix();
  16273. }
  16274. /**
  16275. * Removes the view offset from the projection matrix.
  16276. */
  16277. clearViewOffset() {
  16278. if ( this.view !== null ) {
  16279. this.view.enabled = false;
  16280. }
  16281. this.updateProjectionMatrix();
  16282. }
  16283. /**
  16284. * Updates the camera's projection matrix. Must be called after any change of
  16285. * camera properties.
  16286. */
  16287. updateProjectionMatrix() {
  16288. const near = this.near;
  16289. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16290. let height = 2 * top;
  16291. let width = this.aspect * height;
  16292. let left = -0.5 * width;
  16293. const view = this.view;
  16294. if ( this.view !== null && this.view.enabled ) {
  16295. const fullWidth = view.fullWidth,
  16296. fullHeight = view.fullHeight;
  16297. left += view.offsetX * width / fullWidth;
  16298. top -= view.offsetY * height / fullHeight;
  16299. width *= view.width / fullWidth;
  16300. height *= view.height / fullHeight;
  16301. }
  16302. const skew = this.filmOffset;
  16303. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16304. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16305. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16306. }
  16307. toJSON( meta ) {
  16308. const data = super.toJSON( meta );
  16309. data.object.fov = this.fov;
  16310. data.object.zoom = this.zoom;
  16311. data.object.near = this.near;
  16312. data.object.far = this.far;
  16313. data.object.focus = this.focus;
  16314. data.object.aspect = this.aspect;
  16315. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16316. data.object.filmGauge = this.filmGauge;
  16317. data.object.filmOffset = this.filmOffset;
  16318. return data;
  16319. }
  16320. }
  16321. const fov = -90; // negative fov is not an error
  16322. const aspect = 1;
  16323. /**
  16324. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16325. * cube render target. The render target can then be used as an environment map for rendering
  16326. * realtime reflections in your scene.
  16327. *
  16328. * ```js
  16329. * // Create cube render target
  16330. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16331. *
  16332. * // Create cube camera
  16333. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16334. * scene.add( cubeCamera );
  16335. *
  16336. * // Create car
  16337. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16338. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16339. * scene.add( car );
  16340. *
  16341. * // Update the render target cube
  16342. * car.visible = false;
  16343. * cubeCamera.position.copy( car.position );
  16344. * cubeCamera.update( renderer, scene );
  16345. *
  16346. * // Render the scene
  16347. * car.visible = true;
  16348. * renderer.render( scene, camera );
  16349. * ```
  16350. *
  16351. * @augments Object3D
  16352. */
  16353. class CubeCamera extends Object3D {
  16354. /**
  16355. * Constructs a new cube camera.
  16356. *
  16357. * @param {number} near - The camera's near plane.
  16358. * @param {number} far - The camera's far plane.
  16359. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16360. */
  16361. constructor( near, far, renderTarget ) {
  16362. super();
  16363. this.type = 'CubeCamera';
  16364. /**
  16365. * A reference to the cube render target.
  16366. *
  16367. * @type {WebGLCubeRenderTarget}
  16368. */
  16369. this.renderTarget = renderTarget;
  16370. /**
  16371. * The current active coordinate system.
  16372. *
  16373. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16374. * @default null
  16375. */
  16376. this.coordinateSystem = null;
  16377. /**
  16378. * The current active mipmap level
  16379. *
  16380. * @type {number}
  16381. * @default 0
  16382. */
  16383. this.activeMipmapLevel = 0;
  16384. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16385. cameraPX.layers = this.layers;
  16386. this.add( cameraPX );
  16387. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16388. cameraNX.layers = this.layers;
  16389. this.add( cameraNX );
  16390. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16391. cameraPY.layers = this.layers;
  16392. this.add( cameraPY );
  16393. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16394. cameraNY.layers = this.layers;
  16395. this.add( cameraNY );
  16396. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16397. cameraPZ.layers = this.layers;
  16398. this.add( cameraPZ );
  16399. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16400. cameraNZ.layers = this.layers;
  16401. this.add( cameraNZ );
  16402. }
  16403. /**
  16404. * Must be called when the coordinate system of the cube camera is changed.
  16405. */
  16406. updateCoordinateSystem() {
  16407. const coordinateSystem = this.coordinateSystem;
  16408. const cameras = this.children.concat();
  16409. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16410. for ( const camera of cameras ) this.remove( camera );
  16411. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16412. cameraPX.up.set( 0, 1, 0 );
  16413. cameraPX.lookAt( 1, 0, 0 );
  16414. cameraNX.up.set( 0, 1, 0 );
  16415. cameraNX.lookAt( -1, 0, 0 );
  16416. cameraPY.up.set( 0, 0, -1 );
  16417. cameraPY.lookAt( 0, 1, 0 );
  16418. cameraNY.up.set( 0, 0, 1 );
  16419. cameraNY.lookAt( 0, -1, 0 );
  16420. cameraPZ.up.set( 0, 1, 0 );
  16421. cameraPZ.lookAt( 0, 0, 1 );
  16422. cameraNZ.up.set( 0, 1, 0 );
  16423. cameraNZ.lookAt( 0, 0, -1 );
  16424. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16425. cameraPX.up.set( 0, -1, 0 );
  16426. cameraPX.lookAt( -1, 0, 0 );
  16427. cameraNX.up.set( 0, -1, 0 );
  16428. cameraNX.lookAt( 1, 0, 0 );
  16429. cameraPY.up.set( 0, 0, 1 );
  16430. cameraPY.lookAt( 0, 1, 0 );
  16431. cameraNY.up.set( 0, 0, -1 );
  16432. cameraNY.lookAt( 0, -1, 0 );
  16433. cameraPZ.up.set( 0, -1, 0 );
  16434. cameraPZ.lookAt( 0, 0, 1 );
  16435. cameraNZ.up.set( 0, -1, 0 );
  16436. cameraNZ.lookAt( 0, 0, -1 );
  16437. } else {
  16438. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16439. }
  16440. for ( const camera of cameras ) {
  16441. this.add( camera );
  16442. camera.updateMatrixWorld();
  16443. }
  16444. }
  16445. /**
  16446. * Calling this method will render the given scene with the given renderer
  16447. * into the cube render target of the camera.
  16448. *
  16449. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16450. * @param {Scene} scene - The scene to render.
  16451. */
  16452. update( renderer, scene ) {
  16453. if ( this.parent === null ) this.updateMatrixWorld();
  16454. const { renderTarget, activeMipmapLevel } = this;
  16455. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16456. this.coordinateSystem = renderer.coordinateSystem;
  16457. this.updateCoordinateSystem();
  16458. }
  16459. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16460. const currentRenderTarget = renderer.getRenderTarget();
  16461. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16462. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16463. const currentXrEnabled = renderer.xr.enabled;
  16464. renderer.xr.enabled = false;
  16465. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16466. renderTarget.texture.generateMipmaps = false;
  16467. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16468. renderer.render( scene, cameraPX );
  16469. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16470. renderer.render( scene, cameraNX );
  16471. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16472. renderer.render( scene, cameraPY );
  16473. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16474. renderer.render( scene, cameraNY );
  16475. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16476. renderer.render( scene, cameraPZ );
  16477. // mipmaps are generated during the last call of render()
  16478. // at this point, all sides of the cube render target are defined
  16479. renderTarget.texture.generateMipmaps = generateMipmaps;
  16480. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16481. renderer.render( scene, cameraNZ );
  16482. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16483. renderer.xr.enabled = currentXrEnabled;
  16484. renderTarget.texture.needsPMREMUpdate = true;
  16485. }
  16486. }
  16487. /**
  16488. * Creates a cube texture made up of six images.
  16489. *
  16490. * ```js
  16491. * const loader = new THREE.CubeTextureLoader();
  16492. * loader.setPath( 'textures/cube/pisa/' );
  16493. *
  16494. * const textureCube = loader.load( [
  16495. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16496. * ] );
  16497. *
  16498. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16499. * ```
  16500. *
  16501. * @augments Texture
  16502. */
  16503. class CubeTexture extends Texture {
  16504. /**
  16505. * Constructs a new cube texture.
  16506. *
  16507. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16508. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16509. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16510. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16511. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16512. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16513. * @param {number} [format=RGBAFormat] - The texture format.
  16514. * @param {number} [type=UnsignedByteType] - The texture type.
  16515. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16516. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16517. */
  16518. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16519. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16520. /**
  16521. * This flag can be used for type testing.
  16522. *
  16523. * @type {boolean}
  16524. * @readonly
  16525. * @default true
  16526. */
  16527. this.isCubeTexture = true;
  16528. /**
  16529. * If set to `true`, the texture is flipped along the vertical axis when
  16530. * uploaded to the GPU.
  16531. *
  16532. * Overwritten and set to `false` by default.
  16533. *
  16534. * @type {boolean}
  16535. * @default false
  16536. */
  16537. this.flipY = false;
  16538. }
  16539. /**
  16540. * Alias for {@link CubeTexture#image}.
  16541. *
  16542. * @type {Array<Image>}
  16543. */
  16544. get images() {
  16545. return this.image;
  16546. }
  16547. set images( value ) {
  16548. this.image = value;
  16549. }
  16550. }
  16551. /**
  16552. * A cube render target used in context of {@link WebGLRenderer}.
  16553. *
  16554. * @augments WebGLRenderTarget
  16555. */
  16556. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16557. /**
  16558. * Constructs a new cube render target.
  16559. *
  16560. * @param {number} [size=1] - The size of the render target.
  16561. * @param {RenderTarget~Options} [options] - The configuration object.
  16562. */
  16563. constructor( size = 1, options = {} ) {
  16564. super( size, size, options );
  16565. /**
  16566. * This flag can be used for type testing.
  16567. *
  16568. * @type {boolean}
  16569. * @readonly
  16570. * @default true
  16571. */
  16572. this.isWebGLCubeRenderTarget = true;
  16573. const image = { width: size, height: size, depth: 1 };
  16574. const images = [ image, image, image, image, image, image ];
  16575. /**
  16576. * Overwritten with a different texture type.
  16577. *
  16578. * @type {DataArrayTexture}
  16579. */
  16580. this.texture = new CubeTexture( images );
  16581. this._setTextureOptions( options );
  16582. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16583. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16584. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16585. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16586. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16587. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16588. this.texture.isRenderTargetTexture = true;
  16589. }
  16590. /**
  16591. * Converts the given equirectangular texture to a cube map.
  16592. *
  16593. * @param {WebGLRenderer} renderer - The renderer.
  16594. * @param {Texture} texture - The equirectangular texture.
  16595. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16596. */
  16597. fromEquirectangularTexture( renderer, texture ) {
  16598. this.texture.type = texture.type;
  16599. this.texture.colorSpace = texture.colorSpace;
  16600. this.texture.generateMipmaps = texture.generateMipmaps;
  16601. this.texture.minFilter = texture.minFilter;
  16602. this.texture.magFilter = texture.magFilter;
  16603. const shader = {
  16604. uniforms: {
  16605. tEquirect: { value: null },
  16606. },
  16607. vertexShader: /* glsl */`
  16608. varying vec3 vWorldDirection;
  16609. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16610. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16611. }
  16612. void main() {
  16613. vWorldDirection = transformDirection( position, modelMatrix );
  16614. #include <begin_vertex>
  16615. #include <project_vertex>
  16616. }
  16617. `,
  16618. fragmentShader: /* glsl */`
  16619. uniform sampler2D tEquirect;
  16620. varying vec3 vWorldDirection;
  16621. #include <common>
  16622. void main() {
  16623. vec3 direction = normalize( vWorldDirection );
  16624. vec2 sampleUV = equirectUv( direction );
  16625. gl_FragColor = texture2D( tEquirect, sampleUV );
  16626. }
  16627. `
  16628. };
  16629. const geometry = new BoxGeometry( 5, 5, 5 );
  16630. const material = new ShaderMaterial( {
  16631. name: 'CubemapFromEquirect',
  16632. uniforms: cloneUniforms( shader.uniforms ),
  16633. vertexShader: shader.vertexShader,
  16634. fragmentShader: shader.fragmentShader,
  16635. side: BackSide,
  16636. blending: NoBlending
  16637. } );
  16638. material.uniforms.tEquirect.value = texture;
  16639. const mesh = new Mesh( geometry, material );
  16640. const currentMinFilter = texture.minFilter;
  16641. // Avoid blurred poles
  16642. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16643. const camera = new CubeCamera( 1, 10, this );
  16644. camera.update( renderer, mesh );
  16645. texture.minFilter = currentMinFilter;
  16646. mesh.geometry.dispose();
  16647. mesh.material.dispose();
  16648. return this;
  16649. }
  16650. /**
  16651. * Clears this cube render target.
  16652. *
  16653. * @param {WebGLRenderer} renderer - The renderer.
  16654. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16655. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16656. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16657. */
  16658. clear( renderer, color = true, depth = true, stencil = true ) {
  16659. const currentRenderTarget = renderer.getRenderTarget();
  16660. for ( let i = 0; i < 6; i ++ ) {
  16661. renderer.setRenderTarget( this, i );
  16662. renderer.clear( color, depth, stencil );
  16663. }
  16664. renderer.setRenderTarget( currentRenderTarget );
  16665. }
  16666. }
  16667. /**
  16668. * This is almost identical to an {@link Object3D}. Its purpose is to
  16669. * make working with groups of objects syntactically clearer.
  16670. *
  16671. * ```js
  16672. * // Create a group and add the two cubes.
  16673. * // These cubes can now be rotated / scaled etc as a group.
  16674. * const group = new THREE.Group();
  16675. *
  16676. * group.add( meshA );
  16677. * group.add( meshB );
  16678. *
  16679. * scene.add( group );
  16680. * ```
  16681. *
  16682. * @augments Object3D
  16683. */
  16684. class Group extends Object3D {
  16685. constructor() {
  16686. super();
  16687. /**
  16688. * This flag can be used for type testing.
  16689. *
  16690. * @type {boolean}
  16691. * @readonly
  16692. * @default true
  16693. */
  16694. this.isGroup = true;
  16695. this.type = 'Group';
  16696. }
  16697. }
  16698. const _moveEvent = { type: 'move' };
  16699. /**
  16700. * Class for representing a XR controller with its
  16701. * different coordinate systems.
  16702. *
  16703. * @private
  16704. */
  16705. class WebXRController {
  16706. /**
  16707. * Constructs a new XR controller.
  16708. */
  16709. constructor() {
  16710. /**
  16711. * A group representing the target ray space
  16712. * of the XR controller.
  16713. *
  16714. * @private
  16715. * @type {?Group}
  16716. * @default null
  16717. */
  16718. this._targetRay = null;
  16719. /**
  16720. * A group representing the grip space
  16721. * of the XR controller.
  16722. *
  16723. * @private
  16724. * @type {?Group}
  16725. * @default null
  16726. */
  16727. this._grip = null;
  16728. /**
  16729. * A group representing the hand space
  16730. * of the XR controller.
  16731. *
  16732. * @private
  16733. * @type {?Group}
  16734. * @default null
  16735. */
  16736. this._hand = null;
  16737. }
  16738. /**
  16739. * Returns a group representing the hand space of the XR controller.
  16740. *
  16741. * @return {Group} A group representing the hand space of the XR controller.
  16742. */
  16743. getHandSpace() {
  16744. if ( this._hand === null ) {
  16745. this._hand = new Group();
  16746. this._hand.matrixAutoUpdate = false;
  16747. this._hand.visible = false;
  16748. this._hand.joints = {};
  16749. this._hand.inputState = { pinching: false };
  16750. }
  16751. return this._hand;
  16752. }
  16753. /**
  16754. * Returns a group representing the target ray space of the XR controller.
  16755. *
  16756. * @return {Group} A group representing the target ray space of the XR controller.
  16757. */
  16758. getTargetRaySpace() {
  16759. if ( this._targetRay === null ) {
  16760. this._targetRay = new Group();
  16761. this._targetRay.matrixAutoUpdate = false;
  16762. this._targetRay.visible = false;
  16763. this._targetRay.hasLinearVelocity = false;
  16764. this._targetRay.linearVelocity = new Vector3();
  16765. this._targetRay.hasAngularVelocity = false;
  16766. this._targetRay.angularVelocity = new Vector3();
  16767. }
  16768. return this._targetRay;
  16769. }
  16770. /**
  16771. * Returns a group representing the grip space of the XR controller.
  16772. *
  16773. * @return {Group} A group representing the grip space of the XR controller.
  16774. */
  16775. getGripSpace() {
  16776. if ( this._grip === null ) {
  16777. this._grip = new Group();
  16778. this._grip.matrixAutoUpdate = false;
  16779. this._grip.visible = false;
  16780. this._grip.hasLinearVelocity = false;
  16781. this._grip.linearVelocity = new Vector3();
  16782. this._grip.hasAngularVelocity = false;
  16783. this._grip.angularVelocity = new Vector3();
  16784. }
  16785. return this._grip;
  16786. }
  16787. /**
  16788. * Dispatches the given event to the groups representing
  16789. * the different coordinate spaces of the XR controller.
  16790. *
  16791. * @param {Object} event - The event to dispatch.
  16792. * @return {WebXRController} A reference to this instance.
  16793. */
  16794. dispatchEvent( event ) {
  16795. if ( this._targetRay !== null ) {
  16796. this._targetRay.dispatchEvent( event );
  16797. }
  16798. if ( this._grip !== null ) {
  16799. this._grip.dispatchEvent( event );
  16800. }
  16801. if ( this._hand !== null ) {
  16802. this._hand.dispatchEvent( event );
  16803. }
  16804. return this;
  16805. }
  16806. /**
  16807. * Connects the controller with the given XR input source.
  16808. *
  16809. * @param {XRInputSource} inputSource - The input source.
  16810. * @return {WebXRController} A reference to this instance.
  16811. */
  16812. connect( inputSource ) {
  16813. if ( inputSource && inputSource.hand ) {
  16814. const hand = this._hand;
  16815. if ( hand ) {
  16816. for ( const inputjoint of inputSource.hand.values() ) {
  16817. // Initialize hand with joints when connected
  16818. this._getHandJoint( hand, inputjoint );
  16819. }
  16820. }
  16821. }
  16822. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16823. return this;
  16824. }
  16825. /**
  16826. * Disconnects the controller from the given XR input source.
  16827. *
  16828. * @param {XRInputSource} inputSource - The input source.
  16829. * @return {WebXRController} A reference to this instance.
  16830. */
  16831. disconnect( inputSource ) {
  16832. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16833. if ( this._targetRay !== null ) {
  16834. this._targetRay.visible = false;
  16835. }
  16836. if ( this._grip !== null ) {
  16837. this._grip.visible = false;
  16838. }
  16839. if ( this._hand !== null ) {
  16840. this._hand.visible = false;
  16841. }
  16842. return this;
  16843. }
  16844. /**
  16845. * Updates the controller with the given input source, XR frame and reference space.
  16846. * This updates the transformations of the groups that represent the different
  16847. * coordinate systems of the controller.
  16848. *
  16849. * @param {XRInputSource} inputSource - The input source.
  16850. * @param {XRFrame} frame - The XR frame.
  16851. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16852. * @return {WebXRController} A reference to this instance.
  16853. */
  16854. update( inputSource, frame, referenceSpace ) {
  16855. let inputPose = null;
  16856. let gripPose = null;
  16857. let handPose = null;
  16858. const targetRay = this._targetRay;
  16859. const grip = this._grip;
  16860. const hand = this._hand;
  16861. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16862. if ( hand && inputSource.hand ) {
  16863. handPose = true;
  16864. for ( const inputjoint of inputSource.hand.values() ) {
  16865. // Update the joints groups with the XRJoint poses
  16866. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16867. // The transform of this joint will be updated with the joint pose on each frame
  16868. const joint = this._getHandJoint( hand, inputjoint );
  16869. if ( jointPose !== null ) {
  16870. joint.matrix.fromArray( jointPose.transform.matrix );
  16871. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16872. joint.matrixWorldNeedsUpdate = true;
  16873. joint.jointRadius = jointPose.radius;
  16874. }
  16875. joint.visible = jointPose !== null;
  16876. }
  16877. // Custom events
  16878. // Check pinchz
  16879. const indexTip = hand.joints[ 'index-finger-tip' ];
  16880. const thumbTip = hand.joints[ 'thumb-tip' ];
  16881. const distance = indexTip.position.distanceTo( thumbTip.position );
  16882. const distanceToPinch = 0.02;
  16883. const threshold = 0.005;
  16884. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16885. hand.inputState.pinching = false;
  16886. this.dispatchEvent( {
  16887. type: 'pinchend',
  16888. handedness: inputSource.handedness,
  16889. target: this
  16890. } );
  16891. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16892. hand.inputState.pinching = true;
  16893. this.dispatchEvent( {
  16894. type: 'pinchstart',
  16895. handedness: inputSource.handedness,
  16896. target: this
  16897. } );
  16898. }
  16899. } else {
  16900. if ( grip !== null && inputSource.gripSpace ) {
  16901. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16902. if ( gripPose !== null ) {
  16903. grip.matrix.fromArray( gripPose.transform.matrix );
  16904. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16905. grip.matrixWorldNeedsUpdate = true;
  16906. if ( gripPose.linearVelocity ) {
  16907. grip.hasLinearVelocity = true;
  16908. grip.linearVelocity.copy( gripPose.linearVelocity );
  16909. } else {
  16910. grip.hasLinearVelocity = false;
  16911. }
  16912. if ( gripPose.angularVelocity ) {
  16913. grip.hasAngularVelocity = true;
  16914. grip.angularVelocity.copy( gripPose.angularVelocity );
  16915. } else {
  16916. grip.hasAngularVelocity = false;
  16917. }
  16918. }
  16919. }
  16920. }
  16921. if ( targetRay !== null ) {
  16922. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  16923. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  16924. if ( inputPose === null && gripPose !== null ) {
  16925. inputPose = gripPose;
  16926. }
  16927. if ( inputPose !== null ) {
  16928. targetRay.matrix.fromArray( inputPose.transform.matrix );
  16929. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  16930. targetRay.matrixWorldNeedsUpdate = true;
  16931. if ( inputPose.linearVelocity ) {
  16932. targetRay.hasLinearVelocity = true;
  16933. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  16934. } else {
  16935. targetRay.hasLinearVelocity = false;
  16936. }
  16937. if ( inputPose.angularVelocity ) {
  16938. targetRay.hasAngularVelocity = true;
  16939. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  16940. } else {
  16941. targetRay.hasAngularVelocity = false;
  16942. }
  16943. this.dispatchEvent( _moveEvent );
  16944. }
  16945. }
  16946. }
  16947. if ( targetRay !== null ) {
  16948. targetRay.visible = ( inputPose !== null );
  16949. }
  16950. if ( grip !== null ) {
  16951. grip.visible = ( gripPose !== null );
  16952. }
  16953. if ( hand !== null ) {
  16954. hand.visible = ( handPose !== null );
  16955. }
  16956. return this;
  16957. }
  16958. /**
  16959. * Returns a group representing the hand joint for the given input joint.
  16960. *
  16961. * @private
  16962. * @param {Group} hand - The group representing the hand space.
  16963. * @param {XRJointSpace} inputjoint - The hand joint data.
  16964. * @return {Group} A group representing the hand joint for the given input joint.
  16965. */
  16966. _getHandJoint( hand, inputjoint ) {
  16967. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  16968. const joint = new Group();
  16969. joint.matrixAutoUpdate = false;
  16970. joint.visible = false;
  16971. hand.joints[ inputjoint.jointName ] = joint;
  16972. hand.add( joint );
  16973. }
  16974. return hand.joints[ inputjoint.jointName ];
  16975. }
  16976. }
  16977. /**
  16978. * This class can be used to define an exponential squared fog,
  16979. * which gives a clear view near the camera and a faster than exponentially
  16980. * densening fog farther from the camera.
  16981. *
  16982. * ```js
  16983. * const scene = new THREE.Scene();
  16984. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  16985. * ```
  16986. */
  16987. class FogExp2 {
  16988. /**
  16989. * Constructs a new fog.
  16990. *
  16991. * @param {number|Color} color - The fog's color.
  16992. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  16993. */
  16994. constructor( color, density = 0.00025 ) {
  16995. /**
  16996. * This flag can be used for type testing.
  16997. *
  16998. * @type {boolean}
  16999. * @readonly
  17000. * @default true
  17001. */
  17002. this.isFogExp2 = true;
  17003. /**
  17004. * The name of the fog.
  17005. *
  17006. * @type {string}
  17007. */
  17008. this.name = '';
  17009. /**
  17010. * The fog's color.
  17011. *
  17012. * @type {Color}
  17013. */
  17014. this.color = new Color( color );
  17015. /**
  17016. * Defines how fast the fog will grow dense.
  17017. *
  17018. * @type {number}
  17019. * @default 0.00025
  17020. */
  17021. this.density = density;
  17022. }
  17023. /**
  17024. * Returns a new fog with copied values from this instance.
  17025. *
  17026. * @return {FogExp2} A clone of this instance.
  17027. */
  17028. clone() {
  17029. return new FogExp2( this.color, this.density );
  17030. }
  17031. /**
  17032. * Serializes the fog into JSON.
  17033. *
  17034. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17035. * @return {Object} A JSON object representing the serialized fog
  17036. */
  17037. toJSON( /* meta */ ) {
  17038. return {
  17039. type: 'FogExp2',
  17040. name: this.name,
  17041. color: this.color.getHex(),
  17042. density: this.density
  17043. };
  17044. }
  17045. }
  17046. /**
  17047. * This class can be used to define a linear fog that grows linearly denser
  17048. * with the distance.
  17049. *
  17050. * ```js
  17051. * const scene = new THREE.Scene();
  17052. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17053. * ```
  17054. */
  17055. class Fog {
  17056. /**
  17057. * Constructs a new fog.
  17058. *
  17059. * @param {number|Color} color - The fog's color.
  17060. * @param {number} [near=1] - The minimum distance to start applying fog.
  17061. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17062. */
  17063. constructor( color, near = 1, far = 1000 ) {
  17064. /**
  17065. * This flag can be used for type testing.
  17066. *
  17067. * @type {boolean}
  17068. * @readonly
  17069. * @default true
  17070. */
  17071. this.isFog = true;
  17072. /**
  17073. * The name of the fog.
  17074. *
  17075. * @type {string}
  17076. */
  17077. this.name = '';
  17078. /**
  17079. * The fog's color.
  17080. *
  17081. * @type {Color}
  17082. */
  17083. this.color = new Color( color );
  17084. /**
  17085. * The minimum distance to start applying fog. Objects that are less than
  17086. * `near` units from the active camera won't be affected by fog.
  17087. *
  17088. * @type {number}
  17089. * @default 1
  17090. */
  17091. this.near = near;
  17092. /**
  17093. * The maximum distance at which fog stops being calculated and applied.
  17094. * Objects that are more than `far` units away from the active camera won't
  17095. * be affected by fog.
  17096. *
  17097. * @type {number}
  17098. * @default 1000
  17099. */
  17100. this.far = far;
  17101. }
  17102. /**
  17103. * Returns a new fog with copied values from this instance.
  17104. *
  17105. * @return {Fog} A clone of this instance.
  17106. */
  17107. clone() {
  17108. return new Fog( this.color, this.near, this.far );
  17109. }
  17110. /**
  17111. * Serializes the fog into JSON.
  17112. *
  17113. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17114. * @return {Object} A JSON object representing the serialized fog
  17115. */
  17116. toJSON( /* meta */ ) {
  17117. return {
  17118. type: 'Fog',
  17119. name: this.name,
  17120. color: this.color.getHex(),
  17121. near: this.near,
  17122. far: this.far
  17123. };
  17124. }
  17125. }
  17126. /**
  17127. * Scenes allow you to set up what is to be rendered and where by three.js.
  17128. * This is where you place 3D objects like meshes, lines or lights.
  17129. *
  17130. * @augments Object3D
  17131. */
  17132. class Scene extends Object3D {
  17133. /**
  17134. * Constructs a new scene.
  17135. */
  17136. constructor() {
  17137. super();
  17138. /**
  17139. * This flag can be used for type testing.
  17140. *
  17141. * @type {boolean}
  17142. * @readonly
  17143. * @default true
  17144. */
  17145. this.isScene = true;
  17146. this.type = 'Scene';
  17147. /**
  17148. * Defines the background of the scene. Valid inputs are:
  17149. *
  17150. * - A color for defining a uniform colored background.
  17151. * - A texture for defining a (flat) textured background.
  17152. * - Cube textures or equirectangular textures for defining a skybox.
  17153. *
  17154. * @type {?(Color|Texture)}
  17155. * @default null
  17156. */
  17157. this.background = null;
  17158. /**
  17159. * Sets the environment map for all physical materials in the scene. However,
  17160. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17161. * material property.
  17162. *
  17163. * @type {?Texture}
  17164. * @default null
  17165. */
  17166. this.environment = null;
  17167. /**
  17168. * A fog instance defining the type of fog that affects everything
  17169. * rendered in the scene.
  17170. *
  17171. * @type {?(Fog|FogExp2)}
  17172. * @default null
  17173. */
  17174. this.fog = null;
  17175. /**
  17176. * Sets the blurriness of the background. Only influences environment maps
  17177. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17178. * and `1`.
  17179. *
  17180. * @type {number}
  17181. * @default 0
  17182. */
  17183. this.backgroundBlurriness = 0;
  17184. /**
  17185. * Attenuates the color of the background. Only applies to background textures.
  17186. *
  17187. * @type {number}
  17188. * @default 1
  17189. */
  17190. this.backgroundIntensity = 1;
  17191. /**
  17192. * The rotation of the background in radians. Only influences environment maps
  17193. * assigned to {@link Scene#background}.
  17194. *
  17195. * @type {Euler}
  17196. * @default (0,0,0)
  17197. */
  17198. this.backgroundRotation = new Euler();
  17199. /**
  17200. * Attenuates the color of the environment. Only influences environment maps
  17201. * assigned to {@link Scene#environment}.
  17202. *
  17203. * @type {number}
  17204. * @default 1
  17205. */
  17206. this.environmentIntensity = 1;
  17207. /**
  17208. * The rotation of the environment map in radians. Only influences physical materials
  17209. * in the scene when {@link Scene#environment} is used.
  17210. *
  17211. * @type {Euler}
  17212. * @default (0,0,0)
  17213. */
  17214. this.environmentRotation = new Euler();
  17215. /**
  17216. * Forces everything in the scene to be rendered with the defined material. It is possible
  17217. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17218. *
  17219. * @type {?Material}
  17220. * @default null
  17221. */
  17222. this.overrideMaterial = null;
  17223. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17224. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17225. }
  17226. }
  17227. copy( source, recursive ) {
  17228. super.copy( source, recursive );
  17229. if ( source.background !== null ) this.background = source.background.clone();
  17230. if ( source.environment !== null ) this.environment = source.environment.clone();
  17231. if ( source.fog !== null ) this.fog = source.fog.clone();
  17232. this.backgroundBlurriness = source.backgroundBlurriness;
  17233. this.backgroundIntensity = source.backgroundIntensity;
  17234. this.backgroundRotation.copy( source.backgroundRotation );
  17235. this.environmentIntensity = source.environmentIntensity;
  17236. this.environmentRotation.copy( source.environmentRotation );
  17237. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17238. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17239. return this;
  17240. }
  17241. toJSON( meta ) {
  17242. const data = super.toJSON( meta );
  17243. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17244. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17245. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17246. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17247. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17248. data.object.environmentRotation = this.environmentRotation.toArray();
  17249. return data;
  17250. }
  17251. }
  17252. /**
  17253. * "Interleaved" means that multiple attributes, possibly of different types,
  17254. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17255. *
  17256. * An introduction into interleaved arrays can be found here: [Interleaved array basics]{@link https://blog.tojicode.com/2011/05/interleaved-array-basics.html}
  17257. */
  17258. class InterleavedBuffer {
  17259. /**
  17260. * Constructs a new interleaved buffer.
  17261. *
  17262. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17263. * @param {number} stride - The number of typed-array elements per vertex.
  17264. */
  17265. constructor( array, stride ) {
  17266. /**
  17267. * This flag can be used for type testing.
  17268. *
  17269. * @type {boolean}
  17270. * @readonly
  17271. * @default true
  17272. */
  17273. this.isInterleavedBuffer = true;
  17274. /**
  17275. * A typed array with a shared buffer storing attribute data.
  17276. *
  17277. * @type {TypedArray}
  17278. */
  17279. this.array = array;
  17280. /**
  17281. * The number of typed-array elements per vertex.
  17282. *
  17283. * @type {number}
  17284. */
  17285. this.stride = stride;
  17286. /**
  17287. * The total number of elements in the array
  17288. *
  17289. * @type {number}
  17290. * @readonly
  17291. */
  17292. this.count = array !== undefined ? array.length / stride : 0;
  17293. /**
  17294. * Defines the intended usage pattern of the data store for optimization purposes.
  17295. *
  17296. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17297. * instantiate a new one and set the desired usage before the next render.
  17298. *
  17299. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17300. * @default StaticDrawUsage
  17301. */
  17302. this.usage = StaticDrawUsage;
  17303. /**
  17304. * This can be used to only update some components of stored vectors (for example, just the
  17305. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17306. *
  17307. * @type {Array<Object>}
  17308. */
  17309. this.updateRanges = [];
  17310. /**
  17311. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17312. *
  17313. * @type {number}
  17314. */
  17315. this.version = 0;
  17316. /**
  17317. * The UUID of the interleaved buffer.
  17318. *
  17319. * @type {string}
  17320. * @readonly
  17321. */
  17322. this.uuid = generateUUID();
  17323. }
  17324. /**
  17325. * A callback function that is executed after the renderer has transferred the attribute array
  17326. * data to the GPU.
  17327. */
  17328. onUploadCallback() {}
  17329. /**
  17330. * Flag to indicate that this attribute has changed and should be re-sent to
  17331. * the GPU. Set this to `true` when you modify the value of the array.
  17332. *
  17333. * @type {number}
  17334. * @default false
  17335. * @param {boolean} value
  17336. */
  17337. set needsUpdate( value ) {
  17338. if ( value === true ) this.version ++;
  17339. }
  17340. /**
  17341. * Sets the usage of this interleaved buffer.
  17342. *
  17343. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17344. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17345. */
  17346. setUsage( value ) {
  17347. this.usage = value;
  17348. return this;
  17349. }
  17350. /**
  17351. * Adds a range of data in the data array to be updated on the GPU.
  17352. *
  17353. * @param {number} start - Position at which to start update.
  17354. * @param {number} count - The number of components to update.
  17355. */
  17356. addUpdateRange( start, count ) {
  17357. this.updateRanges.push( { start, count } );
  17358. }
  17359. /**
  17360. * Clears the update ranges.
  17361. */
  17362. clearUpdateRanges() {
  17363. this.updateRanges.length = 0;
  17364. }
  17365. /**
  17366. * Copies the values of the given interleaved buffer to this instance.
  17367. *
  17368. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17369. * @return {InterleavedBuffer} A reference to this instance.
  17370. */
  17371. copy( source ) {
  17372. this.array = new source.array.constructor( source.array );
  17373. this.count = source.count;
  17374. this.stride = source.stride;
  17375. this.usage = source.usage;
  17376. return this;
  17377. }
  17378. /**
  17379. * Copies a vector from the given interleaved buffer to this one. The start
  17380. * and destination position in the attribute buffers are represented by the
  17381. * given indices.
  17382. *
  17383. * @param {number} index1 - The destination index into this interleaved buffer.
  17384. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17385. * @param {number} index2 - The source index into the given interleaved buffer.
  17386. * @return {InterleavedBuffer} A reference to this instance.
  17387. */
  17388. copyAt( index1, interleavedBuffer, index2 ) {
  17389. index1 *= this.stride;
  17390. index2 *= interleavedBuffer.stride;
  17391. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17392. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17393. }
  17394. return this;
  17395. }
  17396. /**
  17397. * Sets the given array data in the interleaved buffer.
  17398. *
  17399. * @param {(TypedArray|Array)} value - The array data to set.
  17400. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17401. * @return {InterleavedBuffer} A reference to this instance.
  17402. */
  17403. set( value, offset = 0 ) {
  17404. this.array.set( value, offset );
  17405. return this;
  17406. }
  17407. /**
  17408. * Returns a new interleaved buffer with copied values from this instance.
  17409. *
  17410. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17411. * @return {InterleavedBuffer} A clone of this instance.
  17412. */
  17413. clone( data ) {
  17414. if ( data.arrayBuffers === undefined ) {
  17415. data.arrayBuffers = {};
  17416. }
  17417. if ( this.array.buffer._uuid === undefined ) {
  17418. this.array.buffer._uuid = generateUUID();
  17419. }
  17420. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17421. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17422. }
  17423. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17424. const ib = new this.constructor( array, this.stride );
  17425. ib.setUsage( this.usage );
  17426. return ib;
  17427. }
  17428. /**
  17429. * Sets the given callback function that is executed after the Renderer has transferred
  17430. * the array data to the GPU. Can be used to perform clean-up operations after
  17431. * the upload when data are not needed anymore on the CPU side.
  17432. *
  17433. * @param {Function} callback - The `onUpload()` callback.
  17434. * @return {InterleavedBuffer} A reference to this instance.
  17435. */
  17436. onUpload( callback ) {
  17437. this.onUploadCallback = callback;
  17438. return this;
  17439. }
  17440. /**
  17441. * Serializes the interleaved buffer into JSON.
  17442. *
  17443. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17444. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17445. */
  17446. toJSON( data ) {
  17447. if ( data.arrayBuffers === undefined ) {
  17448. data.arrayBuffers = {};
  17449. }
  17450. // generate UUID for array buffer if necessary
  17451. if ( this.array.buffer._uuid === undefined ) {
  17452. this.array.buffer._uuid = generateUUID();
  17453. }
  17454. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17455. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17456. }
  17457. //
  17458. return {
  17459. uuid: this.uuid,
  17460. buffer: this.array.buffer._uuid,
  17461. type: this.array.constructor.name,
  17462. stride: this.stride
  17463. };
  17464. }
  17465. }
  17466. const _vector$7 = /*@__PURE__*/ new Vector3();
  17467. /**
  17468. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17469. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17470. * different offsets into the buffer.
  17471. */
  17472. class InterleavedBufferAttribute {
  17473. /**
  17474. * Constructs a new interleaved buffer attribute.
  17475. *
  17476. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17477. * @param {number} itemSize - The item size.
  17478. * @param {number} offset - The attribute offset into the buffer.
  17479. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17480. */
  17481. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17482. /**
  17483. * This flag can be used for type testing.
  17484. *
  17485. * @type {boolean}
  17486. * @readonly
  17487. * @default true
  17488. */
  17489. this.isInterleavedBufferAttribute = true;
  17490. /**
  17491. * The name of the buffer attribute.
  17492. *
  17493. * @type {string}
  17494. */
  17495. this.name = '';
  17496. /**
  17497. * The buffer holding the interleaved data.
  17498. *
  17499. * @type {InterleavedBuffer}
  17500. */
  17501. this.data = interleavedBuffer;
  17502. /**
  17503. * The item size, see {@link BufferAttribute#itemSize}.
  17504. *
  17505. * @type {number}
  17506. */
  17507. this.itemSize = itemSize;
  17508. /**
  17509. * The attribute offset into the buffer.
  17510. *
  17511. * @type {number}
  17512. */
  17513. this.offset = offset;
  17514. /**
  17515. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17516. *
  17517. * @type {InterleavedBuffer}
  17518. */
  17519. this.normalized = normalized;
  17520. }
  17521. /**
  17522. * The item count of this buffer attribute.
  17523. *
  17524. * @type {number}
  17525. * @readonly
  17526. */
  17527. get count() {
  17528. return this.data.count;
  17529. }
  17530. /**
  17531. * The array holding the interleaved buffer attribute data.
  17532. *
  17533. * @type {TypedArray}
  17534. */
  17535. get array() {
  17536. return this.data.array;
  17537. }
  17538. /**
  17539. * Flag to indicate that this attribute has changed and should be re-sent to
  17540. * the GPU. Set this to `true` when you modify the value of the array.
  17541. *
  17542. * @type {number}
  17543. * @default false
  17544. * @param {boolean} value
  17545. */
  17546. set needsUpdate( value ) {
  17547. this.data.needsUpdate = value;
  17548. }
  17549. /**
  17550. * Applies the given 4x4 matrix to the given attribute. Only works with
  17551. * item size `3`.
  17552. *
  17553. * @param {Matrix4} m - The matrix to apply.
  17554. * @return {InterleavedBufferAttribute} A reference to this instance.
  17555. */
  17556. applyMatrix4( m ) {
  17557. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17558. _vector$7.fromBufferAttribute( this, i );
  17559. _vector$7.applyMatrix4( m );
  17560. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17561. }
  17562. return this;
  17563. }
  17564. /**
  17565. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17566. * item size `3`.
  17567. *
  17568. * @param {Matrix3} m - The normal matrix to apply.
  17569. * @return {InterleavedBufferAttribute} A reference to this instance.
  17570. */
  17571. applyNormalMatrix( m ) {
  17572. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17573. _vector$7.fromBufferAttribute( this, i );
  17574. _vector$7.applyNormalMatrix( m );
  17575. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17576. }
  17577. return this;
  17578. }
  17579. /**
  17580. * Applies the given 4x4 matrix to the given attribute. Only works with
  17581. * item size `3` and with direction vectors.
  17582. *
  17583. * @param {Matrix4} m - The matrix to apply.
  17584. * @return {InterleavedBufferAttribute} A reference to this instance.
  17585. */
  17586. transformDirection( m ) {
  17587. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17588. _vector$7.fromBufferAttribute( this, i );
  17589. _vector$7.transformDirection( m );
  17590. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17591. }
  17592. return this;
  17593. }
  17594. /**
  17595. * Returns the given component of the vector at the given index.
  17596. *
  17597. * @param {number} index - The index into the buffer attribute.
  17598. * @param {number} component - The component index.
  17599. * @return {number} The returned value.
  17600. */
  17601. getComponent( index, component ) {
  17602. let value = this.array[ index * this.data.stride + this.offset + component ];
  17603. if ( this.normalized ) value = denormalize( value, this.array );
  17604. return value;
  17605. }
  17606. /**
  17607. * Sets the given value to the given component of the vector at the given index.
  17608. *
  17609. * @param {number} index - The index into the buffer attribute.
  17610. * @param {number} component - The component index.
  17611. * @param {number} value - The value to set.
  17612. * @return {InterleavedBufferAttribute} A reference to this instance.
  17613. */
  17614. setComponent( index, component, value ) {
  17615. if ( this.normalized ) value = normalize( value, this.array );
  17616. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17617. return this;
  17618. }
  17619. /**
  17620. * Sets the x component of the vector at the given index.
  17621. *
  17622. * @param {number} index - The index into the buffer attribute.
  17623. * @param {number} x - The value to set.
  17624. * @return {InterleavedBufferAttribute} A reference to this instance.
  17625. */
  17626. setX( index, x ) {
  17627. if ( this.normalized ) x = normalize( x, this.array );
  17628. this.data.array[ index * this.data.stride + this.offset ] = x;
  17629. return this;
  17630. }
  17631. /**
  17632. * Sets the y component of the vector at the given index.
  17633. *
  17634. * @param {number} index - The index into the buffer attribute.
  17635. * @param {number} y - The value to set.
  17636. * @return {InterleavedBufferAttribute} A reference to this instance.
  17637. */
  17638. setY( index, y ) {
  17639. if ( this.normalized ) y = normalize( y, this.array );
  17640. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17641. return this;
  17642. }
  17643. /**
  17644. * Sets the z component of the vector at the given index.
  17645. *
  17646. * @param {number} index - The index into the buffer attribute.
  17647. * @param {number} z - The value to set.
  17648. * @return {InterleavedBufferAttribute} A reference to this instance.
  17649. */
  17650. setZ( index, z ) {
  17651. if ( this.normalized ) z = normalize( z, this.array );
  17652. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17653. return this;
  17654. }
  17655. /**
  17656. * Sets the w component of the vector at the given index.
  17657. *
  17658. * @param {number} index - The index into the buffer attribute.
  17659. * @param {number} w - The value to set.
  17660. * @return {InterleavedBufferAttribute} A reference to this instance.
  17661. */
  17662. setW( index, w ) {
  17663. if ( this.normalized ) w = normalize( w, this.array );
  17664. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17665. return this;
  17666. }
  17667. /**
  17668. * Returns the x component of the vector at the given index.
  17669. *
  17670. * @param {number} index - The index into the buffer attribute.
  17671. * @return {number} The x component.
  17672. */
  17673. getX( index ) {
  17674. let x = this.data.array[ index * this.data.stride + this.offset ];
  17675. if ( this.normalized ) x = denormalize( x, this.array );
  17676. return x;
  17677. }
  17678. /**
  17679. * Returns the y component of the vector at the given index.
  17680. *
  17681. * @param {number} index - The index into the buffer attribute.
  17682. * @return {number} The y component.
  17683. */
  17684. getY( index ) {
  17685. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17686. if ( this.normalized ) y = denormalize( y, this.array );
  17687. return y;
  17688. }
  17689. /**
  17690. * Returns the z component of the vector at the given index.
  17691. *
  17692. * @param {number} index - The index into the buffer attribute.
  17693. * @return {number} The z component.
  17694. */
  17695. getZ( index ) {
  17696. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17697. if ( this.normalized ) z = denormalize( z, this.array );
  17698. return z;
  17699. }
  17700. /**
  17701. * Returns the w component of the vector at the given index.
  17702. *
  17703. * @param {number} index - The index into the buffer attribute.
  17704. * @return {number} The w component.
  17705. */
  17706. getW( index ) {
  17707. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17708. if ( this.normalized ) w = denormalize( w, this.array );
  17709. return w;
  17710. }
  17711. /**
  17712. * Sets the x and y component of the vector at the given index.
  17713. *
  17714. * @param {number} index - The index into the buffer attribute.
  17715. * @param {number} x - The value for the x component to set.
  17716. * @param {number} y - The value for the y component to set.
  17717. * @return {InterleavedBufferAttribute} A reference to this instance.
  17718. */
  17719. setXY( index, x, y ) {
  17720. index = index * this.data.stride + this.offset;
  17721. if ( this.normalized ) {
  17722. x = normalize( x, this.array );
  17723. y = normalize( y, this.array );
  17724. }
  17725. this.data.array[ index + 0 ] = x;
  17726. this.data.array[ index + 1 ] = y;
  17727. return this;
  17728. }
  17729. /**
  17730. * Sets the x, y and z component of the vector at the given index.
  17731. *
  17732. * @param {number} index - The index into the buffer attribute.
  17733. * @param {number} x - The value for the x component to set.
  17734. * @param {number} y - The value for the y component to set.
  17735. * @param {number} z - The value for the z component to set.
  17736. * @return {InterleavedBufferAttribute} A reference to this instance.
  17737. */
  17738. setXYZ( index, x, y, z ) {
  17739. index = index * this.data.stride + this.offset;
  17740. if ( this.normalized ) {
  17741. x = normalize( x, this.array );
  17742. y = normalize( y, this.array );
  17743. z = normalize( z, this.array );
  17744. }
  17745. this.data.array[ index + 0 ] = x;
  17746. this.data.array[ index + 1 ] = y;
  17747. this.data.array[ index + 2 ] = z;
  17748. return this;
  17749. }
  17750. /**
  17751. * Sets the x, y, z and w component of the vector at the given index.
  17752. *
  17753. * @param {number} index - The index into the buffer attribute.
  17754. * @param {number} x - The value for the x component to set.
  17755. * @param {number} y - The value for the y component to set.
  17756. * @param {number} z - The value for the z component to set.
  17757. * @param {number} w - The value for the w component to set.
  17758. * @return {InterleavedBufferAttribute} A reference to this instance.
  17759. */
  17760. setXYZW( index, x, y, z, w ) {
  17761. index = index * this.data.stride + this.offset;
  17762. if ( this.normalized ) {
  17763. x = normalize( x, this.array );
  17764. y = normalize( y, this.array );
  17765. z = normalize( z, this.array );
  17766. w = normalize( w, this.array );
  17767. }
  17768. this.data.array[ index + 0 ] = x;
  17769. this.data.array[ index + 1 ] = y;
  17770. this.data.array[ index + 2 ] = z;
  17771. this.data.array[ index + 3 ] = w;
  17772. return this;
  17773. }
  17774. /**
  17775. * Returns a new buffer attribute with copied values from this instance.
  17776. *
  17777. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17778. *
  17779. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17780. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17781. */
  17782. clone( data ) {
  17783. if ( data === undefined ) {
  17784. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17785. const array = [];
  17786. for ( let i = 0; i < this.count; i ++ ) {
  17787. const index = i * this.data.stride + this.offset;
  17788. for ( let j = 0; j < this.itemSize; j ++ ) {
  17789. array.push( this.data.array[ index + j ] );
  17790. }
  17791. }
  17792. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17793. } else {
  17794. if ( data.interleavedBuffers === undefined ) {
  17795. data.interleavedBuffers = {};
  17796. }
  17797. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17798. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17799. }
  17800. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17801. }
  17802. }
  17803. /**
  17804. * Serializes the buffer attribute into JSON.
  17805. *
  17806. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17807. *
  17808. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17809. * @return {Object} A JSON object representing the serialized buffer attribute.
  17810. */
  17811. toJSON( data ) {
  17812. if ( data === undefined ) {
  17813. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17814. const array = [];
  17815. for ( let i = 0; i < this.count; i ++ ) {
  17816. const index = i * this.data.stride + this.offset;
  17817. for ( let j = 0; j < this.itemSize; j ++ ) {
  17818. array.push( this.data.array[ index + j ] );
  17819. }
  17820. }
  17821. // de-interleave data and save it as an ordinary buffer attribute for now
  17822. return {
  17823. itemSize: this.itemSize,
  17824. type: this.array.constructor.name,
  17825. array: array,
  17826. normalized: this.normalized
  17827. };
  17828. } else {
  17829. // save as true interleaved attribute
  17830. if ( data.interleavedBuffers === undefined ) {
  17831. data.interleavedBuffers = {};
  17832. }
  17833. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17834. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17835. }
  17836. return {
  17837. isInterleavedBufferAttribute: true,
  17838. itemSize: this.itemSize,
  17839. data: this.data.uuid,
  17840. offset: this.offset,
  17841. normalized: this.normalized
  17842. };
  17843. }
  17844. }
  17845. }
  17846. /**
  17847. * A material for rendering instances of {@link Sprite}.
  17848. *
  17849. * ```js
  17850. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17851. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17852. *
  17853. * const sprite = new THREE.Sprite( material );
  17854. * sprite.scale.set(200, 200, 1)
  17855. * scene.add( sprite );
  17856. * ```
  17857. *
  17858. * @augments Material
  17859. */
  17860. class SpriteMaterial extends Material {
  17861. /**
  17862. * Constructs a new sprite material.
  17863. *
  17864. * @param {Object} [parameters] - An object with one or more properties
  17865. * defining the material's appearance. Any property of the material
  17866. * (including any property from inherited materials) can be passed
  17867. * in here. Color values can be passed any type of value accepted
  17868. * by {@link Color#set}.
  17869. */
  17870. constructor( parameters ) {
  17871. super();
  17872. /**
  17873. * This flag can be used for type testing.
  17874. *
  17875. * @type {boolean}
  17876. * @readonly
  17877. * @default true
  17878. */
  17879. this.isSpriteMaterial = true;
  17880. this.type = 'SpriteMaterial';
  17881. /**
  17882. * Color of the material.
  17883. *
  17884. * @type {Color}
  17885. * @default (1,1,1)
  17886. */
  17887. this.color = new Color( 0xffffff );
  17888. /**
  17889. * The color map. May optionally include an alpha channel, typically combined
  17890. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17891. * color is modulated by the diffuse `color`.
  17892. *
  17893. * @type {?Texture}
  17894. * @default null
  17895. */
  17896. this.map = null;
  17897. /**
  17898. * The alpha map is a grayscale texture that controls the opacity across the
  17899. * surface (black: fully transparent; white: fully opaque).
  17900. *
  17901. * Only the color of the texture is used, ignoring the alpha channel if one
  17902. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17903. * when sampling this texture due to the extra bit of precision provided for
  17904. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17905. * luminance/alpha textures will also still work as expected.
  17906. *
  17907. * @type {?Texture}
  17908. * @default null
  17909. */
  17910. this.alphaMap = null;
  17911. /**
  17912. * The rotation of the sprite in radians.
  17913. *
  17914. * @type {number}
  17915. * @default 0
  17916. */
  17917. this.rotation = 0;
  17918. /**
  17919. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  17920. *
  17921. * @type {boolean}
  17922. * @default true
  17923. */
  17924. this.sizeAttenuation = true;
  17925. /**
  17926. * Overwritten since sprite materials are transparent
  17927. * by default.
  17928. *
  17929. * @type {boolean}
  17930. * @default true
  17931. */
  17932. this.transparent = true;
  17933. /**
  17934. * Whether the material is affected by fog or not.
  17935. *
  17936. * @type {boolean}
  17937. * @default true
  17938. */
  17939. this.fog = true;
  17940. this.setValues( parameters );
  17941. }
  17942. copy( source ) {
  17943. super.copy( source );
  17944. this.color.copy( source.color );
  17945. this.map = source.map;
  17946. this.alphaMap = source.alphaMap;
  17947. this.rotation = source.rotation;
  17948. this.sizeAttenuation = source.sizeAttenuation;
  17949. this.fog = source.fog;
  17950. return this;
  17951. }
  17952. }
  17953. let _geometry;
  17954. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17955. const _worldScale = /*@__PURE__*/ new Vector3();
  17956. const _mvPosition = /*@__PURE__*/ new Vector3();
  17957. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17958. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17959. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17960. const _vA = /*@__PURE__*/ new Vector3();
  17961. const _vB = /*@__PURE__*/ new Vector3();
  17962. const _vC = /*@__PURE__*/ new Vector3();
  17963. const _uvA = /*@__PURE__*/ new Vector2();
  17964. const _uvB = /*@__PURE__*/ new Vector2();
  17965. const _uvC = /*@__PURE__*/ new Vector2();
  17966. /**
  17967. * A sprite is a plane that always faces towards the camera, generally with a
  17968. * partially transparent texture applied.
  17969. *
  17970. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  17971. * have no effect.
  17972. *
  17973. * ```js
  17974. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  17975. * const material = new THREE.SpriteMaterial( { map: map } );
  17976. *
  17977. * const sprite = new THREE.Sprite( material );
  17978. * scene.add( sprite );
  17979. * ```
  17980. *
  17981. * @augments Object3D
  17982. */
  17983. class Sprite extends Object3D {
  17984. /**
  17985. * Constructs a new sprite.
  17986. *
  17987. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  17988. */
  17989. constructor( material = new SpriteMaterial() ) {
  17990. super();
  17991. /**
  17992. * This flag can be used for type testing.
  17993. *
  17994. * @type {boolean}
  17995. * @readonly
  17996. * @default true
  17997. */
  17998. this.isSprite = true;
  17999. this.type = 'Sprite';
  18000. if ( _geometry === undefined ) {
  18001. _geometry = new BufferGeometry();
  18002. const float32Array = new Float32Array( [
  18003. -0.5, -0.5, 0, 0, 0,
  18004. 0.5, -0.5, 0, 1, 0,
  18005. 0.5, 0.5, 0, 1, 1,
  18006. -0.5, 0.5, 0, 0, 1
  18007. ] );
  18008. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18009. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18010. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18011. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18012. }
  18013. /**
  18014. * The sprite geometry.
  18015. *
  18016. * @type {BufferGeometry}
  18017. */
  18018. this.geometry = _geometry;
  18019. /**
  18020. * The sprite material.
  18021. *
  18022. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18023. */
  18024. this.material = material;
  18025. /**
  18026. * The sprite's anchor point, and the point around which the sprite rotates.
  18027. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18028. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18029. *
  18030. * @type {Vector2}
  18031. * @default (0.5,0.5)
  18032. */
  18033. this.center = new Vector2( 0.5, 0.5 );
  18034. /**
  18035. * The number of instances of this sprite.
  18036. * Can only be used with {@link WebGPURenderer}.
  18037. *
  18038. * @type {number}
  18039. * @default 1
  18040. */
  18041. this.count = 1;
  18042. }
  18043. /**
  18044. * Computes intersection points between a casted ray and this sprite.
  18045. *
  18046. * @param {Raycaster} raycaster - The raycaster.
  18047. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18048. */
  18049. raycast( raycaster, intersects ) {
  18050. if ( raycaster.camera === null ) {
  18051. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18052. }
  18053. _worldScale.setFromMatrixScale( this.matrixWorld );
  18054. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18055. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18056. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18057. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18058. _worldScale.multiplyScalar( - _mvPosition.z );
  18059. }
  18060. const rotation = this.material.rotation;
  18061. let sin, cos;
  18062. if ( rotation !== 0 ) {
  18063. cos = Math.cos( rotation );
  18064. sin = Math.sin( rotation );
  18065. }
  18066. const center = this.center;
  18067. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18068. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18069. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18070. _uvA.set( 0, 0 );
  18071. _uvB.set( 1, 0 );
  18072. _uvC.set( 1, 1 );
  18073. // check first triangle
  18074. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18075. if ( intersect === null ) {
  18076. // check second triangle
  18077. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18078. _uvB.set( 0, 1 );
  18079. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18080. if ( intersect === null ) {
  18081. return;
  18082. }
  18083. }
  18084. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18085. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18086. intersects.push( {
  18087. distance: distance,
  18088. point: _intersectPoint.clone(),
  18089. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18090. face: null,
  18091. object: this
  18092. } );
  18093. }
  18094. copy( source, recursive ) {
  18095. super.copy( source, recursive );
  18096. if ( source.center !== undefined ) this.center.copy( source.center );
  18097. this.material = source.material;
  18098. return this;
  18099. }
  18100. }
  18101. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18102. // compute position in camera space
  18103. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18104. // to check if rotation is not zero
  18105. if ( sin !== undefined ) {
  18106. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18107. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18108. } else {
  18109. _rotatedPosition.copy( _alignedPosition );
  18110. }
  18111. vertexPosition.copy( mvPosition );
  18112. vertexPosition.x += _rotatedPosition.x;
  18113. vertexPosition.y += _rotatedPosition.y;
  18114. // transform to world space
  18115. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18116. }
  18117. const _v1$2 = /*@__PURE__*/ new Vector3();
  18118. const _v2$1 = /*@__PURE__*/ new Vector3();
  18119. /**
  18120. * A component for providing a basic Level of Detail (LOD) mechanism.
  18121. *
  18122. * Every LOD level is associated with an object, and rendering can be switched
  18123. * between them at the distances specified. Typically you would create, say,
  18124. * three meshes, one for far away (low detail), one for mid range (medium
  18125. * detail) and one for close up (high detail).
  18126. *
  18127. * ```js
  18128. * const lod = new THREE.LOD();
  18129. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18130. *
  18131. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18132. * for( let i = 0; i < 3; i++ ) {
  18133. *
  18134. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18135. * const mesh = new THREE.Mesh( geometry, material );
  18136. * lod.addLevel( mesh, i * 75 );
  18137. *
  18138. * }
  18139. *
  18140. * scene.add( lod );
  18141. * ```
  18142. *
  18143. * @augments Object3D
  18144. */
  18145. class LOD extends Object3D {
  18146. /**
  18147. * Constructs a new LOD.
  18148. */
  18149. constructor() {
  18150. super();
  18151. /**
  18152. * This flag can be used for type testing.
  18153. *
  18154. * @type {boolean}
  18155. * @readonly
  18156. * @default true
  18157. */
  18158. this.isLOD = true;
  18159. /**
  18160. * The current LOD index.
  18161. *
  18162. * @private
  18163. * @type {number}
  18164. * @default 0
  18165. */
  18166. this._currentLevel = 0;
  18167. this.type = 'LOD';
  18168. Object.defineProperties( this, {
  18169. /**
  18170. * This array holds the LOD levels.
  18171. *
  18172. * @name LOD#levels
  18173. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18174. */
  18175. levels: {
  18176. enumerable: true,
  18177. value: []
  18178. }
  18179. } );
  18180. /**
  18181. * Whether the LOD object is updated automatically by the renderer per frame
  18182. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18183. * render loop by yourself.
  18184. *
  18185. * @type {boolean}
  18186. * @default true
  18187. */
  18188. this.autoUpdate = true;
  18189. }
  18190. copy( source ) {
  18191. super.copy( source, false );
  18192. const levels = source.levels;
  18193. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18194. const level = levels[ i ];
  18195. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18196. }
  18197. this.autoUpdate = source.autoUpdate;
  18198. return this;
  18199. }
  18200. /**
  18201. * Adds a mesh that will display at a certain distance and greater. Typically
  18202. * the further away the distance, the lower the detail on the mesh.
  18203. *
  18204. * @param {Object3D} object - The 3D object to display at this level.
  18205. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18206. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18207. * @return {LOD} A reference to this instance.
  18208. */
  18209. addLevel( object, distance = 0, hysteresis = 0 ) {
  18210. distance = Math.abs( distance );
  18211. const levels = this.levels;
  18212. let l;
  18213. for ( l = 0; l < levels.length; l ++ ) {
  18214. if ( distance < levels[ l ].distance ) {
  18215. break;
  18216. }
  18217. }
  18218. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18219. this.add( object );
  18220. return this;
  18221. }
  18222. /**
  18223. * Removes an existing level, based on the distance from the camera.
  18224. * Returns `true` when the level has been removed. Otherwise `false`.
  18225. *
  18226. * @param {number} distance - Distance of the level to remove.
  18227. * @return {boolean} Whether the level has been removed or not.
  18228. */
  18229. removeLevel( distance ) {
  18230. const levels = this.levels;
  18231. for ( let i = 0; i < levels.length; i ++ ) {
  18232. if ( levels[ i ].distance === distance ) {
  18233. const removedElements = levels.splice( i, 1 );
  18234. this.remove( removedElements[ 0 ].object );
  18235. return true;
  18236. }
  18237. }
  18238. return false;
  18239. }
  18240. /**
  18241. * Returns the currently active LOD level index.
  18242. *
  18243. * @return {number} The current active LOD level index.
  18244. */
  18245. getCurrentLevel() {
  18246. return this._currentLevel;
  18247. }
  18248. /**
  18249. * Returns a reference to the first 3D object that is greater than
  18250. * the given distance.
  18251. *
  18252. * @param {number} distance - The LOD distance.
  18253. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18254. */
  18255. getObjectForDistance( distance ) {
  18256. const levels = this.levels;
  18257. if ( levels.length > 0 ) {
  18258. let i, l;
  18259. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18260. let levelDistance = levels[ i ].distance;
  18261. if ( levels[ i ].object.visible ) {
  18262. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18263. }
  18264. if ( distance < levelDistance ) {
  18265. break;
  18266. }
  18267. }
  18268. return levels[ i - 1 ].object;
  18269. }
  18270. return null;
  18271. }
  18272. /**
  18273. * Computes intersection points between a casted ray and this LOD.
  18274. *
  18275. * @param {Raycaster} raycaster - The raycaster.
  18276. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18277. */
  18278. raycast( raycaster, intersects ) {
  18279. const levels = this.levels;
  18280. if ( levels.length > 0 ) {
  18281. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18282. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18283. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18284. }
  18285. }
  18286. /**
  18287. * Updates the LOD by computing which LOD level should be visible according
  18288. * to the current distance of the given camera.
  18289. *
  18290. * @param {Camera} camera - The camera the scene is rendered with.
  18291. */
  18292. update( camera ) {
  18293. const levels = this.levels;
  18294. if ( levels.length > 1 ) {
  18295. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18296. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18297. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18298. levels[ 0 ].object.visible = true;
  18299. let i, l;
  18300. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18301. let levelDistance = levels[ i ].distance;
  18302. if ( levels[ i ].object.visible ) {
  18303. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18304. }
  18305. if ( distance >= levelDistance ) {
  18306. levels[ i - 1 ].object.visible = false;
  18307. levels[ i ].object.visible = true;
  18308. } else {
  18309. break;
  18310. }
  18311. }
  18312. this._currentLevel = i - 1;
  18313. for ( ; i < l; i ++ ) {
  18314. levels[ i ].object.visible = false;
  18315. }
  18316. }
  18317. }
  18318. toJSON( meta ) {
  18319. const data = super.toJSON( meta );
  18320. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18321. data.object.levels = [];
  18322. const levels = this.levels;
  18323. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18324. const level = levels[ i ];
  18325. data.object.levels.push( {
  18326. object: level.object.uuid,
  18327. distance: level.distance,
  18328. hysteresis: level.hysteresis
  18329. } );
  18330. }
  18331. return data;
  18332. }
  18333. }
  18334. const _basePosition = /*@__PURE__*/ new Vector3();
  18335. const _skinIndex = /*@__PURE__*/ new Vector4();
  18336. const _skinWeight = /*@__PURE__*/ new Vector4();
  18337. const _vector3 = /*@__PURE__*/ new Vector3();
  18338. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18339. const _vertex = /*@__PURE__*/ new Vector3();
  18340. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18341. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18342. const _ray$2 = /*@__PURE__*/ new Ray();
  18343. /**
  18344. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18345. * vertices of the geometry with skinning/skeleton animation.
  18346. *
  18347. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18348. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18349. * vertex to a certain extend.
  18350. *
  18351. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18352. * or {@link FBXLoader } import respective models.
  18353. *
  18354. * @augments Mesh
  18355. */
  18356. class SkinnedMesh extends Mesh {
  18357. /**
  18358. * Constructs a new skinned mesh.
  18359. *
  18360. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18361. * @param {Material|Array<Material>} [material] - The mesh material.
  18362. */
  18363. constructor( geometry, material ) {
  18364. super( geometry, material );
  18365. /**
  18366. * This flag can be used for type testing.
  18367. *
  18368. * @type {boolean}
  18369. * @readonly
  18370. * @default true
  18371. */
  18372. this.isSkinnedMesh = true;
  18373. this.type = 'SkinnedMesh';
  18374. /**
  18375. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18376. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18377. * across multiple skinned meshes.
  18378. *
  18379. * @type {(AttachedBindMode|DetachedBindMode)}
  18380. * @default AttachedBindMode
  18381. */
  18382. this.bindMode = AttachedBindMode;
  18383. /**
  18384. * The base matrix that is used for the bound bone transforms.
  18385. *
  18386. * @type {Matrix4}
  18387. */
  18388. this.bindMatrix = new Matrix4();
  18389. /**
  18390. * The base matrix that is used for resetting the bound bone transforms.
  18391. *
  18392. * @type {Matrix4}
  18393. */
  18394. this.bindMatrixInverse = new Matrix4();
  18395. /**
  18396. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18397. *
  18398. * @type {?Box3}
  18399. * @default null
  18400. */
  18401. this.boundingBox = null;
  18402. /**
  18403. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18404. *
  18405. * @type {?Sphere}
  18406. * @default null
  18407. */
  18408. this.boundingSphere = null;
  18409. }
  18410. /**
  18411. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18412. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18413. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18414. * the current animation state.
  18415. */
  18416. computeBoundingBox() {
  18417. const geometry = this.geometry;
  18418. if ( this.boundingBox === null ) {
  18419. this.boundingBox = new Box3();
  18420. }
  18421. this.boundingBox.makeEmpty();
  18422. const positionAttribute = geometry.getAttribute( 'position' );
  18423. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18424. this.getVertexPosition( i, _vertex );
  18425. this.boundingBox.expandByPoint( _vertex );
  18426. }
  18427. }
  18428. /**
  18429. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18430. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18431. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18432. * per frame in order to reflect the current animation state.
  18433. */
  18434. computeBoundingSphere() {
  18435. const geometry = this.geometry;
  18436. if ( this.boundingSphere === null ) {
  18437. this.boundingSphere = new Sphere();
  18438. }
  18439. this.boundingSphere.makeEmpty();
  18440. const positionAttribute = geometry.getAttribute( 'position' );
  18441. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18442. this.getVertexPosition( i, _vertex );
  18443. this.boundingSphere.expandByPoint( _vertex );
  18444. }
  18445. }
  18446. copy( source, recursive ) {
  18447. super.copy( source, recursive );
  18448. this.bindMode = source.bindMode;
  18449. this.bindMatrix.copy( source.bindMatrix );
  18450. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18451. this.skeleton = source.skeleton;
  18452. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18453. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18454. return this;
  18455. }
  18456. raycast( raycaster, intersects ) {
  18457. const material = this.material;
  18458. const matrixWorld = this.matrixWorld;
  18459. if ( material === undefined ) return;
  18460. // test with bounding sphere in world space
  18461. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18462. _sphere$5.copy( this.boundingSphere );
  18463. _sphere$5.applyMatrix4( matrixWorld );
  18464. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18465. // convert ray to local space of skinned mesh
  18466. _inverseMatrix$2.copy( matrixWorld ).invert();
  18467. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18468. // test with bounding box in local space
  18469. if ( this.boundingBox !== null ) {
  18470. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18471. }
  18472. // test for intersections with geometry
  18473. this._computeIntersections( raycaster, intersects, _ray$2 );
  18474. }
  18475. getVertexPosition( index, target ) {
  18476. super.getVertexPosition( index, target );
  18477. this.applyBoneTransform( index, target );
  18478. return target;
  18479. }
  18480. /**
  18481. * Binds the given skeleton to the skinned mesh.
  18482. *
  18483. * @param {Skeleton} skeleton - The skeleton to bind.
  18484. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18485. * the skinned mesh's world matrix will be used instead.
  18486. */
  18487. bind( skeleton, bindMatrix ) {
  18488. this.skeleton = skeleton;
  18489. if ( bindMatrix === undefined ) {
  18490. this.updateMatrixWorld( true );
  18491. this.skeleton.calculateInverses();
  18492. bindMatrix = this.matrixWorld;
  18493. }
  18494. this.bindMatrix.copy( bindMatrix );
  18495. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18496. }
  18497. /**
  18498. * This method sets the skinned mesh in the rest pose).
  18499. */
  18500. pose() {
  18501. this.skeleton.pose();
  18502. }
  18503. /**
  18504. * Normalizes the skin weights which are defined as a buffer attribute
  18505. * in the skinned mesh's geometry.
  18506. */
  18507. normalizeSkinWeights() {
  18508. const vector = new Vector4();
  18509. const skinWeight = this.geometry.attributes.skinWeight;
  18510. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18511. vector.fromBufferAttribute( skinWeight, i );
  18512. const scale = 1.0 / vector.manhattanLength();
  18513. if ( scale !== Infinity ) {
  18514. vector.multiplyScalar( scale );
  18515. } else {
  18516. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18517. }
  18518. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18519. }
  18520. }
  18521. updateMatrixWorld( force ) {
  18522. super.updateMatrixWorld( force );
  18523. if ( this.bindMode === AttachedBindMode ) {
  18524. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18525. } else if ( this.bindMode === DetachedBindMode ) {
  18526. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18527. } else {
  18528. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18529. }
  18530. }
  18531. /**
  18532. * Applies the bone transform associated with the given index to the given
  18533. * vertex position. Returns the updated vector.
  18534. *
  18535. * @param {number} index - The vertex index.
  18536. * @param {Vector3} target - The target object that is used to store the method's result.
  18537. * the skinned mesh's world matrix will be used instead.
  18538. * @return {Vector3} The updated vertex position.
  18539. */
  18540. applyBoneTransform( index, target ) {
  18541. const skeleton = this.skeleton;
  18542. const geometry = this.geometry;
  18543. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18544. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18545. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18546. target.set( 0, 0, 0 );
  18547. for ( let i = 0; i < 4; i ++ ) {
  18548. const weight = _skinWeight.getComponent( i );
  18549. if ( weight !== 0 ) {
  18550. const boneIndex = _skinIndex.getComponent( i );
  18551. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18552. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18553. }
  18554. }
  18555. return target.applyMatrix4( this.bindMatrixInverse );
  18556. }
  18557. }
  18558. /**
  18559. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18560. * the {@link SkinnedMesh}.
  18561. *
  18562. * ```js
  18563. * const root = new THREE.Bone();
  18564. * const child = new THREE.Bone();
  18565. *
  18566. * root.add( child );
  18567. * child.position.y = 5;
  18568. * ```
  18569. *
  18570. * @augments Object3D
  18571. */
  18572. class Bone extends Object3D {
  18573. /**
  18574. * Constructs a new bone.
  18575. */
  18576. constructor() {
  18577. super();
  18578. /**
  18579. * This flag can be used for type testing.
  18580. *
  18581. * @type {boolean}
  18582. * @readonly
  18583. * @default true
  18584. */
  18585. this.isBone = true;
  18586. this.type = 'Bone';
  18587. }
  18588. }
  18589. /**
  18590. * Creates a texture directly from raw buffer data.
  18591. *
  18592. * The interpretation of the data depends on type and format: If the type is
  18593. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18594. * texel data. If the format is `RGBAFormat`, data needs four values for
  18595. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18596. *
  18597. * @augments Texture
  18598. */
  18599. class DataTexture extends Texture {
  18600. /**
  18601. * Constructs a new data texture.
  18602. *
  18603. * @param {?TypedArray} [data=null] - The buffer data.
  18604. * @param {number} [width=1] - The width of the texture.
  18605. * @param {number} [height=1] - The height of the texture.
  18606. * @param {number} [format=RGBAFormat] - The texture format.
  18607. * @param {number} [type=UnsignedByteType] - The texture type.
  18608. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18609. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18610. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18611. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18612. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18613. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18614. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18615. */
  18616. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18617. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18618. /**
  18619. * This flag can be used for type testing.
  18620. *
  18621. * @type {boolean}
  18622. * @readonly
  18623. * @default true
  18624. */
  18625. this.isDataTexture = true;
  18626. /**
  18627. * The image definition of a data texture.
  18628. *
  18629. * @type {{data:TypedArray,width:number,height:number}}
  18630. */
  18631. this.image = { data: data, width: width, height: height };
  18632. /**
  18633. * Whether to generate mipmaps (if possible) for a texture.
  18634. *
  18635. * Overwritten and set to `false` by default.
  18636. *
  18637. * @type {boolean}
  18638. * @default false
  18639. */
  18640. this.generateMipmaps = false;
  18641. /**
  18642. * If set to `true`, the texture is flipped along the vertical axis when
  18643. * uploaded to the GPU.
  18644. *
  18645. * Overwritten and set to `false` by default.
  18646. *
  18647. * @type {boolean}
  18648. * @default false
  18649. */
  18650. this.flipY = false;
  18651. /**
  18652. * Specifies the alignment requirements for the start of each pixel row in memory.
  18653. *
  18654. * Overwritten and set to `1` by default.
  18655. *
  18656. * @type {boolean}
  18657. * @default 1
  18658. */
  18659. this.unpackAlignment = 1;
  18660. }
  18661. }
  18662. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18663. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18664. /**
  18665. * Class for representing the armatures in `three.js`. The skeleton
  18666. * is defined by a hierarchy of bones.
  18667. *
  18668. * ```js
  18669. * const bones = [];
  18670. *
  18671. * const shoulder = new THREE.Bone();
  18672. * const elbow = new THREE.Bone();
  18673. * const hand = new THREE.Bone();
  18674. *
  18675. * shoulder.add( elbow );
  18676. * elbow.add( hand );
  18677. *
  18678. * bones.push( shoulder , elbow, hand);
  18679. *
  18680. * shoulder.position.y = -5;
  18681. * elbow.position.y = 0;
  18682. * hand.position.y = 5;
  18683. *
  18684. * const armSkeleton = new THREE.Skeleton( bones );
  18685. * ```
  18686. */
  18687. class Skeleton {
  18688. /**
  18689. * Constructs a new skeleton.
  18690. *
  18691. * @param {Array<Bone>} [bones] - An array of bones.
  18692. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18693. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18694. */
  18695. constructor( bones = [], boneInverses = [] ) {
  18696. this.uuid = generateUUID();
  18697. /**
  18698. * An array of bones defining the skeleton.
  18699. *
  18700. * @type {Array<Bone>}
  18701. */
  18702. this.bones = bones.slice( 0 );
  18703. /**
  18704. * An array of bone inverse matrices.
  18705. *
  18706. * @type {Array<Matrix4>}
  18707. */
  18708. this.boneInverses = boneInverses;
  18709. /**
  18710. * An array buffer holding the bone data.
  18711. * Input data for {@link Skeleton#boneTexture}.
  18712. *
  18713. * @type {?Float32Array}
  18714. * @default null
  18715. */
  18716. this.boneMatrices = null;
  18717. /**
  18718. * A texture holding the bone data for use
  18719. * in the vertex shader.
  18720. *
  18721. * @type {?DataTexture}
  18722. * @default null
  18723. */
  18724. this.boneTexture = null;
  18725. this.init();
  18726. }
  18727. /**
  18728. * Initializes the skeleton. This method gets automatically called by the constructor
  18729. * but depending on how the skeleton is created it might be necessary to call this method
  18730. * manually.
  18731. */
  18732. init() {
  18733. const bones = this.bones;
  18734. const boneInverses = this.boneInverses;
  18735. this.boneMatrices = new Float32Array( bones.length * 16 );
  18736. // calculate inverse bone matrices if necessary
  18737. if ( boneInverses.length === 0 ) {
  18738. this.calculateInverses();
  18739. } else {
  18740. // handle special case
  18741. if ( bones.length !== boneInverses.length ) {
  18742. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18743. this.boneInverses = [];
  18744. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18745. this.boneInverses.push( new Matrix4() );
  18746. }
  18747. }
  18748. }
  18749. }
  18750. /**
  18751. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18752. * and fills it with new matrices.
  18753. */
  18754. calculateInverses() {
  18755. this.boneInverses.length = 0;
  18756. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18757. const inverse = new Matrix4();
  18758. if ( this.bones[ i ] ) {
  18759. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18760. }
  18761. this.boneInverses.push( inverse );
  18762. }
  18763. }
  18764. /**
  18765. * Resets the skeleton to the base pose.
  18766. */
  18767. pose() {
  18768. // recover the bind-time world matrices
  18769. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18770. const bone = this.bones[ i ];
  18771. if ( bone ) {
  18772. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18773. }
  18774. }
  18775. // compute the local matrices, positions, rotations and scales
  18776. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18777. const bone = this.bones[ i ];
  18778. if ( bone ) {
  18779. if ( bone.parent && bone.parent.isBone ) {
  18780. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18781. bone.matrix.multiply( bone.matrixWorld );
  18782. } else {
  18783. bone.matrix.copy( bone.matrixWorld );
  18784. }
  18785. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18786. }
  18787. }
  18788. }
  18789. /**
  18790. * Resets the skeleton to the base pose.
  18791. */
  18792. update() {
  18793. const bones = this.bones;
  18794. const boneInverses = this.boneInverses;
  18795. const boneMatrices = this.boneMatrices;
  18796. const boneTexture = this.boneTexture;
  18797. // flatten bone matrices to array
  18798. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18799. // compute the offset between the current and the original transform
  18800. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18801. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18802. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18803. }
  18804. if ( boneTexture !== null ) {
  18805. boneTexture.needsUpdate = true;
  18806. }
  18807. }
  18808. /**
  18809. * Returns a new skeleton with copied values from this instance.
  18810. *
  18811. * @return {Skeleton} A clone of this instance.
  18812. */
  18813. clone() {
  18814. return new Skeleton( this.bones, this.boneInverses );
  18815. }
  18816. /**
  18817. * Computes a data texture for passing bone data to the vertex shader.
  18818. *
  18819. * @return {Skeleton} A reference of this instance.
  18820. */
  18821. computeBoneTexture() {
  18822. // layout (1 matrix = 4 pixels)
  18823. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18824. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18825. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18826. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18827. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18828. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18829. size = Math.ceil( size / 4 ) * 4;
  18830. size = Math.max( size, 4 );
  18831. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18832. boneMatrices.set( this.boneMatrices ); // copy current values
  18833. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18834. boneTexture.needsUpdate = true;
  18835. this.boneMatrices = boneMatrices;
  18836. this.boneTexture = boneTexture;
  18837. return this;
  18838. }
  18839. /**
  18840. * Searches through the skeleton's bone array and returns the first with a
  18841. * matching name.
  18842. *
  18843. * @param {string} name - The name of the bone.
  18844. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18845. */
  18846. getBoneByName( name ) {
  18847. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18848. const bone = this.bones[ i ];
  18849. if ( bone.name === name ) {
  18850. return bone;
  18851. }
  18852. }
  18853. return undefined;
  18854. }
  18855. /**
  18856. * Frees the GPU-related resources allocated by this instance. Call this
  18857. * method whenever this instance is no longer used in your app.
  18858. */
  18859. dispose( ) {
  18860. if ( this.boneTexture !== null ) {
  18861. this.boneTexture.dispose();
  18862. this.boneTexture = null;
  18863. }
  18864. }
  18865. /**
  18866. * Setups the skeleton by the given JSON and bones.
  18867. *
  18868. * @param {Object} json - The skeleton as serialized JSON.
  18869. * @param {Object<string, Bone>} bones - An array of bones.
  18870. * @return {Skeleton} A reference of this instance.
  18871. */
  18872. fromJSON( json, bones ) {
  18873. this.uuid = json.uuid;
  18874. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18875. const uuid = json.bones[ i ];
  18876. let bone = bones[ uuid ];
  18877. if ( bone === undefined ) {
  18878. warn( 'Skeleton: No bone found with UUID:', uuid );
  18879. bone = new Bone();
  18880. }
  18881. this.bones.push( bone );
  18882. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18883. }
  18884. this.init();
  18885. return this;
  18886. }
  18887. /**
  18888. * Serializes the skeleton into JSON.
  18889. *
  18890. * @return {Object} A JSON object representing the serialized skeleton.
  18891. * @see {@link ObjectLoader#parse}
  18892. */
  18893. toJSON() {
  18894. const data = {
  18895. metadata: {
  18896. version: 4.7,
  18897. type: 'Skeleton',
  18898. generator: 'Skeleton.toJSON'
  18899. },
  18900. bones: [],
  18901. boneInverses: []
  18902. };
  18903. data.uuid = this.uuid;
  18904. const bones = this.bones;
  18905. const boneInverses = this.boneInverses;
  18906. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18907. const bone = bones[ i ];
  18908. data.bones.push( bone.uuid );
  18909. const boneInverse = boneInverses[ i ];
  18910. data.boneInverses.push( boneInverse.toArray() );
  18911. }
  18912. return data;
  18913. }
  18914. }
  18915. /**
  18916. * An instanced version of a buffer attribute.
  18917. *
  18918. * @augments BufferAttribute
  18919. */
  18920. class InstancedBufferAttribute extends BufferAttribute {
  18921. /**
  18922. * Constructs a new instanced buffer attribute.
  18923. *
  18924. * @param {TypedArray} array - The array holding the attribute data.
  18925. * @param {number} itemSize - The item size.
  18926. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  18927. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  18928. */
  18929. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18930. super( array, itemSize, normalized );
  18931. /**
  18932. * This flag can be used for type testing.
  18933. *
  18934. * @type {boolean}
  18935. * @readonly
  18936. * @default true
  18937. */
  18938. this.isInstancedBufferAttribute = true;
  18939. /**
  18940. * Defines how often a value of this buffer attribute should be repeated. A
  18941. * value of one means that each value of the instanced attribute is used for
  18942. * a single instance. A value of two means that each value is used for two
  18943. * consecutive instances (and so on).
  18944. *
  18945. * @type {number}
  18946. * @default 1
  18947. */
  18948. this.meshPerAttribute = meshPerAttribute;
  18949. }
  18950. copy( source ) {
  18951. super.copy( source );
  18952. this.meshPerAttribute = source.meshPerAttribute;
  18953. return this;
  18954. }
  18955. toJSON() {
  18956. const data = super.toJSON();
  18957. data.meshPerAttribute = this.meshPerAttribute;
  18958. data.isInstancedBufferAttribute = true;
  18959. return data;
  18960. }
  18961. }
  18962. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18963. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18964. const _instanceIntersects = [];
  18965. const _box3 = /*@__PURE__*/ new Box3();
  18966. const _identity = /*@__PURE__*/ new Matrix4();
  18967. const _mesh$1 = /*@__PURE__*/ new Mesh();
  18968. const _sphere$4 = /*@__PURE__*/ new Sphere();
  18969. /**
  18970. * A special version of a mesh with instanced rendering support. Use
  18971. * this class if you have to render a large number of objects with the same
  18972. * geometry and material(s) but with different world transformations. The usage
  18973. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  18974. * improve the overall rendering performance in your application.
  18975. *
  18976. * @augments Mesh
  18977. */
  18978. class InstancedMesh extends Mesh {
  18979. /**
  18980. * Constructs a new instanced mesh.
  18981. *
  18982. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18983. * @param {Material|Array<Material>} [material] - The mesh material.
  18984. * @param {number} count - The number of instances.
  18985. */
  18986. constructor( geometry, material, count ) {
  18987. super( geometry, material );
  18988. /**
  18989. * This flag can be used for type testing.
  18990. *
  18991. * @type {boolean}
  18992. * @readonly
  18993. * @default true
  18994. */
  18995. this.isInstancedMesh = true;
  18996. /**
  18997. * Represents the local transformation of all instances. You have to set its
  18998. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  18999. * via {@link InstancedMesh#setMatrixAt}.
  19000. *
  19001. * @type {InstancedBufferAttribute}
  19002. */
  19003. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19004. /**
  19005. * Represents the color of all instances. You have to set its
  19006. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19007. * via {@link InstancedMesh#setColorAt}.
  19008. *
  19009. * @type {?InstancedBufferAttribute}
  19010. * @default null
  19011. */
  19012. this.instanceColor = null;
  19013. /**
  19014. * Represents the morph target weights of all instances. You have to set its
  19015. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19016. * via {@link InstancedMesh#setMorphAt}.
  19017. *
  19018. * @type {?DataTexture}
  19019. * @default null
  19020. */
  19021. this.morphTexture = null;
  19022. /**
  19023. * The number of instances.
  19024. *
  19025. * @type {number}
  19026. */
  19027. this.count = count;
  19028. /**
  19029. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19030. *
  19031. * @type {?Box3}
  19032. * @default null
  19033. */
  19034. this.boundingBox = null;
  19035. /**
  19036. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19037. *
  19038. * @type {?Sphere}
  19039. * @default null
  19040. */
  19041. this.boundingSphere = null;
  19042. for ( let i = 0; i < count; i ++ ) {
  19043. this.setMatrixAt( i, _identity );
  19044. }
  19045. }
  19046. /**
  19047. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19048. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19049. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19050. */
  19051. computeBoundingBox() {
  19052. const geometry = this.geometry;
  19053. const count = this.count;
  19054. if ( this.boundingBox === null ) {
  19055. this.boundingBox = new Box3();
  19056. }
  19057. if ( geometry.boundingBox === null ) {
  19058. geometry.computeBoundingBox();
  19059. }
  19060. this.boundingBox.makeEmpty();
  19061. for ( let i = 0; i < count; i ++ ) {
  19062. this.getMatrixAt( i, _instanceLocalMatrix );
  19063. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19064. this.boundingBox.union( _box3 );
  19065. }
  19066. }
  19067. /**
  19068. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19069. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19070. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19071. */
  19072. computeBoundingSphere() {
  19073. const geometry = this.geometry;
  19074. const count = this.count;
  19075. if ( this.boundingSphere === null ) {
  19076. this.boundingSphere = new Sphere();
  19077. }
  19078. if ( geometry.boundingSphere === null ) {
  19079. geometry.computeBoundingSphere();
  19080. }
  19081. this.boundingSphere.makeEmpty();
  19082. for ( let i = 0; i < count; i ++ ) {
  19083. this.getMatrixAt( i, _instanceLocalMatrix );
  19084. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19085. this.boundingSphere.union( _sphere$4 );
  19086. }
  19087. }
  19088. copy( source, recursive ) {
  19089. super.copy( source, recursive );
  19090. this.instanceMatrix.copy( source.instanceMatrix );
  19091. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19092. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19093. this.count = source.count;
  19094. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19095. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19096. return this;
  19097. }
  19098. /**
  19099. * Gets the color of the defined instance.
  19100. *
  19101. * @param {number} index - The instance index.
  19102. * @param {Color} color - The target object that is used to store the method's result.
  19103. */
  19104. getColorAt( index, color ) {
  19105. color.fromArray( this.instanceColor.array, index * 3 );
  19106. }
  19107. /**
  19108. * Gets the local transformation matrix of the defined instance.
  19109. *
  19110. * @param {number} index - The instance index.
  19111. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19112. */
  19113. getMatrixAt( index, matrix ) {
  19114. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19115. }
  19116. /**
  19117. * Gets the morph target weights of the defined instance.
  19118. *
  19119. * @param {number} index - The instance index.
  19120. * @param {Mesh} object - The target object that is used to store the method's result.
  19121. */
  19122. getMorphAt( index, object ) {
  19123. const objectInfluences = object.morphTargetInfluences;
  19124. const array = this.morphTexture.source.data.data;
  19125. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19126. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19127. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19128. objectInfluences[ i ] = array[ dataIndex + i ];
  19129. }
  19130. }
  19131. raycast( raycaster, intersects ) {
  19132. const matrixWorld = this.matrixWorld;
  19133. const raycastTimes = this.count;
  19134. _mesh$1.geometry = this.geometry;
  19135. _mesh$1.material = this.material;
  19136. if ( _mesh$1.material === undefined ) return;
  19137. // test with bounding sphere first
  19138. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19139. _sphere$4.copy( this.boundingSphere );
  19140. _sphere$4.applyMatrix4( matrixWorld );
  19141. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19142. // now test each instance
  19143. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19144. // calculate the world matrix for each instance
  19145. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19146. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19147. // the mesh represents this single instance
  19148. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19149. _mesh$1.raycast( raycaster, _instanceIntersects );
  19150. // process the result of raycast
  19151. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19152. const intersect = _instanceIntersects[ i ];
  19153. intersect.instanceId = instanceId;
  19154. intersect.object = this;
  19155. intersects.push( intersect );
  19156. }
  19157. _instanceIntersects.length = 0;
  19158. }
  19159. }
  19160. /**
  19161. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19162. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19163. *
  19164. * @param {number} index - The instance index.
  19165. * @param {Color} color - The instance color.
  19166. */
  19167. setColorAt( index, color ) {
  19168. if ( this.instanceColor === null ) {
  19169. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19170. }
  19171. color.toArray( this.instanceColor.array, index * 3 );
  19172. }
  19173. /**
  19174. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19175. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19176. *
  19177. * @param {number} index - The instance index.
  19178. * @param {Matrix4} matrix - The local transformation.
  19179. */
  19180. setMatrixAt( index, matrix ) {
  19181. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19182. }
  19183. /**
  19184. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19185. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19186. *
  19187. * @param {number} index - The instance index.
  19188. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19189. * of a single instance.
  19190. */
  19191. setMorphAt( index, object ) {
  19192. const objectInfluences = object.morphTargetInfluences;
  19193. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19194. if ( this.morphTexture === null ) {
  19195. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19196. }
  19197. const array = this.morphTexture.source.data.data;
  19198. let morphInfluencesSum = 0;
  19199. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19200. morphInfluencesSum += objectInfluences[ i ];
  19201. }
  19202. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19203. const dataIndex = len * index;
  19204. array[ dataIndex ] = morphBaseInfluence;
  19205. array.set( objectInfluences, dataIndex + 1 );
  19206. }
  19207. updateMorphTargets() {
  19208. }
  19209. /**
  19210. * Frees the GPU-related resources allocated by this instance. Call this
  19211. * method whenever this instance is no longer used in your app.
  19212. */
  19213. dispose() {
  19214. this.dispatchEvent( { type: 'dispose' } );
  19215. if ( this.morphTexture !== null ) {
  19216. this.morphTexture.dispose();
  19217. this.morphTexture = null;
  19218. }
  19219. }
  19220. }
  19221. const _vector1 = /*@__PURE__*/ new Vector3();
  19222. const _vector2 = /*@__PURE__*/ new Vector3();
  19223. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19224. /**
  19225. * A two dimensional surface that extends infinitely in 3D space, represented
  19226. * in [Hessian normal form]{@link http://mathworld.wolfram.com/HessianNormalForm.html}
  19227. * by a unit length normal vector and a constant.
  19228. */
  19229. class Plane {
  19230. /**
  19231. * Constructs a new plane.
  19232. *
  19233. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19234. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19235. */
  19236. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19237. /**
  19238. * This flag can be used for type testing.
  19239. *
  19240. * @type {boolean}
  19241. * @readonly
  19242. * @default true
  19243. */
  19244. this.isPlane = true;
  19245. /**
  19246. * A unit length vector defining the normal of the plane.
  19247. *
  19248. * @type {Vector3}
  19249. */
  19250. this.normal = normal;
  19251. /**
  19252. * The signed distance from the origin to the plane.
  19253. *
  19254. * @type {number}
  19255. * @default 0
  19256. */
  19257. this.constant = constant;
  19258. }
  19259. /**
  19260. * Sets the plane components by copying the given values.
  19261. *
  19262. * @param {Vector3} normal - The normal.
  19263. * @param {number} constant - The constant.
  19264. * @return {Plane} A reference to this plane.
  19265. */
  19266. set( normal, constant ) {
  19267. this.normal.copy( normal );
  19268. this.constant = constant;
  19269. return this;
  19270. }
  19271. /**
  19272. * Sets the plane components by defining `x`, `y`, `z` as the
  19273. * plane normal and `w` as the constant.
  19274. *
  19275. * @param {number} x - The value for the normal's x component.
  19276. * @param {number} y - The value for the normal's y component.
  19277. * @param {number} z - The value for the normal's z component.
  19278. * @param {number} w - The constant value.
  19279. * @return {Plane} A reference to this plane.
  19280. */
  19281. setComponents( x, y, z, w ) {
  19282. this.normal.set( x, y, z );
  19283. this.constant = w;
  19284. return this;
  19285. }
  19286. /**
  19287. * Sets the plane from the given normal and coplanar point (that is a point
  19288. * that lies onto the plane).
  19289. *
  19290. * @param {Vector3} normal - The normal.
  19291. * @param {Vector3} point - A coplanar point.
  19292. * @return {Plane} A reference to this plane.
  19293. */
  19294. setFromNormalAndCoplanarPoint( normal, point ) {
  19295. this.normal.copy( normal );
  19296. this.constant = - point.dot( this.normal );
  19297. return this;
  19298. }
  19299. /**
  19300. * Sets the plane from three coplanar points. The winding order is
  19301. * assumed to be counter-clockwise, and determines the direction of
  19302. * the plane normal.
  19303. *
  19304. * @param {Vector3} a - The first coplanar point.
  19305. * @param {Vector3} b - The second coplanar point.
  19306. * @param {Vector3} c - The third coplanar point.
  19307. * @return {Plane} A reference to this plane.
  19308. */
  19309. setFromCoplanarPoints( a, b, c ) {
  19310. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19311. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19312. this.setFromNormalAndCoplanarPoint( normal, a );
  19313. return this;
  19314. }
  19315. /**
  19316. * Copies the values of the given plane to this instance.
  19317. *
  19318. * @param {Plane} plane - The plane to copy.
  19319. * @return {Plane} A reference to this plane.
  19320. */
  19321. copy( plane ) {
  19322. this.normal.copy( plane.normal );
  19323. this.constant = plane.constant;
  19324. return this;
  19325. }
  19326. /**
  19327. * Normalizes the plane normal and adjusts the constant accordingly.
  19328. *
  19329. * @return {Plane} A reference to this plane.
  19330. */
  19331. normalize() {
  19332. // Note: will lead to a divide by zero if the plane is invalid.
  19333. const inverseNormalLength = 1.0 / this.normal.length();
  19334. this.normal.multiplyScalar( inverseNormalLength );
  19335. this.constant *= inverseNormalLength;
  19336. return this;
  19337. }
  19338. /**
  19339. * Negates both the plane normal and the constant.
  19340. *
  19341. * @return {Plane} A reference to this plane.
  19342. */
  19343. negate() {
  19344. this.constant *= -1;
  19345. this.normal.negate();
  19346. return this;
  19347. }
  19348. /**
  19349. * Returns the signed distance from the given point to this plane.
  19350. *
  19351. * @param {Vector3} point - The point to compute the distance for.
  19352. * @return {number} The signed distance.
  19353. */
  19354. distanceToPoint( point ) {
  19355. return this.normal.dot( point ) + this.constant;
  19356. }
  19357. /**
  19358. * Returns the signed distance from the given sphere to this plane.
  19359. *
  19360. * @param {Sphere} sphere - The sphere to compute the distance for.
  19361. * @return {number} The signed distance.
  19362. */
  19363. distanceToSphere( sphere ) {
  19364. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19365. }
  19366. /**
  19367. * Projects a the given point onto the plane.
  19368. *
  19369. * @param {Vector3} point - The point to project.
  19370. * @param {Vector3} target - The target vector that is used to store the method's result.
  19371. * @return {Vector3} The projected point on the plane.
  19372. */
  19373. projectPoint( point, target ) {
  19374. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19375. }
  19376. /**
  19377. * Returns the intersection point of the passed line and the plane. Returns
  19378. * `null` if the line does not intersect. Returns the line's starting point if
  19379. * the line is coplanar with the plane.
  19380. *
  19381. * @param {Line3} line - The line to compute the intersection for.
  19382. * @param {Vector3} target - The target vector that is used to store the method's result.
  19383. * @return {?Vector3} The intersection point.
  19384. */
  19385. intersectLine( line, target ) {
  19386. const direction = line.delta( _vector1 );
  19387. const denominator = this.normal.dot( direction );
  19388. if ( denominator === 0 ) {
  19389. // line is coplanar, return origin
  19390. if ( this.distanceToPoint( line.start ) === 0 ) {
  19391. return target.copy( line.start );
  19392. }
  19393. // Unsure if this is the correct method to handle this case.
  19394. return null;
  19395. }
  19396. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19397. if ( t < 0 || t > 1 ) {
  19398. return null;
  19399. }
  19400. return target.copy( line.start ).addScaledVector( direction, t );
  19401. }
  19402. /**
  19403. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19404. *
  19405. * @param {Line3} line - The line to test.
  19406. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19407. */
  19408. intersectsLine( line ) {
  19409. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19410. const startSign = this.distanceToPoint( line.start );
  19411. const endSign = this.distanceToPoint( line.end );
  19412. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19413. }
  19414. /**
  19415. * Returns `true` if the given bounding box intersects with the plane.
  19416. *
  19417. * @param {Box3} box - The bounding box to test.
  19418. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19419. */
  19420. intersectsBox( box ) {
  19421. return box.intersectsPlane( this );
  19422. }
  19423. /**
  19424. * Returns `true` if the given bounding sphere intersects with the plane.
  19425. *
  19426. * @param {Sphere} sphere - The bounding sphere to test.
  19427. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19428. */
  19429. intersectsSphere( sphere ) {
  19430. return sphere.intersectsPlane( this );
  19431. }
  19432. /**
  19433. * Returns a coplanar vector to the plane, by calculating the
  19434. * projection of the normal at the origin onto the plane.
  19435. *
  19436. * @param {Vector3} target - The target vector that is used to store the method's result.
  19437. * @return {Vector3} The coplanar point.
  19438. */
  19439. coplanarPoint( target ) {
  19440. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19441. }
  19442. /**
  19443. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19444. *
  19445. * The optional normal matrix can be pre-computed like so:
  19446. * ```js
  19447. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19448. * ```
  19449. *
  19450. * @param {Matrix4} matrix - The transformation matrix.
  19451. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19452. * @return {Plane} A reference to this plane.
  19453. */
  19454. applyMatrix4( matrix, optionalNormalMatrix ) {
  19455. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19456. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19457. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19458. this.constant = - referencePoint.dot( normal );
  19459. return this;
  19460. }
  19461. /**
  19462. * Translates the plane by the distance defined by the given offset vector.
  19463. * Note that this only affects the plane constant and will not affect the normal vector.
  19464. *
  19465. * @param {Vector3} offset - The offset vector.
  19466. * @return {Plane} A reference to this plane.
  19467. */
  19468. translate( offset ) {
  19469. this.constant -= offset.dot( this.normal );
  19470. return this;
  19471. }
  19472. /**
  19473. * Returns `true` if this plane is equal with the given one.
  19474. *
  19475. * @param {Plane} plane - The plane to test for equality.
  19476. * @return {boolean} Whether this plane is equal with the given one.
  19477. */
  19478. equals( plane ) {
  19479. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19480. }
  19481. /**
  19482. * Returns a new plane with copied values from this instance.
  19483. *
  19484. * @return {Plane} A clone of this instance.
  19485. */
  19486. clone() {
  19487. return new this.constructor().copy( this );
  19488. }
  19489. }
  19490. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19491. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19492. const _vector$6 = /*@__PURE__*/ new Vector3();
  19493. /**
  19494. * Frustums are used to determine what is inside the camera's field of view.
  19495. * They help speed up the rendering process - objects which lie outside a camera's
  19496. * frustum can safely be excluded from rendering.
  19497. *
  19498. * This class is mainly intended for use internally by a renderer.
  19499. */
  19500. class Frustum {
  19501. /**
  19502. * Constructs a new frustum.
  19503. *
  19504. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19505. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19506. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19507. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19508. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19509. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19510. */
  19511. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19512. /**
  19513. * This array holds the planes that enclose the frustum.
  19514. *
  19515. * @type {Array<Plane>}
  19516. */
  19517. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19518. }
  19519. /**
  19520. * Sets the frustum planes by copying the given planes.
  19521. *
  19522. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19523. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19524. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19525. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19526. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19527. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19528. * @return {Frustum} A reference to this frustum.
  19529. */
  19530. set( p0, p1, p2, p3, p4, p5 ) {
  19531. const planes = this.planes;
  19532. planes[ 0 ].copy( p0 );
  19533. planes[ 1 ].copy( p1 );
  19534. planes[ 2 ].copy( p2 );
  19535. planes[ 3 ].copy( p3 );
  19536. planes[ 4 ].copy( p4 );
  19537. planes[ 5 ].copy( p5 );
  19538. return this;
  19539. }
  19540. /**
  19541. * Copies the values of the given frustum to this instance.
  19542. *
  19543. * @param {Frustum} frustum - The frustum to copy.
  19544. * @return {Frustum} A reference to this frustum.
  19545. */
  19546. copy( frustum ) {
  19547. const planes = this.planes;
  19548. for ( let i = 0; i < 6; i ++ ) {
  19549. planes[ i ].copy( frustum.planes[ i ] );
  19550. }
  19551. return this;
  19552. }
  19553. /**
  19554. * Sets the frustum planes from the given projection matrix.
  19555. *
  19556. * @param {Matrix4} m - The projection matrix.
  19557. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19558. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19559. * @return {Frustum} A reference to this frustum.
  19560. */
  19561. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19562. const planes = this.planes;
  19563. const me = m.elements;
  19564. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19565. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19566. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19567. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19568. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19569. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19570. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19571. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19572. if ( reversedDepth ) {
  19573. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19574. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19575. } else {
  19576. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19577. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19578. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19579. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19580. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19581. } else {
  19582. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19583. }
  19584. }
  19585. return this;
  19586. }
  19587. /**
  19588. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19589. *
  19590. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19591. *
  19592. * @param {Object3D} object - The 3D object to test.
  19593. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19594. */
  19595. intersectsObject( object ) {
  19596. if ( object.boundingSphere !== undefined ) {
  19597. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19598. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19599. } else {
  19600. const geometry = object.geometry;
  19601. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19602. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19603. }
  19604. return this.intersectsSphere( _sphere$3 );
  19605. }
  19606. /**
  19607. * Returns `true` if the given sprite is intersecting this frustum.
  19608. *
  19609. * @param {Sprite} sprite - The sprite to test.
  19610. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19611. */
  19612. intersectsSprite( sprite ) {
  19613. _sphere$3.center.set( 0, 0, 0 );
  19614. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19615. _sphere$3.radius = 0.7071067811865476 + offset;
  19616. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19617. return this.intersectsSphere( _sphere$3 );
  19618. }
  19619. /**
  19620. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19621. *
  19622. * @param {Sphere} sphere - The bounding sphere to test.
  19623. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19624. */
  19625. intersectsSphere( sphere ) {
  19626. const planes = this.planes;
  19627. const center = sphere.center;
  19628. const negRadius = - sphere.radius;
  19629. for ( let i = 0; i < 6; i ++ ) {
  19630. const distance = planes[ i ].distanceToPoint( center );
  19631. if ( distance < negRadius ) {
  19632. return false;
  19633. }
  19634. }
  19635. return true;
  19636. }
  19637. /**
  19638. * Returns `true` if the given bounding box is intersecting this frustum.
  19639. *
  19640. * @param {Box3} box - The bounding box to test.
  19641. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19642. */
  19643. intersectsBox( box ) {
  19644. const planes = this.planes;
  19645. for ( let i = 0; i < 6; i ++ ) {
  19646. const plane = planes[ i ];
  19647. // corner at max distance
  19648. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19649. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19650. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19651. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19652. return false;
  19653. }
  19654. }
  19655. return true;
  19656. }
  19657. /**
  19658. * Returns `true` if the given point lies within the frustum.
  19659. *
  19660. * @param {Vector3} point - The point to test.
  19661. * @return {boolean} Whether the point lies within this frustum or not.
  19662. */
  19663. containsPoint( point ) {
  19664. const planes = this.planes;
  19665. for ( let i = 0; i < 6; i ++ ) {
  19666. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19667. return false;
  19668. }
  19669. }
  19670. return true;
  19671. }
  19672. /**
  19673. * Returns a new frustum with copied values from this instance.
  19674. *
  19675. * @return {Frustum} A clone of this instance.
  19676. */
  19677. clone() {
  19678. return new this.constructor().copy( this );
  19679. }
  19680. }
  19681. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19682. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19683. /**
  19684. * FrustumArray is used to determine if an object is visible in at least one camera
  19685. * from an array of cameras. This is particularly useful for multi-view renderers.
  19686. */
  19687. class FrustumArray {
  19688. /**
  19689. * Constructs a new frustum array.
  19690. *
  19691. */
  19692. constructor() {
  19693. /**
  19694. * The coordinate system to use.
  19695. *
  19696. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19697. * @default WebGLCoordinateSystem
  19698. */
  19699. this.coordinateSystem = WebGLCoordinateSystem;
  19700. }
  19701. /**
  19702. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19703. * from the camera array.
  19704. *
  19705. * @param {Object3D} object - The 3D object to test.
  19706. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19707. * @return {boolean} Whether the 3D object is visible in any camera.
  19708. */
  19709. intersectsObject( object, cameraArray ) {
  19710. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19711. return false;
  19712. }
  19713. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19714. const camera = cameraArray.cameras[ i ];
  19715. _projScreenMatrix$2.multiplyMatrices(
  19716. camera.projectionMatrix,
  19717. camera.matrixWorldInverse
  19718. );
  19719. _frustum$1.setFromProjectionMatrix(
  19720. _projScreenMatrix$2,
  19721. camera.coordinateSystem,
  19722. camera.reversedDepth
  19723. );
  19724. if ( _frustum$1.intersectsObject( object ) ) {
  19725. return true; // Object is visible in at least one camera
  19726. }
  19727. }
  19728. return false; // Not visible in any camera
  19729. }
  19730. /**
  19731. * Returns `true` if the given sprite is intersecting any frustum
  19732. * from the camera array.
  19733. *
  19734. * @param {Sprite} sprite - The sprite to test.
  19735. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19736. * @return {boolean} Whether the sprite is visible in any camera.
  19737. */
  19738. intersectsSprite( sprite, cameraArray ) {
  19739. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19740. return false;
  19741. }
  19742. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19743. const camera = cameraArray.cameras[ i ];
  19744. _projScreenMatrix$2.multiplyMatrices(
  19745. camera.projectionMatrix,
  19746. camera.matrixWorldInverse
  19747. );
  19748. _frustum$1.setFromProjectionMatrix(
  19749. _projScreenMatrix$2,
  19750. camera.coordinateSystem,
  19751. camera.reversedDepth
  19752. );
  19753. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19754. return true; // Sprite is visible in at least one camera
  19755. }
  19756. }
  19757. return false; // Not visible in any camera
  19758. }
  19759. /**
  19760. * Returns `true` if the given bounding sphere is intersecting any frustum
  19761. * from the camera array.
  19762. *
  19763. * @param {Sphere} sphere - The bounding sphere to test.
  19764. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19765. * @return {boolean} Whether the sphere is visible in any camera.
  19766. */
  19767. intersectsSphere( sphere, cameraArray ) {
  19768. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19769. return false;
  19770. }
  19771. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19772. const camera = cameraArray.cameras[ i ];
  19773. _projScreenMatrix$2.multiplyMatrices(
  19774. camera.projectionMatrix,
  19775. camera.matrixWorldInverse
  19776. );
  19777. _frustum$1.setFromProjectionMatrix(
  19778. _projScreenMatrix$2,
  19779. camera.coordinateSystem,
  19780. camera.reversedDepth
  19781. );
  19782. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19783. return true; // Sphere is visible in at least one camera
  19784. }
  19785. }
  19786. return false; // Not visible in any camera
  19787. }
  19788. /**
  19789. * Returns `true` if the given bounding box is intersecting any frustum
  19790. * from the camera array.
  19791. *
  19792. * @param {Box3} box - The bounding box to test.
  19793. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19794. * @return {boolean} Whether the box is visible in any camera.
  19795. */
  19796. intersectsBox( box, cameraArray ) {
  19797. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19798. return false;
  19799. }
  19800. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19801. const camera = cameraArray.cameras[ i ];
  19802. _projScreenMatrix$2.multiplyMatrices(
  19803. camera.projectionMatrix,
  19804. camera.matrixWorldInverse
  19805. );
  19806. _frustum$1.setFromProjectionMatrix(
  19807. _projScreenMatrix$2,
  19808. camera.coordinateSystem,
  19809. camera.reversedDepth
  19810. );
  19811. if ( _frustum$1.intersectsBox( box ) ) {
  19812. return true; // Box is visible in at least one camera
  19813. }
  19814. }
  19815. return false; // Not visible in any camera
  19816. }
  19817. /**
  19818. * Returns `true` if the given point lies within any frustum
  19819. * from the camera array.
  19820. *
  19821. * @param {Vector3} point - The point to test.
  19822. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19823. * @return {boolean} Whether the point is visible in any camera.
  19824. */
  19825. containsPoint( point, cameraArray ) {
  19826. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19827. return false;
  19828. }
  19829. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19830. const camera = cameraArray.cameras[ i ];
  19831. _projScreenMatrix$2.multiplyMatrices(
  19832. camera.projectionMatrix,
  19833. camera.matrixWorldInverse
  19834. );
  19835. _frustum$1.setFromProjectionMatrix(
  19836. _projScreenMatrix$2,
  19837. camera.coordinateSystem,
  19838. camera.reversedDepth
  19839. );
  19840. if ( _frustum$1.containsPoint( point ) ) {
  19841. return true; // Point is visible in at least one camera
  19842. }
  19843. }
  19844. return false; // Not visible in any camera
  19845. }
  19846. /**
  19847. * Returns a new frustum array with copied values from this instance.
  19848. *
  19849. * @return {FrustumArray} A clone of this instance.
  19850. */
  19851. clone() {
  19852. return new FrustumArray();
  19853. }
  19854. }
  19855. function ascIdSort( a, b ) {
  19856. return a - b;
  19857. }
  19858. function sortOpaque( a, b ) {
  19859. return a.z - b.z;
  19860. }
  19861. function sortTransparent( a, b ) {
  19862. return b.z - a.z;
  19863. }
  19864. class MultiDrawRenderList {
  19865. constructor() {
  19866. this.index = 0;
  19867. this.pool = [];
  19868. this.list = [];
  19869. }
  19870. push( start, count, z, index ) {
  19871. const pool = this.pool;
  19872. const list = this.list;
  19873. if ( this.index >= pool.length ) {
  19874. pool.push( {
  19875. start: -1,
  19876. count: -1,
  19877. z: -1,
  19878. index: -1,
  19879. } );
  19880. }
  19881. const item = pool[ this.index ];
  19882. list.push( item );
  19883. this.index ++;
  19884. item.start = start;
  19885. item.count = count;
  19886. item.z = z;
  19887. item.index = index;
  19888. }
  19889. reset() {
  19890. this.list.length = 0;
  19891. this.index = 0;
  19892. }
  19893. }
  19894. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19895. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19896. const _frustum = /*@__PURE__*/ new Frustum();
  19897. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19898. const _box$1 = /*@__PURE__*/ new Box3();
  19899. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19900. const _vector$5 = /*@__PURE__*/ new Vector3();
  19901. const _forward$1 = /*@__PURE__*/ new Vector3();
  19902. const _temp = /*@__PURE__*/ new Vector3();
  19903. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19904. const _mesh = /*@__PURE__*/ new Mesh();
  19905. const _batchIntersects = [];
  19906. // copies data from attribute "src" into "target" starting at "targetOffset"
  19907. function copyAttributeData( src, target, targetOffset = 0 ) {
  19908. const itemSize = target.itemSize;
  19909. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19910. // use the component getters and setters if the array data cannot
  19911. // be copied directly
  19912. const vertexCount = src.count;
  19913. for ( let i = 0; i < vertexCount; i ++ ) {
  19914. for ( let c = 0; c < itemSize; c ++ ) {
  19915. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19916. }
  19917. }
  19918. } else {
  19919. // faster copy approach using typed array set function
  19920. target.array.set( src.array, targetOffset * itemSize );
  19921. }
  19922. target.needsUpdate = true;
  19923. }
  19924. // safely copies array contents to a potentially smaller array
  19925. function copyArrayContents( src, target ) {
  19926. if ( src.constructor !== target.constructor ) {
  19927. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  19928. const len = Math.min( src.length, target.length );
  19929. for ( let i = 0; i < len; i ++ ) {
  19930. target[ i ] = src[ i ];
  19931. }
  19932. } else {
  19933. // if the arrays use the same data layout we can use a fast block copy
  19934. const len = Math.min( src.length, target.length );
  19935. target.set( new src.constructor( src.buffer, 0, len ) );
  19936. }
  19937. }
  19938. /**
  19939. * A special version of a mesh with multi draw batch rendering support. Use
  19940. * this class if you have to render a large number of objects with the same
  19941. * material but with different geometries or world transformations. The usage of
  19942. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  19943. * rendering performance in your application.
  19944. *
  19945. * ```js
  19946. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  19947. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  19948. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  19949. *
  19950. * // initialize and add geometries into the batched mesh
  19951. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  19952. * const boxGeometryId = batchedMesh.addGeometry( box );
  19953. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  19954. *
  19955. * // create instances of those geometries
  19956. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  19957. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  19958. *
  19959. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  19960. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  19961. *
  19962. * // position the geometries
  19963. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  19964. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  19965. *
  19966. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  19967. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  19968. *
  19969. * scene.add( batchedMesh );
  19970. * ```
  19971. *
  19972. * @augments Mesh
  19973. */
  19974. class BatchedMesh extends Mesh {
  19975. /**
  19976. * Constructs a new batched mesh.
  19977. *
  19978. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  19979. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  19980. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  19981. * @param {Material|Array<Material>} [material] - The mesh material.
  19982. */
  19983. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  19984. super( new BufferGeometry(), material );
  19985. /**
  19986. * This flag can be used for type testing.
  19987. *
  19988. * @type {boolean}
  19989. * @readonly
  19990. * @default true
  19991. */
  19992. this.isBatchedMesh = true;
  19993. /**
  19994. * When set ot `true`, the individual objects of a batch are frustum culled.
  19995. *
  19996. * @type {boolean}
  19997. * @default true
  19998. */
  19999. this.perObjectFrustumCulled = true;
  20000. /**
  20001. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20002. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20003. * rendered front to back.
  20004. *
  20005. * @type {boolean}
  20006. * @default true
  20007. */
  20008. this.sortObjects = true;
  20009. /**
  20010. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20011. *
  20012. * @type {?Box3}
  20013. * @default null
  20014. */
  20015. this.boundingBox = null;
  20016. /**
  20017. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20018. *
  20019. * @type {?Sphere}
  20020. * @default null
  20021. */
  20022. this.boundingSphere = null;
  20023. /**
  20024. * Takes a sort a function that is run before render. The function takes a list of instances to
  20025. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20026. * sort with.
  20027. *
  20028. * @type {?Function}
  20029. * @default null
  20030. */
  20031. this.customSort = null;
  20032. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20033. this._instanceInfo = [];
  20034. this._geometryInfo = [];
  20035. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20036. this._availableInstanceIds = [];
  20037. this._availableGeometryIds = [];
  20038. // used to track where the next point is that geometry should be inserted
  20039. this._nextIndexStart = 0;
  20040. this._nextVertexStart = 0;
  20041. this._geometryCount = 0;
  20042. // flags
  20043. this._visibilityChanged = true;
  20044. this._geometryInitialized = false;
  20045. // cached user options
  20046. this._maxInstanceCount = maxInstanceCount;
  20047. this._maxVertexCount = maxVertexCount;
  20048. this._maxIndexCount = maxIndexCount;
  20049. // buffers for multi draw
  20050. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20051. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20052. this._multiDrawCount = 0;
  20053. this._multiDrawInstances = null;
  20054. // Local matrix per geometry by using data texture
  20055. this._matricesTexture = null;
  20056. this._indirectTexture = null;
  20057. this._colorsTexture = null;
  20058. this._initMatricesTexture();
  20059. this._initIndirectTexture();
  20060. }
  20061. /**
  20062. * The maximum number of individual instances that can be stored in the batch.
  20063. *
  20064. * @type {number}
  20065. * @readonly
  20066. */
  20067. get maxInstanceCount() {
  20068. return this._maxInstanceCount;
  20069. }
  20070. /**
  20071. * The instance count.
  20072. *
  20073. * @type {number}
  20074. * @readonly
  20075. */
  20076. get instanceCount() {
  20077. return this._instanceInfo.length - this._availableInstanceIds.length;
  20078. }
  20079. /**
  20080. * The number of unused vertices.
  20081. *
  20082. * @type {number}
  20083. * @readonly
  20084. */
  20085. get unusedVertexCount() {
  20086. return this._maxVertexCount - this._nextVertexStart;
  20087. }
  20088. /**
  20089. * The number of unused indices.
  20090. *
  20091. * @type {number}
  20092. * @readonly
  20093. */
  20094. get unusedIndexCount() {
  20095. return this._maxIndexCount - this._nextIndexStart;
  20096. }
  20097. _initMatricesTexture() {
  20098. // layout (1 matrix = 4 pixels)
  20099. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20100. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20101. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20102. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20103. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20104. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20105. size = Math.ceil( size / 4 ) * 4;
  20106. size = Math.max( size, 4 );
  20107. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20108. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20109. this._matricesTexture = matricesTexture;
  20110. }
  20111. _initIndirectTexture() {
  20112. let size = Math.sqrt( this._maxInstanceCount );
  20113. size = Math.ceil( size );
  20114. const indirectArray = new Uint32Array( size * size );
  20115. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20116. this._indirectTexture = indirectTexture;
  20117. }
  20118. _initColorsTexture() {
  20119. let size = Math.sqrt( this._maxInstanceCount );
  20120. size = Math.ceil( size );
  20121. // 4 floats per RGBA pixel initialized to white
  20122. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20123. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20124. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20125. this._colorsTexture = colorsTexture;
  20126. }
  20127. _initializeGeometry( reference ) {
  20128. const geometry = this.geometry;
  20129. const maxVertexCount = this._maxVertexCount;
  20130. const maxIndexCount = this._maxIndexCount;
  20131. if ( this._geometryInitialized === false ) {
  20132. for ( const attributeName in reference.attributes ) {
  20133. const srcAttribute = reference.getAttribute( attributeName );
  20134. const { array, itemSize, normalized } = srcAttribute;
  20135. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20136. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20137. geometry.setAttribute( attributeName, dstAttribute );
  20138. }
  20139. if ( reference.getIndex() !== null ) {
  20140. // Reserve last u16 index for primitive restart.
  20141. const indexArray = maxVertexCount > 65535
  20142. ? new Uint32Array( maxIndexCount )
  20143. : new Uint16Array( maxIndexCount );
  20144. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20145. }
  20146. this._geometryInitialized = true;
  20147. }
  20148. }
  20149. // Make sure the geometry is compatible with the existing combined geometry attributes
  20150. _validateGeometry( geometry ) {
  20151. // check to ensure the geometries are using consistent attributes and indices
  20152. const batchGeometry = this.geometry;
  20153. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20154. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20155. }
  20156. for ( const attributeName in batchGeometry.attributes ) {
  20157. if ( ! geometry.hasAttribute( attributeName ) ) {
  20158. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20159. }
  20160. const srcAttribute = geometry.getAttribute( attributeName );
  20161. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20162. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20163. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20164. }
  20165. }
  20166. }
  20167. /**
  20168. * Validates the instance defined by the given ID.
  20169. *
  20170. * @param {number} instanceId - The instance to validate.
  20171. */
  20172. validateInstanceId( instanceId ) {
  20173. const instanceInfo = this._instanceInfo;
  20174. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20175. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20176. }
  20177. }
  20178. /**
  20179. * Validates the geometry defined by the given ID.
  20180. *
  20181. * @param {number} geometryId - The geometry to validate.
  20182. */
  20183. validateGeometryId( geometryId ) {
  20184. const geometryInfoList = this._geometryInfo;
  20185. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20186. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20187. }
  20188. }
  20189. /**
  20190. * Takes a sort a function that is run before render. The function takes a list of instances to
  20191. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20192. *
  20193. * @param {Function} func - The custom sort function.
  20194. * @return {BatchedMesh} A reference to this batched mesh.
  20195. */
  20196. setCustomSort( func ) {
  20197. this.customSort = func;
  20198. return this;
  20199. }
  20200. /**
  20201. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20202. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20203. * otherwise they are `null`.
  20204. */
  20205. computeBoundingBox() {
  20206. if ( this.boundingBox === null ) {
  20207. this.boundingBox = new Box3();
  20208. }
  20209. const boundingBox = this.boundingBox;
  20210. const instanceInfo = this._instanceInfo;
  20211. boundingBox.makeEmpty();
  20212. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20213. if ( instanceInfo[ i ].active === false ) continue;
  20214. const geometryId = instanceInfo[ i ].geometryIndex;
  20215. this.getMatrixAt( i, _matrix$1 );
  20216. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20217. boundingBox.union( _box$1 );
  20218. }
  20219. }
  20220. /**
  20221. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20222. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20223. * otherwise they are `null`.
  20224. */
  20225. computeBoundingSphere() {
  20226. if ( this.boundingSphere === null ) {
  20227. this.boundingSphere = new Sphere();
  20228. }
  20229. const boundingSphere = this.boundingSphere;
  20230. const instanceInfo = this._instanceInfo;
  20231. boundingSphere.makeEmpty();
  20232. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20233. if ( instanceInfo[ i ].active === false ) continue;
  20234. const geometryId = instanceInfo[ i ].geometryIndex;
  20235. this.getMatrixAt( i, _matrix$1 );
  20236. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20237. boundingSphere.union( _sphere$2 );
  20238. }
  20239. }
  20240. /**
  20241. * Adds a new instance to the batch using the geometry of the given ID and returns
  20242. * a new id referring to the new instance to be used by other functions.
  20243. *
  20244. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20245. * @return {number} The instance ID.
  20246. */
  20247. addInstance( geometryId ) {
  20248. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20249. // ensure we're not over geometry
  20250. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20251. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20252. }
  20253. const instanceInfo = {
  20254. visible: true,
  20255. active: true,
  20256. geometryIndex: geometryId,
  20257. };
  20258. let drawId = null;
  20259. // Prioritize using previously freed instance ids
  20260. if ( this._availableInstanceIds.length > 0 ) {
  20261. this._availableInstanceIds.sort( ascIdSort );
  20262. drawId = this._availableInstanceIds.shift();
  20263. this._instanceInfo[ drawId ] = instanceInfo;
  20264. } else {
  20265. drawId = this._instanceInfo.length;
  20266. this._instanceInfo.push( instanceInfo );
  20267. }
  20268. const matricesTexture = this._matricesTexture;
  20269. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20270. matricesTexture.needsUpdate = true;
  20271. const colorsTexture = this._colorsTexture;
  20272. if ( colorsTexture ) {
  20273. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20274. colorsTexture.needsUpdate = true;
  20275. }
  20276. this._visibilityChanged = true;
  20277. return drawId;
  20278. }
  20279. /**
  20280. * Adds the given geometry to the batch and returns the associated
  20281. * geometry id referring to it to be used in other functions.
  20282. *
  20283. * @param {BufferGeometry} geometry - The geometry to add.
  20284. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20285. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20286. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20287. * Defaults to the length of the given geometry vertex buffer.
  20288. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20289. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20290. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20291. * the length of the given geometry index buffer.
  20292. * @return {number} The geometry ID.
  20293. */
  20294. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20295. this._initializeGeometry( geometry );
  20296. this._validateGeometry( geometry );
  20297. const geometryInfo = {
  20298. // geometry information
  20299. vertexStart: -1,
  20300. vertexCount: -1,
  20301. reservedVertexCount: -1,
  20302. indexStart: -1,
  20303. indexCount: -1,
  20304. reservedIndexCount: -1,
  20305. // draw range information
  20306. start: -1,
  20307. count: -1,
  20308. // state
  20309. boundingBox: null,
  20310. boundingSphere: null,
  20311. active: true,
  20312. };
  20313. const geometryInfoList = this._geometryInfo;
  20314. geometryInfo.vertexStart = this._nextVertexStart;
  20315. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20316. const index = geometry.getIndex();
  20317. const hasIndex = index !== null;
  20318. if ( hasIndex ) {
  20319. geometryInfo.indexStart = this._nextIndexStart;
  20320. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20321. }
  20322. if (
  20323. geometryInfo.indexStart !== -1 &&
  20324. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20325. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20326. ) {
  20327. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20328. }
  20329. // update id
  20330. let geometryId;
  20331. if ( this._availableGeometryIds.length > 0 ) {
  20332. this._availableGeometryIds.sort( ascIdSort );
  20333. geometryId = this._availableGeometryIds.shift();
  20334. geometryInfoList[ geometryId ] = geometryInfo;
  20335. } else {
  20336. geometryId = this._geometryCount;
  20337. this._geometryCount ++;
  20338. geometryInfoList.push( geometryInfo );
  20339. }
  20340. // update the geometry
  20341. this.setGeometryAt( geometryId, geometry );
  20342. // increment the next geometry position
  20343. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20344. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20345. return geometryId;
  20346. }
  20347. /**
  20348. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20349. * is not enough space reserved for geometry. Calling this will change all instances that are
  20350. * rendering that geometry.
  20351. *
  20352. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20353. * @param {BufferGeometry} geometry - The new geometry.
  20354. * @return {number} The geometry ID.
  20355. */
  20356. setGeometryAt( geometryId, geometry ) {
  20357. if ( geometryId >= this._geometryCount ) {
  20358. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20359. }
  20360. this._validateGeometry( geometry );
  20361. const batchGeometry = this.geometry;
  20362. const hasIndex = batchGeometry.getIndex() !== null;
  20363. const dstIndex = batchGeometry.getIndex();
  20364. const srcIndex = geometry.getIndex();
  20365. const geometryInfo = this._geometryInfo[ geometryId ];
  20366. if (
  20367. hasIndex &&
  20368. srcIndex.count > geometryInfo.reservedIndexCount ||
  20369. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20370. ) {
  20371. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20372. }
  20373. // copy geometry buffer data over
  20374. const vertexStart = geometryInfo.vertexStart;
  20375. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20376. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20377. for ( const attributeName in batchGeometry.attributes ) {
  20378. // copy attribute data
  20379. const srcAttribute = geometry.getAttribute( attributeName );
  20380. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20381. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20382. // fill the rest in with zeroes
  20383. const itemSize = srcAttribute.itemSize;
  20384. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20385. const index = vertexStart + i;
  20386. for ( let c = 0; c < itemSize; c ++ ) {
  20387. dstAttribute.setComponent( index, c, 0 );
  20388. }
  20389. }
  20390. dstAttribute.needsUpdate = true;
  20391. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20392. }
  20393. // copy index
  20394. if ( hasIndex ) {
  20395. const indexStart = geometryInfo.indexStart;
  20396. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20397. geometryInfo.indexCount = geometry.getIndex().count;
  20398. // copy index data over
  20399. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20400. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20401. }
  20402. // fill the rest in with zeroes
  20403. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20404. dstIndex.setX( indexStart + i, vertexStart );
  20405. }
  20406. dstIndex.needsUpdate = true;
  20407. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20408. }
  20409. // update the draw range
  20410. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20411. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20412. // store the bounding boxes
  20413. geometryInfo.boundingBox = null;
  20414. if ( geometry.boundingBox !== null ) {
  20415. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20416. }
  20417. geometryInfo.boundingSphere = null;
  20418. if ( geometry.boundingSphere !== null ) {
  20419. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20420. }
  20421. this._visibilityChanged = true;
  20422. return geometryId;
  20423. }
  20424. /**
  20425. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20426. * this geometry will also be removed as a side effect.
  20427. *
  20428. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20429. * @return {BatchedMesh} A reference to this batched mesh.
  20430. */
  20431. deleteGeometry( geometryId ) {
  20432. const geometryInfoList = this._geometryInfo;
  20433. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20434. return this;
  20435. }
  20436. // delete any instances associated with this geometry
  20437. const instanceInfo = this._instanceInfo;
  20438. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20439. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20440. this.deleteInstance( i );
  20441. }
  20442. }
  20443. geometryInfoList[ geometryId ].active = false;
  20444. this._availableGeometryIds.push( geometryId );
  20445. this._visibilityChanged = true;
  20446. return this;
  20447. }
  20448. /**
  20449. * Deletes an existing instance from the batch using the given ID.
  20450. *
  20451. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20452. * @return {BatchedMesh} A reference to this batched mesh.
  20453. */
  20454. deleteInstance( instanceId ) {
  20455. this.validateInstanceId( instanceId );
  20456. this._instanceInfo[ instanceId ].active = false;
  20457. this._availableInstanceIds.push( instanceId );
  20458. this._visibilityChanged = true;
  20459. return this;
  20460. }
  20461. /**
  20462. * Repacks the sub geometries in [name] to remove any unused space remaining from
  20463. * previously deleted geometry, freeing up space to add new geometry.
  20464. *
  20465. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20466. * @return {BatchedMesh} A reference to this batched mesh.
  20467. */
  20468. optimize() {
  20469. // track the next indices to copy data to
  20470. let nextVertexStart = 0;
  20471. let nextIndexStart = 0;
  20472. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20473. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20474. const geometryInfoList = this._geometryInfo;
  20475. const indices = geometryInfoList
  20476. .map( ( e, i ) => i )
  20477. .sort( ( a, b ) => {
  20478. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20479. } );
  20480. const geometry = this.geometry;
  20481. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20482. // if a geometry range is inactive then don't copy anything
  20483. const index = indices[ i ];
  20484. const geometryInfo = geometryInfoList[ index ];
  20485. if ( geometryInfo.active === false ) {
  20486. continue;
  20487. }
  20488. // if a geometry contains an index buffer then shift it, as well
  20489. if ( geometry.index !== null ) {
  20490. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20491. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20492. const index = geometry.index;
  20493. const array = index.array;
  20494. // shift the index pointers based on how the vertex data will shift
  20495. // adjusting the index must happen first so the original vertex start value is available
  20496. const elementDelta = nextVertexStart - vertexStart;
  20497. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20498. array[ j ] = array[ j ] + elementDelta;
  20499. }
  20500. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20501. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20502. geometryInfo.indexStart = nextIndexStart;
  20503. }
  20504. nextIndexStart += geometryInfo.reservedIndexCount;
  20505. }
  20506. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20507. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20508. const { vertexStart, reservedVertexCount } = geometryInfo;
  20509. const attributes = geometry.attributes;
  20510. for ( const key in attributes ) {
  20511. const attribute = attributes[ key ];
  20512. const { array, itemSize } = attribute;
  20513. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20514. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20515. }
  20516. geometryInfo.vertexStart = nextVertexStart;
  20517. }
  20518. nextVertexStart += geometryInfo.reservedVertexCount;
  20519. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20520. // step the next geometry points to the shifted position
  20521. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20522. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20523. }
  20524. return this;
  20525. }
  20526. /**
  20527. * Returns the bounding box for the given geometry.
  20528. *
  20529. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20530. * @param {Box3} target - The target object that is used to store the method's result.
  20531. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20532. */
  20533. getBoundingBoxAt( geometryId, target ) {
  20534. if ( geometryId >= this._geometryCount ) {
  20535. return null;
  20536. }
  20537. // compute bounding box
  20538. const geometry = this.geometry;
  20539. const geometryInfo = this._geometryInfo[ geometryId ];
  20540. if ( geometryInfo.boundingBox === null ) {
  20541. const box = new Box3();
  20542. const index = geometry.index;
  20543. const position = geometry.attributes.position;
  20544. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20545. let iv = i;
  20546. if ( index ) {
  20547. iv = index.getX( iv );
  20548. }
  20549. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20550. }
  20551. geometryInfo.boundingBox = box;
  20552. }
  20553. target.copy( geometryInfo.boundingBox );
  20554. return target;
  20555. }
  20556. /**
  20557. * Returns the bounding sphere for the given geometry.
  20558. *
  20559. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20560. * @param {Sphere} target - The target object that is used to store the method's result.
  20561. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20562. */
  20563. getBoundingSphereAt( geometryId, target ) {
  20564. if ( geometryId >= this._geometryCount ) {
  20565. return null;
  20566. }
  20567. // compute bounding sphere
  20568. const geometry = this.geometry;
  20569. const geometryInfo = this._geometryInfo[ geometryId ];
  20570. if ( geometryInfo.boundingSphere === null ) {
  20571. const sphere = new Sphere();
  20572. this.getBoundingBoxAt( geometryId, _box$1 );
  20573. _box$1.getCenter( sphere.center );
  20574. const index = geometry.index;
  20575. const position = geometry.attributes.position;
  20576. let maxRadiusSq = 0;
  20577. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20578. let iv = i;
  20579. if ( index ) {
  20580. iv = index.getX( iv );
  20581. }
  20582. _vector$5.fromBufferAttribute( position, iv );
  20583. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20584. }
  20585. sphere.radius = Math.sqrt( maxRadiusSq );
  20586. geometryInfo.boundingSphere = sphere;
  20587. }
  20588. target.copy( geometryInfo.boundingSphere );
  20589. return target;
  20590. }
  20591. /**
  20592. * Sets the given local transformation matrix to the defined instance.
  20593. * Negatively scaled matrices are not supported.
  20594. *
  20595. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20596. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20597. * @return {BatchedMesh} A reference to this batched mesh.
  20598. */
  20599. setMatrixAt( instanceId, matrix ) {
  20600. this.validateInstanceId( instanceId );
  20601. const matricesTexture = this._matricesTexture;
  20602. const matricesArray = this._matricesTexture.image.data;
  20603. matrix.toArray( matricesArray, instanceId * 16 );
  20604. matricesTexture.needsUpdate = true;
  20605. return this;
  20606. }
  20607. /**
  20608. * Returns the local transformation matrix of the defined instance.
  20609. *
  20610. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20611. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20612. * @return {Matrix4} The instance's local transformation matrix.
  20613. */
  20614. getMatrixAt( instanceId, matrix ) {
  20615. this.validateInstanceId( instanceId );
  20616. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20617. }
  20618. /**
  20619. * Sets the given color to the defined instance.
  20620. *
  20621. * @param {number} instanceId - The ID of an instance to set the color of.
  20622. * @param {Color} color - The color to set the instance to.
  20623. * @return {BatchedMesh} A reference to this batched mesh.
  20624. */
  20625. setColorAt( instanceId, color ) {
  20626. this.validateInstanceId( instanceId );
  20627. if ( this._colorsTexture === null ) {
  20628. this._initColorsTexture();
  20629. }
  20630. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20631. this._colorsTexture.needsUpdate = true;
  20632. return this;
  20633. }
  20634. /**
  20635. * Returns the color of the defined instance.
  20636. *
  20637. * @param {number} instanceId - The ID of an instance to get the color of.
  20638. * @param {Color} color - The target object that is used to store the method's result.
  20639. * @return {Color} The instance's color.
  20640. */
  20641. getColorAt( instanceId, color ) {
  20642. this.validateInstanceId( instanceId );
  20643. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20644. }
  20645. /**
  20646. * Sets the visibility of the instance.
  20647. *
  20648. * @param {number} instanceId - The id of the instance to set the visibility of.
  20649. * @param {boolean} visible - Whether the instance is visible or not.
  20650. * @return {BatchedMesh} A reference to this batched mesh.
  20651. */
  20652. setVisibleAt( instanceId, visible ) {
  20653. this.validateInstanceId( instanceId );
  20654. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20655. return this;
  20656. }
  20657. this._instanceInfo[ instanceId ].visible = visible;
  20658. this._visibilityChanged = true;
  20659. return this;
  20660. }
  20661. /**
  20662. * Returns the visibility state of the defined instance.
  20663. *
  20664. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20665. * @return {boolean} Whether the instance is visible or not.
  20666. */
  20667. getVisibleAt( instanceId ) {
  20668. this.validateInstanceId( instanceId );
  20669. return this._instanceInfo[ instanceId ].visible;
  20670. }
  20671. /**
  20672. * Sets the geometry ID of the instance at the given index.
  20673. *
  20674. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20675. * @param {number} geometryId - The geometry ID to be use by the instance.
  20676. * @return {BatchedMesh} A reference to this batched mesh.
  20677. */
  20678. setGeometryIdAt( instanceId, geometryId ) {
  20679. this.validateInstanceId( instanceId );
  20680. this.validateGeometryId( geometryId );
  20681. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20682. return this;
  20683. }
  20684. /**
  20685. * Returns the geometry ID of the defined instance.
  20686. *
  20687. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20688. * @return {number} The instance's geometry ID.
  20689. */
  20690. getGeometryIdAt( instanceId ) {
  20691. this.validateInstanceId( instanceId );
  20692. return this._instanceInfo[ instanceId ].geometryIndex;
  20693. }
  20694. /**
  20695. * Get the range representing the subset of triangles related to the attached geometry,
  20696. * indicating the starting offset and count, or `null` if invalid.
  20697. *
  20698. * @param {number} geometryId - The id of the geometry to get the range of.
  20699. * @param {Object} [target] - The target object that is used to store the method's result.
  20700. * @return {{
  20701. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20702. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20703. * start:number,count:number
  20704. * }} The result object with range data.
  20705. */
  20706. getGeometryRangeAt( geometryId, target = {} ) {
  20707. this.validateGeometryId( geometryId );
  20708. const geometryInfo = this._geometryInfo[ geometryId ];
  20709. target.vertexStart = geometryInfo.vertexStart;
  20710. target.vertexCount = geometryInfo.vertexCount;
  20711. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20712. target.indexStart = geometryInfo.indexStart;
  20713. target.indexCount = geometryInfo.indexCount;
  20714. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20715. target.start = geometryInfo.start;
  20716. target.count = geometryInfo.count;
  20717. return target;
  20718. }
  20719. /**
  20720. * Resizes the necessary buffers to support the provided number of instances.
  20721. * If the provided arguments shrink the number of instances but there are not enough
  20722. * unused Ids at the end of the list then an error is thrown.
  20723. *
  20724. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20725. */
  20726. setInstanceCount( maxInstanceCount ) {
  20727. // shrink the available instances as much as possible
  20728. const availableInstanceIds = this._availableInstanceIds;
  20729. const instanceInfo = this._instanceInfo;
  20730. availableInstanceIds.sort( ascIdSort );
  20731. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20732. instanceInfo.pop();
  20733. availableInstanceIds.pop();
  20734. }
  20735. // throw an error if it can't be shrunk to the desired size
  20736. if ( maxInstanceCount < instanceInfo.length ) {
  20737. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20738. }
  20739. // copy the multi draw counts
  20740. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20741. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20742. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20743. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20744. this._multiDrawCounts = multiDrawCounts;
  20745. this._multiDrawStarts = multiDrawStarts;
  20746. this._maxInstanceCount = maxInstanceCount;
  20747. // update texture data for instance sampling
  20748. const indirectTexture = this._indirectTexture;
  20749. const matricesTexture = this._matricesTexture;
  20750. const colorsTexture = this._colorsTexture;
  20751. indirectTexture.dispose();
  20752. this._initIndirectTexture();
  20753. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20754. matricesTexture.dispose();
  20755. this._initMatricesTexture();
  20756. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20757. if ( colorsTexture ) {
  20758. colorsTexture.dispose();
  20759. this._initColorsTexture();
  20760. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20761. }
  20762. }
  20763. /**
  20764. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20765. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20766. * end of the geometry attributes then an error is thrown.
  20767. *
  20768. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20769. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20770. */
  20771. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20772. // Check if we can shrink to the requested vertex attribute size
  20773. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20774. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20775. if ( requiredVertexLength > maxVertexCount ) {
  20776. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20777. }
  20778. // Check if we can shrink to the requested index attribute size
  20779. if ( this.geometry.index ) {
  20780. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20781. if ( requiredIndexLength > maxIndexCount ) {
  20782. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20783. }
  20784. }
  20785. //
  20786. // dispose of the previous geometry
  20787. const oldGeometry = this.geometry;
  20788. oldGeometry.dispose();
  20789. // recreate the geometry needed based on the previous variant
  20790. this._maxVertexCount = maxVertexCount;
  20791. this._maxIndexCount = maxIndexCount;
  20792. if ( this._geometryInitialized ) {
  20793. this._geometryInitialized = false;
  20794. this.geometry = new BufferGeometry();
  20795. this._initializeGeometry( oldGeometry );
  20796. }
  20797. // copy data from the previous geometry
  20798. const geometry = this.geometry;
  20799. if ( oldGeometry.index ) {
  20800. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20801. }
  20802. for ( const key in oldGeometry.attributes ) {
  20803. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20804. }
  20805. }
  20806. raycast( raycaster, intersects ) {
  20807. const instanceInfo = this._instanceInfo;
  20808. const geometryInfoList = this._geometryInfo;
  20809. const matrixWorld = this.matrixWorld;
  20810. const batchGeometry = this.geometry;
  20811. // iterate over each geometry
  20812. _mesh.material = this.material;
  20813. _mesh.geometry.index = batchGeometry.index;
  20814. _mesh.geometry.attributes = batchGeometry.attributes;
  20815. if ( _mesh.geometry.boundingBox === null ) {
  20816. _mesh.geometry.boundingBox = new Box3();
  20817. }
  20818. if ( _mesh.geometry.boundingSphere === null ) {
  20819. _mesh.geometry.boundingSphere = new Sphere();
  20820. }
  20821. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20822. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20823. continue;
  20824. }
  20825. const geometryId = instanceInfo[ i ].geometryIndex;
  20826. const geometryInfo = geometryInfoList[ geometryId ];
  20827. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20828. // get the intersects
  20829. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20830. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20831. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20832. _mesh.raycast( raycaster, _batchIntersects );
  20833. // add batch id to the intersects
  20834. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20835. const intersect = _batchIntersects[ j ];
  20836. intersect.object = this;
  20837. intersect.batchId = i;
  20838. intersects.push( intersect );
  20839. }
  20840. _batchIntersects.length = 0;
  20841. }
  20842. _mesh.material = null;
  20843. _mesh.geometry.index = null;
  20844. _mesh.geometry.attributes = {};
  20845. _mesh.geometry.setDrawRange( 0, Infinity );
  20846. }
  20847. copy( source ) {
  20848. super.copy( source );
  20849. this.geometry = source.geometry.clone();
  20850. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20851. this.sortObjects = source.sortObjects;
  20852. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20853. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20854. this._geometryInfo = source._geometryInfo.map( info => ( {
  20855. ...info,
  20856. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20857. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20858. } ) );
  20859. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20860. this._availableInstanceIds = source._availableInstanceIds.slice();
  20861. this._availableGeometryIds = source._availableGeometryIds.slice();
  20862. this._nextIndexStart = source._nextIndexStart;
  20863. this._nextVertexStart = source._nextVertexStart;
  20864. this._geometryCount = source._geometryCount;
  20865. this._maxInstanceCount = source._maxInstanceCount;
  20866. this._maxVertexCount = source._maxVertexCount;
  20867. this._maxIndexCount = source._maxIndexCount;
  20868. this._geometryInitialized = source._geometryInitialized;
  20869. this._multiDrawCounts = source._multiDrawCounts.slice();
  20870. this._multiDrawStarts = source._multiDrawStarts.slice();
  20871. this._indirectTexture = source._indirectTexture.clone();
  20872. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20873. this._matricesTexture = source._matricesTexture.clone();
  20874. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20875. if ( this._colorsTexture !== null ) {
  20876. this._colorsTexture = source._colorsTexture.clone();
  20877. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20878. }
  20879. return this;
  20880. }
  20881. /**
  20882. * Frees the GPU-related resources allocated by this instance. Call this
  20883. * method whenever this instance is no longer used in your app.
  20884. */
  20885. dispose() {
  20886. // Assuming the geometry is not shared with other meshes
  20887. this.geometry.dispose();
  20888. this._matricesTexture.dispose();
  20889. this._matricesTexture = null;
  20890. this._indirectTexture.dispose();
  20891. this._indirectTexture = null;
  20892. if ( this._colorsTexture !== null ) {
  20893. this._colorsTexture.dispose();
  20894. this._colorsTexture = null;
  20895. }
  20896. }
  20897. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20898. // if visibility has not changed and frustum culling and object sorting is not required
  20899. // then skip iterating over all items
  20900. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20901. return;
  20902. }
  20903. // the indexed version of the multi draw function requires specifying the start
  20904. // offset in bytes.
  20905. const index = geometry.getIndex();
  20906. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20907. const instanceInfo = this._instanceInfo;
  20908. const multiDrawStarts = this._multiDrawStarts;
  20909. const multiDrawCounts = this._multiDrawCounts;
  20910. const geometryInfoList = this._geometryInfo;
  20911. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20912. const indirectTexture = this._indirectTexture;
  20913. const indirectArray = indirectTexture.image.data;
  20914. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  20915. // prepare the frustum in the local frame
  20916. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  20917. _matrix$1
  20918. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  20919. .multiply( this.matrixWorld );
  20920. _frustum.setFromProjectionMatrix(
  20921. _matrix$1,
  20922. camera.coordinateSystem,
  20923. camera.reversedDepth
  20924. );
  20925. }
  20926. let multiDrawCount = 0;
  20927. if ( this.sortObjects ) {
  20928. // get the camera position in the local frame
  20929. _matrix$1.copy( this.matrixWorld ).invert();
  20930. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  20931. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  20932. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20933. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20934. const geometryId = instanceInfo[ i ].geometryIndex;
  20935. // get the bounds in world space
  20936. this.getMatrixAt( i, _matrix$1 );
  20937. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20938. // determine whether the batched geometry is within the frustum
  20939. let culled = false;
  20940. if ( perObjectFrustumCulled ) {
  20941. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20942. }
  20943. if ( ! culled ) {
  20944. // get the distance from camera used for sorting
  20945. const geometryInfo = geometryInfoList[ geometryId ];
  20946. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  20947. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  20948. }
  20949. }
  20950. }
  20951. // Sort the draw ranges and prep for rendering
  20952. const list = _renderList.list;
  20953. const customSort = this.customSort;
  20954. if ( customSort === null ) {
  20955. list.sort( material.transparent ? sortTransparent : sortOpaque );
  20956. } else {
  20957. customSort.call( this, list, camera );
  20958. }
  20959. for ( let i = 0, l = list.length; i < l; i ++ ) {
  20960. const item = list[ i ];
  20961. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  20962. multiDrawCounts[ multiDrawCount ] = item.count;
  20963. indirectArray[ multiDrawCount ] = item.index;
  20964. multiDrawCount ++;
  20965. }
  20966. _renderList.reset();
  20967. } else {
  20968. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20969. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  20970. const geometryId = instanceInfo[ i ].geometryIndex;
  20971. // determine whether the batched geometry is within the frustum
  20972. let culled = false;
  20973. if ( perObjectFrustumCulled ) {
  20974. // get the bounds in world space
  20975. this.getMatrixAt( i, _matrix$1 );
  20976. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20977. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  20978. }
  20979. if ( ! culled ) {
  20980. const geometryInfo = geometryInfoList[ geometryId ];
  20981. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  20982. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  20983. indirectArray[ multiDrawCount ] = i;
  20984. multiDrawCount ++;
  20985. }
  20986. }
  20987. }
  20988. }
  20989. indirectTexture.needsUpdate = true;
  20990. this._multiDrawCount = multiDrawCount;
  20991. this._visibilityChanged = false;
  20992. }
  20993. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  20994. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  20995. }
  20996. }
  20997. /**
  20998. * A material for rendering line primitives.
  20999. *
  21000. * Materials define the appearance of renderable 3D objects.
  21001. *
  21002. * ```js
  21003. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21004. * ```
  21005. *
  21006. * @augments Material
  21007. */
  21008. class LineBasicMaterial extends Material {
  21009. /**
  21010. * Constructs a new line basic material.
  21011. *
  21012. * @param {Object} [parameters] - An object with one or more properties
  21013. * defining the material's appearance. Any property of the material
  21014. * (including any property from inherited materials) can be passed
  21015. * in here. Color values can be passed any type of value accepted
  21016. * by {@link Color#set}.
  21017. */
  21018. constructor( parameters ) {
  21019. super();
  21020. /**
  21021. * This flag can be used for type testing.
  21022. *
  21023. * @type {boolean}
  21024. * @readonly
  21025. * @default true
  21026. */
  21027. this.isLineBasicMaterial = true;
  21028. this.type = 'LineBasicMaterial';
  21029. /**
  21030. * Color of the material.
  21031. *
  21032. * @type {Color}
  21033. * @default (1,1,1)
  21034. */
  21035. this.color = new Color( 0xffffff );
  21036. /**
  21037. * Sets the color of the lines using data from a texture. The texture map
  21038. * color is modulated by the diffuse `color`.
  21039. *
  21040. * @type {?Texture}
  21041. * @default null
  21042. */
  21043. this.map = null;
  21044. /**
  21045. * Controls line thickness or lines.
  21046. *
  21047. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21048. * ignore this setting and always render line primitives with a
  21049. * width of one pixel.
  21050. *
  21051. * @type {number}
  21052. * @default 1
  21053. */
  21054. this.linewidth = 1;
  21055. /**
  21056. * Defines appearance of line ends.
  21057. *
  21058. * Can only be used with {@link SVGRenderer}.
  21059. *
  21060. * @type {('butt'|'round'|'square')}
  21061. * @default 'round'
  21062. */
  21063. this.linecap = 'round';
  21064. /**
  21065. * Defines appearance of line joints.
  21066. *
  21067. * Can only be used with {@link SVGRenderer}.
  21068. *
  21069. * @type {('round'|'bevel'|'miter')}
  21070. * @default 'round'
  21071. */
  21072. this.linejoin = 'round';
  21073. /**
  21074. * Whether the material is affected by fog or not.
  21075. *
  21076. * @type {boolean}
  21077. * @default true
  21078. */
  21079. this.fog = true;
  21080. this.setValues( parameters );
  21081. }
  21082. copy( source ) {
  21083. super.copy( source );
  21084. this.color.copy( source.color );
  21085. this.map = source.map;
  21086. this.linewidth = source.linewidth;
  21087. this.linecap = source.linecap;
  21088. this.linejoin = source.linejoin;
  21089. this.fog = source.fog;
  21090. return this;
  21091. }
  21092. }
  21093. const _vStart = /*@__PURE__*/ new Vector3();
  21094. const _vEnd = /*@__PURE__*/ new Vector3();
  21095. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21096. const _ray$1 = /*@__PURE__*/ new Ray();
  21097. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21098. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21099. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21100. /**
  21101. * A continuous line. The line are rendered by connecting consecutive
  21102. * vertices with straight lines.
  21103. *
  21104. * ```js
  21105. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21106. *
  21107. * const points = [];
  21108. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21109. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21110. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21111. *
  21112. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21113. *
  21114. * const line = new THREE.Line( geometry, material );
  21115. * scene.add( line );
  21116. * ```
  21117. *
  21118. * @augments Object3D
  21119. */
  21120. class Line extends Object3D {
  21121. /**
  21122. * Constructs a new line.
  21123. *
  21124. * @param {BufferGeometry} [geometry] - The line geometry.
  21125. * @param {Material|Array<Material>} [material] - The line material.
  21126. */
  21127. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21128. super();
  21129. /**
  21130. * This flag can be used for type testing.
  21131. *
  21132. * @type {boolean}
  21133. * @readonly
  21134. * @default true
  21135. */
  21136. this.isLine = true;
  21137. this.type = 'Line';
  21138. /**
  21139. * The line geometry.
  21140. *
  21141. * @type {BufferGeometry}
  21142. */
  21143. this.geometry = geometry;
  21144. /**
  21145. * The line material.
  21146. *
  21147. * @type {Material|Array<Material>}
  21148. * @default LineBasicMaterial
  21149. */
  21150. this.material = material;
  21151. /**
  21152. * A dictionary representing the morph targets in the geometry. The key is the
  21153. * morph targets name, the value its attribute index. This member is `undefined`
  21154. * by default and only set when morph targets are detected in the geometry.
  21155. *
  21156. * @type {Object<String,number>|undefined}
  21157. * @default undefined
  21158. */
  21159. this.morphTargetDictionary = undefined;
  21160. /**
  21161. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21162. * is applied. This member is `undefined` by default and only set when morph targets are
  21163. * detected in the geometry.
  21164. *
  21165. * @type {Array<number>|undefined}
  21166. * @default undefined
  21167. */
  21168. this.morphTargetInfluences = undefined;
  21169. this.updateMorphTargets();
  21170. }
  21171. copy( source, recursive ) {
  21172. super.copy( source, recursive );
  21173. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21174. this.geometry = source.geometry;
  21175. return this;
  21176. }
  21177. /**
  21178. * Computes an array of distance values which are necessary for rendering dashed lines.
  21179. * For each vertex in the geometry, the method calculates the cumulative length from the
  21180. * current point to the very beginning of the line.
  21181. *
  21182. * @return {Line} A reference to this line.
  21183. */
  21184. computeLineDistances() {
  21185. const geometry = this.geometry;
  21186. // we assume non-indexed geometry
  21187. if ( geometry.index === null ) {
  21188. const positionAttribute = geometry.attributes.position;
  21189. const lineDistances = [ 0 ];
  21190. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21191. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21192. _vEnd.fromBufferAttribute( positionAttribute, i );
  21193. lineDistances[ i ] = lineDistances[ i - 1 ];
  21194. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21195. }
  21196. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21197. } else {
  21198. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21199. }
  21200. return this;
  21201. }
  21202. /**
  21203. * Computes intersection points between a casted ray and this line.
  21204. *
  21205. * @param {Raycaster} raycaster - The raycaster.
  21206. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21207. */
  21208. raycast( raycaster, intersects ) {
  21209. const geometry = this.geometry;
  21210. const matrixWorld = this.matrixWorld;
  21211. const threshold = raycaster.params.Line.threshold;
  21212. const drawRange = geometry.drawRange;
  21213. // Checking boundingSphere distance to ray
  21214. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21215. _sphere$1.copy( geometry.boundingSphere );
  21216. _sphere$1.applyMatrix4( matrixWorld );
  21217. _sphere$1.radius += threshold;
  21218. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21219. //
  21220. _inverseMatrix$1.copy( matrixWorld ).invert();
  21221. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21222. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21223. const localThresholdSq = localThreshold * localThreshold;
  21224. const step = this.isLineSegments ? 2 : 1;
  21225. const index = geometry.index;
  21226. const attributes = geometry.attributes;
  21227. const positionAttribute = attributes.position;
  21228. if ( index !== null ) {
  21229. const start = Math.max( 0, drawRange.start );
  21230. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21231. for ( let i = start, l = end - 1; i < l; i += step ) {
  21232. const a = index.getX( i );
  21233. const b = index.getX( i + 1 );
  21234. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21235. if ( intersect ) {
  21236. intersects.push( intersect );
  21237. }
  21238. }
  21239. if ( this.isLineLoop ) {
  21240. const a = index.getX( end - 1 );
  21241. const b = index.getX( start );
  21242. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21243. if ( intersect ) {
  21244. intersects.push( intersect );
  21245. }
  21246. }
  21247. } else {
  21248. const start = Math.max( 0, drawRange.start );
  21249. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21250. for ( let i = start, l = end - 1; i < l; i += step ) {
  21251. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21252. if ( intersect ) {
  21253. intersects.push( intersect );
  21254. }
  21255. }
  21256. if ( this.isLineLoop ) {
  21257. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21258. if ( intersect ) {
  21259. intersects.push( intersect );
  21260. }
  21261. }
  21262. }
  21263. }
  21264. /**
  21265. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21266. * to make sure existing morph targets can influence this 3D object.
  21267. */
  21268. updateMorphTargets() {
  21269. const geometry = this.geometry;
  21270. const morphAttributes = geometry.morphAttributes;
  21271. const keys = Object.keys( morphAttributes );
  21272. if ( keys.length > 0 ) {
  21273. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21274. if ( morphAttribute !== undefined ) {
  21275. this.morphTargetInfluences = [];
  21276. this.morphTargetDictionary = {};
  21277. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21278. const name = morphAttribute[ m ].name || String( m );
  21279. this.morphTargetInfluences.push( 0 );
  21280. this.morphTargetDictionary[ name ] = m;
  21281. }
  21282. }
  21283. }
  21284. }
  21285. }
  21286. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21287. const positionAttribute = object.geometry.attributes.position;
  21288. _vStart.fromBufferAttribute( positionAttribute, a );
  21289. _vEnd.fromBufferAttribute( positionAttribute, b );
  21290. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21291. if ( distSq > thresholdSq ) return;
  21292. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21293. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21294. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21295. return {
  21296. distance: distance,
  21297. // What do we want? intersection point on the ray or on the segment??
  21298. // point: raycaster.ray.at( distance ),
  21299. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21300. index: i,
  21301. face: null,
  21302. faceIndex: null,
  21303. barycoord: null,
  21304. object: object
  21305. };
  21306. }
  21307. const _start = /*@__PURE__*/ new Vector3();
  21308. const _end = /*@__PURE__*/ new Vector3();
  21309. /**
  21310. * A series of lines drawn between pairs of vertices.
  21311. *
  21312. * @augments Line
  21313. */
  21314. class LineSegments extends Line {
  21315. /**
  21316. * Constructs a new line segments.
  21317. *
  21318. * @param {BufferGeometry} [geometry] - The line geometry.
  21319. * @param {Material|Array<Material>} [material] - The line material.
  21320. */
  21321. constructor( geometry, material ) {
  21322. super( geometry, material );
  21323. /**
  21324. * This flag can be used for type testing.
  21325. *
  21326. * @type {boolean}
  21327. * @readonly
  21328. * @default true
  21329. */
  21330. this.isLineSegments = true;
  21331. this.type = 'LineSegments';
  21332. }
  21333. computeLineDistances() {
  21334. const geometry = this.geometry;
  21335. // we assume non-indexed geometry
  21336. if ( geometry.index === null ) {
  21337. const positionAttribute = geometry.attributes.position;
  21338. const lineDistances = [];
  21339. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21340. _start.fromBufferAttribute( positionAttribute, i );
  21341. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21342. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21343. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21344. }
  21345. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21346. } else {
  21347. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21348. }
  21349. return this;
  21350. }
  21351. }
  21352. /**
  21353. * A continuous line. This is nearly the same as {@link Line} the only difference
  21354. * is that the last vertex is connected with the first vertex in order to close
  21355. * the line to form a loop.
  21356. *
  21357. * @augments Line
  21358. */
  21359. class LineLoop extends Line {
  21360. /**
  21361. * Constructs a new line loop.
  21362. *
  21363. * @param {BufferGeometry} [geometry] - The line geometry.
  21364. * @param {Material|Array<Material>} [material] - The line material.
  21365. */
  21366. constructor( geometry, material ) {
  21367. super( geometry, material );
  21368. /**
  21369. * This flag can be used for type testing.
  21370. *
  21371. * @type {boolean}
  21372. * @readonly
  21373. * @default true
  21374. */
  21375. this.isLineLoop = true;
  21376. this.type = 'LineLoop';
  21377. }
  21378. }
  21379. /**
  21380. * A material for rendering point primitives.
  21381. *
  21382. * Materials define the appearance of renderable 3D objects.
  21383. *
  21384. * ```js
  21385. * const vertices = [];
  21386. *
  21387. * for ( let i = 0; i < 10000; i ++ ) {
  21388. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21389. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21390. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21391. *
  21392. * vertices.push( x, y, z );
  21393. * }
  21394. *
  21395. * const geometry = new THREE.BufferGeometry();
  21396. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21397. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21398. * const points = new THREE.Points( geometry, material );
  21399. * scene.add( points );
  21400. * ```
  21401. *
  21402. * @augments Material
  21403. */
  21404. class PointsMaterial extends Material {
  21405. /**
  21406. * Constructs a new points material.
  21407. *
  21408. * @param {Object} [parameters] - An object with one or more properties
  21409. * defining the material's appearance. Any property of the material
  21410. * (including any property from inherited materials) can be passed
  21411. * in here. Color values can be passed any type of value accepted
  21412. * by {@link Color#set}.
  21413. */
  21414. constructor( parameters ) {
  21415. super();
  21416. /**
  21417. * This flag can be used for type testing.
  21418. *
  21419. * @type {boolean}
  21420. * @readonly
  21421. * @default true
  21422. */
  21423. this.isPointsMaterial = true;
  21424. this.type = 'PointsMaterial';
  21425. /**
  21426. * Color of the material.
  21427. *
  21428. * @type {Color}
  21429. * @default (1,1,1)
  21430. */
  21431. this.color = new Color( 0xffffff );
  21432. /**
  21433. * The color map. May optionally include an alpha channel, typically combined
  21434. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21435. * color is modulated by the diffuse `color`.
  21436. *
  21437. * @type {?Texture}
  21438. * @default null
  21439. */
  21440. this.map = null;
  21441. /**
  21442. * The alpha map is a grayscale texture that controls the opacity across the
  21443. * surface (black: fully transparent; white: fully opaque).
  21444. *
  21445. * Only the color of the texture is used, ignoring the alpha channel if one
  21446. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21447. * when sampling this texture due to the extra bit of precision provided for
  21448. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21449. * luminance/alpha textures will also still work as expected.
  21450. *
  21451. * @type {?Texture}
  21452. * @default null
  21453. */
  21454. this.alphaMap = null;
  21455. /**
  21456. * Defines the size of the points in pixels.
  21457. *
  21458. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE]{@link https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete}.
  21459. *
  21460. * @type {number}
  21461. * @default 1
  21462. */
  21463. this.size = 1;
  21464. /**
  21465. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21466. *
  21467. * @type {boolean}
  21468. * @default true
  21469. */
  21470. this.sizeAttenuation = true;
  21471. /**
  21472. * Whether the material is affected by fog or not.
  21473. *
  21474. * @type {boolean}
  21475. * @default true
  21476. */
  21477. this.fog = true;
  21478. this.setValues( parameters );
  21479. }
  21480. copy( source ) {
  21481. super.copy( source );
  21482. this.color.copy( source.color );
  21483. this.map = source.map;
  21484. this.alphaMap = source.alphaMap;
  21485. this.size = source.size;
  21486. this.sizeAttenuation = source.sizeAttenuation;
  21487. this.fog = source.fog;
  21488. return this;
  21489. }
  21490. }
  21491. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21492. const _ray = /*@__PURE__*/ new Ray();
  21493. const _sphere = /*@__PURE__*/ new Sphere();
  21494. const _position$2 = /*@__PURE__*/ new Vector3();
  21495. /**
  21496. * A class for displaying points or point clouds.
  21497. *
  21498. * @augments Object3D
  21499. */
  21500. class Points extends Object3D {
  21501. /**
  21502. * Constructs a new point cloud.
  21503. *
  21504. * @param {BufferGeometry} [geometry] - The points geometry.
  21505. * @param {Material|Array<Material>} [material] - The points material.
  21506. */
  21507. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21508. super();
  21509. /**
  21510. * This flag can be used for type testing.
  21511. *
  21512. * @type {boolean}
  21513. * @readonly
  21514. * @default true
  21515. */
  21516. this.isPoints = true;
  21517. this.type = 'Points';
  21518. /**
  21519. * The points geometry.
  21520. *
  21521. * @type {BufferGeometry}
  21522. */
  21523. this.geometry = geometry;
  21524. /**
  21525. * The line material.
  21526. *
  21527. * @type {Material|Array<Material>}
  21528. * @default PointsMaterial
  21529. */
  21530. this.material = material;
  21531. /**
  21532. * A dictionary representing the morph targets in the geometry. The key is the
  21533. * morph targets name, the value its attribute index. This member is `undefined`
  21534. * by default and only set when morph targets are detected in the geometry.
  21535. *
  21536. * @type {Object<String,number>|undefined}
  21537. * @default undefined
  21538. */
  21539. this.morphTargetDictionary = undefined;
  21540. /**
  21541. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21542. * is applied. This member is `undefined` by default and only set when morph targets are
  21543. * detected in the geometry.
  21544. *
  21545. * @type {Array<number>|undefined}
  21546. * @default undefined
  21547. */
  21548. this.morphTargetInfluences = undefined;
  21549. this.updateMorphTargets();
  21550. }
  21551. copy( source, recursive ) {
  21552. super.copy( source, recursive );
  21553. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21554. this.geometry = source.geometry;
  21555. return this;
  21556. }
  21557. /**
  21558. * Computes intersection points between a casted ray and this point cloud.
  21559. *
  21560. * @param {Raycaster} raycaster - The raycaster.
  21561. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21562. */
  21563. raycast( raycaster, intersects ) {
  21564. const geometry = this.geometry;
  21565. const matrixWorld = this.matrixWorld;
  21566. const threshold = raycaster.params.Points.threshold;
  21567. const drawRange = geometry.drawRange;
  21568. // Checking boundingSphere distance to ray
  21569. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21570. _sphere.copy( geometry.boundingSphere );
  21571. _sphere.applyMatrix4( matrixWorld );
  21572. _sphere.radius += threshold;
  21573. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21574. //
  21575. _inverseMatrix.copy( matrixWorld ).invert();
  21576. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21577. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21578. const localThresholdSq = localThreshold * localThreshold;
  21579. const index = geometry.index;
  21580. const attributes = geometry.attributes;
  21581. const positionAttribute = attributes.position;
  21582. if ( index !== null ) {
  21583. const start = Math.max( 0, drawRange.start );
  21584. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21585. for ( let i = start, il = end; i < il; i ++ ) {
  21586. const a = index.getX( i );
  21587. _position$2.fromBufferAttribute( positionAttribute, a );
  21588. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21589. }
  21590. } else {
  21591. const start = Math.max( 0, drawRange.start );
  21592. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21593. for ( let i = start, l = end; i < l; i ++ ) {
  21594. _position$2.fromBufferAttribute( positionAttribute, i );
  21595. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21596. }
  21597. }
  21598. }
  21599. /**
  21600. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21601. * to make sure existing morph targets can influence this 3D object.
  21602. */
  21603. updateMorphTargets() {
  21604. const geometry = this.geometry;
  21605. const morphAttributes = geometry.morphAttributes;
  21606. const keys = Object.keys( morphAttributes );
  21607. if ( keys.length > 0 ) {
  21608. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21609. if ( morphAttribute !== undefined ) {
  21610. this.morphTargetInfluences = [];
  21611. this.morphTargetDictionary = {};
  21612. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21613. const name = morphAttribute[ m ].name || String( m );
  21614. this.morphTargetInfluences.push( 0 );
  21615. this.morphTargetDictionary[ name ] = m;
  21616. }
  21617. }
  21618. }
  21619. }
  21620. }
  21621. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21622. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21623. if ( rayPointDistanceSq < localThresholdSq ) {
  21624. const intersectPoint = new Vector3();
  21625. _ray.closestPointToPoint( point, intersectPoint );
  21626. intersectPoint.applyMatrix4( matrixWorld );
  21627. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21628. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21629. intersects.push( {
  21630. distance: distance,
  21631. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21632. point: intersectPoint,
  21633. index: index,
  21634. face: null,
  21635. faceIndex: null,
  21636. barycoord: null,
  21637. object: object
  21638. } );
  21639. }
  21640. }
  21641. /**
  21642. * A texture for use with a video.
  21643. *
  21644. * ```js
  21645. * // assuming you have created a HTML video element with id="video"
  21646. * const video = document.getElementById( 'video' );
  21647. * const texture = new THREE.VideoTexture( video );
  21648. * ```
  21649. *
  21650. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21651. * set to THREE.SRGBColorSpace.
  21652. *
  21653. * Note: After the initial use of a texture, its dimensions, format, and type
  21654. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21655. *
  21656. * @augments Texture
  21657. */
  21658. class VideoTexture extends Texture {
  21659. /**
  21660. * Constructs a new video texture.
  21661. *
  21662. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21663. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21664. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21665. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21666. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21667. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21668. * @param {number} [format=RGBAFormat] - The texture format.
  21669. * @param {number} [type=UnsignedByteType] - The texture type.
  21670. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21671. */
  21672. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21673. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21674. /**
  21675. * This flag can be used for type testing.
  21676. *
  21677. * @type {boolean}
  21678. * @readonly
  21679. * @default true
  21680. */
  21681. this.isVideoTexture = true;
  21682. /**
  21683. * Whether to generate mipmaps (if possible) for a texture.
  21684. *
  21685. * Overwritten and set to `false` by default.
  21686. *
  21687. * @type {boolean}
  21688. * @default false
  21689. */
  21690. this.generateMipmaps = false;
  21691. /**
  21692. * The video frame request callback identifier, which is a positive integer.
  21693. *
  21694. * Value of 0 represents no scheduled rVFC.
  21695. *
  21696. * @private
  21697. * @type {number}
  21698. */
  21699. this._requestVideoFrameCallbackId = 0;
  21700. const scope = this;
  21701. function updateVideo() {
  21702. scope.needsUpdate = true;
  21703. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21704. }
  21705. if ( 'requestVideoFrameCallback' in video ) {
  21706. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21707. }
  21708. }
  21709. clone() {
  21710. return new this.constructor( this.image ).copy( this );
  21711. }
  21712. /**
  21713. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21714. * to `true` every time a new frame is available.
  21715. *
  21716. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21717. */
  21718. update() {
  21719. const video = this.image;
  21720. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21721. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21722. this.needsUpdate = true;
  21723. }
  21724. }
  21725. dispose() {
  21726. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21727. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21728. }
  21729. super.dispose();
  21730. }
  21731. }
  21732. /**
  21733. * This class can be used as an alternative way to define video data. Instead of using
  21734. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21735. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21736. * video frames are decoded with the WebCodecs API.
  21737. *
  21738. * ```js
  21739. * const texture = new THREE.VideoFrameTexture();
  21740. * texture.setFrame( frame );
  21741. * ```
  21742. *
  21743. * @augments VideoTexture
  21744. */
  21745. class VideoFrameTexture extends VideoTexture {
  21746. /**
  21747. * Constructs a new video frame texture.
  21748. *
  21749. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21750. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21751. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21752. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21753. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21754. * @param {number} [format=RGBAFormat] - The texture format.
  21755. * @param {number} [type=UnsignedByteType] - The texture type.
  21756. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21757. */
  21758. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21759. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21760. /**
  21761. * This flag can be used for type testing.
  21762. *
  21763. * @type {boolean}
  21764. * @readonly
  21765. * @default true
  21766. */
  21767. this.isVideoFrameTexture = true;
  21768. }
  21769. /**
  21770. * This method overwritten with an empty implementation since
  21771. * this type of texture is updated via `setFrame()`.
  21772. */
  21773. update() {}
  21774. clone() {
  21775. return new this.constructor().copy( this ); // restoring Texture.clone()
  21776. }
  21777. /**
  21778. * Sets the current frame of the video. This will automatically update the texture
  21779. * so the data can be used for rendering.
  21780. *
  21781. * @param {VideoFrame} frame - The video frame.
  21782. */
  21783. setFrame( frame ) {
  21784. this.image = frame;
  21785. this.needsUpdate = true;
  21786. }
  21787. }
  21788. /**
  21789. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21790. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21791. * as a texture for further usage.
  21792. *
  21793. * ```js
  21794. * const pixelRatio = window.devicePixelRatio;
  21795. * const textureSize = 128 * pixelRatio;
  21796. *
  21797. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21798. *
  21799. * // calculate start position for copying part of the frame data
  21800. * const vector = new Vector2();
  21801. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21802. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21803. *
  21804. * renderer.render( scene, camera );
  21805. *
  21806. * // copy part of the rendered frame into the framebuffer texture
  21807. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21808. * ```
  21809. *
  21810. * @augments Texture
  21811. */
  21812. class FramebufferTexture extends Texture {
  21813. /**
  21814. * Constructs a new framebuffer texture.
  21815. *
  21816. * @param {number} [width] - The width of the texture.
  21817. * @param {number} [height] - The height of the texture.
  21818. */
  21819. constructor( width, height ) {
  21820. super( { width, height } );
  21821. /**
  21822. * This flag can be used for type testing.
  21823. *
  21824. * @type {boolean}
  21825. * @readonly
  21826. * @default true
  21827. */
  21828. this.isFramebufferTexture = true;
  21829. /**
  21830. * How the texture is sampled when a texel covers more than one pixel.
  21831. *
  21832. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21833. *
  21834. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21835. * @default NearestFilter
  21836. */
  21837. this.magFilter = NearestFilter;
  21838. /**
  21839. * How the texture is sampled when a texel covers less than one pixel.
  21840. *
  21841. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21842. *
  21843. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21844. * @default NearestFilter
  21845. */
  21846. this.minFilter = NearestFilter;
  21847. /**
  21848. * Whether to generate mipmaps (if possible) for a texture.
  21849. *
  21850. * Overwritten and set to `false` by default.
  21851. *
  21852. * @type {boolean}
  21853. * @default false
  21854. */
  21855. this.generateMipmaps = false;
  21856. this.needsUpdate = true;
  21857. }
  21858. }
  21859. /**
  21860. * Creates a texture based on data in compressed form.
  21861. *
  21862. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21863. *
  21864. * @augments Texture
  21865. */
  21866. class CompressedTexture extends Texture {
  21867. /**
  21868. * Constructs a new compressed texture.
  21869. *
  21870. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21871. * the data and dimensions.
  21872. * @param {number} width - The width of the texture.
  21873. * @param {number} height - The height of the texture.
  21874. * @param {number} [format=RGBAFormat] - The texture format.
  21875. * @param {number} [type=UnsignedByteType] - The texture type.
  21876. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21877. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21878. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21879. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21880. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21881. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21882. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21883. */
  21884. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21885. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21886. /**
  21887. * This flag can be used for type testing.
  21888. *
  21889. * @type {boolean}
  21890. * @readonly
  21891. * @default true
  21892. */
  21893. this.isCompressedTexture = true;
  21894. /**
  21895. * The image property of a compressed texture just defines its dimensions.
  21896. *
  21897. * @type {{width:number,height:number}}
  21898. */
  21899. this.image = { width: width, height: height };
  21900. /**
  21901. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21902. *
  21903. * @type {Array<Object>}
  21904. */
  21905. this.mipmaps = mipmaps;
  21906. /**
  21907. * If set to `true`, the texture is flipped along the vertical axis when
  21908. * uploaded to the GPU.
  21909. *
  21910. * Overwritten and set to `false` by default since it is not possible to
  21911. * flip compressed textures.
  21912. *
  21913. * @type {boolean}
  21914. * @default false
  21915. * @readonly
  21916. */
  21917. this.flipY = false;
  21918. /**
  21919. * Whether to generate mipmaps (if possible) for a texture.
  21920. *
  21921. * Overwritten and set to `false` by default since it is not
  21922. * possible to generate mipmaps for compressed data. Mipmaps
  21923. * must be embedded in the compressed texture file.
  21924. *
  21925. * @type {boolean}
  21926. * @default false
  21927. * @readonly
  21928. */
  21929. this.generateMipmaps = false;
  21930. }
  21931. }
  21932. /**
  21933. * Creates a texture 2D array based on data in compressed form.
  21934. *
  21935. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21936. *
  21937. * @augments CompressedTexture
  21938. */
  21939. class CompressedArrayTexture extends CompressedTexture {
  21940. /**
  21941. * Constructs a new compressed array texture.
  21942. *
  21943. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21944. * the data and dimensions.
  21945. * @param {number} width - The width of the texture.
  21946. * @param {number} height - The height of the texture.
  21947. * @param {number} depth - The depth of the texture.
  21948. * @param {number} [format=RGBAFormat] - The min filter value.
  21949. * @param {number} [type=UnsignedByteType] - The min filter value.
  21950. */
  21951. constructor( mipmaps, width, height, depth, format, type ) {
  21952. super( mipmaps, width, height, format, type );
  21953. /**
  21954. * This flag can be used for type testing.
  21955. *
  21956. * @type {boolean}
  21957. * @readonly
  21958. * @default true
  21959. */
  21960. this.isCompressedArrayTexture = true;
  21961. /**
  21962. * The image property of a compressed texture just defines its dimensions.
  21963. *
  21964. * @name CompressedArrayTexture#image
  21965. * @type {{width:number,height:number,depth:number}}
  21966. */
  21967. this.image.depth = depth;
  21968. /**
  21969. * This defines how the texture is wrapped in the depth and corresponds to
  21970. * *W* in UVW mapping.
  21971. *
  21972. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  21973. * @default ClampToEdgeWrapping
  21974. */
  21975. this.wrapR = ClampToEdgeWrapping;
  21976. /**
  21977. * A set of all layers which need to be updated in the texture.
  21978. *
  21979. * @type {Set<number>}
  21980. */
  21981. this.layerUpdates = new Set();
  21982. }
  21983. /**
  21984. * Describes that a specific layer of the texture needs to be updated.
  21985. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  21986. * entire compressed texture array is sent to the GPU. Marking specific
  21987. * layers will only transmit subsets of all mipmaps associated with a
  21988. * specific depth in the array which is often much more performant.
  21989. *
  21990. * @param {number} layerIndex - The layer index that should be updated.
  21991. */
  21992. addLayerUpdate( layerIndex ) {
  21993. this.layerUpdates.add( layerIndex );
  21994. }
  21995. /**
  21996. * Resets the layer updates registry.
  21997. */
  21998. clearLayerUpdates() {
  21999. this.layerUpdates.clear();
  22000. }
  22001. }
  22002. /**
  22003. * Creates a cube texture based on data in compressed form.
  22004. *
  22005. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22006. *
  22007. * @augments CompressedTexture
  22008. */
  22009. class CompressedCubeTexture extends CompressedTexture {
  22010. /**
  22011. * Constructs a new compressed texture.
  22012. *
  22013. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22014. * @param {number} [format=RGBAFormat] - The texture format.
  22015. * @param {number} [type=UnsignedByteType] - The texture type.
  22016. */
  22017. constructor( images, format, type ) {
  22018. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22019. /**
  22020. * This flag can be used for type testing.
  22021. *
  22022. * @type {boolean}
  22023. * @readonly
  22024. * @default true
  22025. */
  22026. this.isCompressedCubeTexture = true;
  22027. /**
  22028. * This flag can be used for type testing.
  22029. *
  22030. * @type {boolean}
  22031. * @readonly
  22032. * @default true
  22033. */
  22034. this.isCubeTexture = true;
  22035. this.image = images;
  22036. }
  22037. }
  22038. /**
  22039. * Creates a texture from a canvas element.
  22040. *
  22041. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22042. * to `true` immediately since a canvas can directly be used for rendering.
  22043. *
  22044. * @augments Texture
  22045. */
  22046. class CanvasTexture extends Texture {
  22047. /**
  22048. * Constructs a new texture.
  22049. *
  22050. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22051. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22052. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22053. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22054. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22055. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22056. * @param {number} [format=RGBAFormat] - The texture format.
  22057. * @param {number} [type=UnsignedByteType] - The texture type.
  22058. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22059. */
  22060. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22061. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22062. /**
  22063. * This flag can be used for type testing.
  22064. *
  22065. * @type {boolean}
  22066. * @readonly
  22067. * @default true
  22068. */
  22069. this.isCanvasTexture = true;
  22070. this.needsUpdate = true;
  22071. }
  22072. }
  22073. /**
  22074. * This class can be used to automatically save the depth information of a
  22075. * rendering into a texture.
  22076. *
  22077. * @augments Texture
  22078. */
  22079. class DepthTexture extends Texture {
  22080. /**
  22081. * Constructs a new depth texture.
  22082. *
  22083. * @param {number} width - The width of the texture.
  22084. * @param {number} height - The height of the texture.
  22085. * @param {number} [type=UnsignedIntType] - The texture type.
  22086. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22087. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22088. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22089. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22090. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22091. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22092. * @param {number} [format=DepthFormat] - The texture format.
  22093. * @param {number} [depth=1] - The depth of the texture.
  22094. */
  22095. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22096. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22097. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22098. }
  22099. const image = { width: width, height: height, depth: depth };
  22100. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22101. /**
  22102. * This flag can be used for type testing.
  22103. *
  22104. * @type {boolean}
  22105. * @readonly
  22106. * @default true
  22107. */
  22108. this.isDepthTexture = true;
  22109. /**
  22110. * If set to `true`, the texture is flipped along the vertical axis when
  22111. * uploaded to the GPU.
  22112. *
  22113. * Overwritten and set to `false` by default.
  22114. *
  22115. * @type {boolean}
  22116. * @default false
  22117. */
  22118. this.flipY = false;
  22119. /**
  22120. * Whether to generate mipmaps (if possible) for a texture.
  22121. *
  22122. * Overwritten and set to `false` by default.
  22123. *
  22124. * @type {boolean}
  22125. * @default false
  22126. */
  22127. this.generateMipmaps = false;
  22128. /**
  22129. * Code corresponding to the depth compare function.
  22130. *
  22131. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22132. * @default null
  22133. */
  22134. this.compareFunction = null;
  22135. }
  22136. copy( source ) {
  22137. super.copy( source );
  22138. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22139. this.compareFunction = source.compareFunction;
  22140. return this;
  22141. }
  22142. toJSON( meta ) {
  22143. const data = super.toJSON( meta );
  22144. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22145. return data;
  22146. }
  22147. }
  22148. /**
  22149. * Represents a texture created externally with the same renderer context.
  22150. *
  22151. * This may be a texture from a protected media stream, device camera feed,
  22152. * or other data feeds like a depth sensor.
  22153. *
  22154. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22155. * the {@link WebGPURenderer} WebGPU backend.
  22156. *
  22157. * @augments Texture
  22158. */
  22159. class ExternalTexture extends Texture {
  22160. /**
  22161. * Creates a new raw texture.
  22162. *
  22163. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22164. */
  22165. constructor( sourceTexture = null ) {
  22166. super();
  22167. /**
  22168. * The external source texture.
  22169. *
  22170. * @type {?(WebGLTexture|GPUTexture)}
  22171. * @default null
  22172. */
  22173. this.sourceTexture = sourceTexture;
  22174. /**
  22175. * This flag can be used for type testing.
  22176. *
  22177. * @type {boolean}
  22178. * @readonly
  22179. * @default true
  22180. */
  22181. this.isExternalTexture = true;
  22182. }
  22183. copy( source ) {
  22184. super.copy( source );
  22185. this.sourceTexture = source.sourceTexture;
  22186. return this;
  22187. }
  22188. }
  22189. /**
  22190. * A geometry class for representing a capsule.
  22191. *
  22192. * ```js
  22193. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22194. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22195. * const capsule = new THREE.Mesh( geometry, material );
  22196. * scene.add( capsule );
  22197. * ```
  22198. *
  22199. * @augments BufferGeometry
  22200. */
  22201. class CapsuleGeometry extends BufferGeometry {
  22202. /**
  22203. * Constructs a new capsule geometry.
  22204. *
  22205. * @param {number} [radius=1] - Radius of the capsule.
  22206. * @param {number} [height=1] - Height of the middle section.
  22207. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22208. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22209. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22210. */
  22211. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22212. super();
  22213. this.type = 'CapsuleGeometry';
  22214. /**
  22215. * Holds the constructor parameters that have been
  22216. * used to generate the geometry. Any modification
  22217. * after instantiation does not change the geometry.
  22218. *
  22219. * @type {Object}
  22220. */
  22221. this.parameters = {
  22222. radius: radius,
  22223. height: height,
  22224. capSegments: capSegments,
  22225. radialSegments: radialSegments,
  22226. heightSegments: heightSegments,
  22227. };
  22228. height = Math.max( 0, height );
  22229. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22230. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22231. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22232. // buffers
  22233. const indices = [];
  22234. const vertices = [];
  22235. const normals = [];
  22236. const uvs = [];
  22237. // helper variables
  22238. const halfHeight = height / 2;
  22239. const capArcLength = ( Math.PI / 2 ) * radius;
  22240. const cylinderPartLength = height;
  22241. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22242. const numVerticalSegments = capSegments * 2 + heightSegments;
  22243. const verticesPerRow = radialSegments + 1;
  22244. const normal = new Vector3();
  22245. const vertex = new Vector3();
  22246. // generate vertices, normals, and uvs
  22247. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22248. let currentArcLength = 0;
  22249. let profileY = 0;
  22250. let profileRadius = 0;
  22251. let normalYComponent = 0;
  22252. if ( iy <= capSegments ) {
  22253. // bottom cap
  22254. const segmentProgress = iy / capSegments;
  22255. const angle = ( segmentProgress * Math.PI ) / 2;
  22256. profileY = - halfHeight - radius * Math.cos( angle );
  22257. profileRadius = radius * Math.sin( angle );
  22258. normalYComponent = - radius * Math.cos( angle );
  22259. currentArcLength = segmentProgress * capArcLength;
  22260. } else if ( iy <= capSegments + heightSegments ) {
  22261. // middle section
  22262. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22263. profileY = - halfHeight + segmentProgress * height;
  22264. profileRadius = radius;
  22265. normalYComponent = 0;
  22266. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22267. } else {
  22268. // top cap
  22269. const segmentProgress =
  22270. ( iy - capSegments - heightSegments ) / capSegments;
  22271. const angle = ( segmentProgress * Math.PI ) / 2;
  22272. profileY = halfHeight + radius * Math.sin( angle );
  22273. profileRadius = radius * Math.cos( angle );
  22274. normalYComponent = radius * Math.sin( angle );
  22275. currentArcLength =
  22276. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22277. }
  22278. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22279. // special case for the poles
  22280. let uOffset = 0;
  22281. if ( iy === 0 ) {
  22282. uOffset = 0.5 / radialSegments;
  22283. } else if ( iy === numVerticalSegments ) {
  22284. uOffset = -0.5 / radialSegments;
  22285. }
  22286. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22287. const u = ix / radialSegments;
  22288. const theta = u * Math.PI * 2;
  22289. const sinTheta = Math.sin( theta );
  22290. const cosTheta = Math.cos( theta );
  22291. // vertex
  22292. vertex.x = - profileRadius * cosTheta;
  22293. vertex.y = profileY;
  22294. vertex.z = profileRadius * sinTheta;
  22295. vertices.push( vertex.x, vertex.y, vertex.z );
  22296. // normal
  22297. normal.set(
  22298. - profileRadius * cosTheta,
  22299. normalYComponent,
  22300. profileRadius * sinTheta
  22301. );
  22302. normal.normalize();
  22303. normals.push( normal.x, normal.y, normal.z );
  22304. // uv
  22305. uvs.push( u + uOffset, v );
  22306. }
  22307. if ( iy > 0 ) {
  22308. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22309. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22310. const i1 = prevIndexRow + ix;
  22311. const i2 = prevIndexRow + ix + 1;
  22312. const i3 = iy * verticesPerRow + ix;
  22313. const i4 = iy * verticesPerRow + ix + 1;
  22314. indices.push( i1, i2, i3 );
  22315. indices.push( i2, i4, i3 );
  22316. }
  22317. }
  22318. }
  22319. // build geometry
  22320. this.setIndex( indices );
  22321. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22322. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22323. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22324. }
  22325. copy( source ) {
  22326. super.copy( source );
  22327. this.parameters = Object.assign( {}, source.parameters );
  22328. return this;
  22329. }
  22330. /**
  22331. * Factory method for creating an instance of this class from the given
  22332. * JSON object.
  22333. *
  22334. * @param {Object} data - A JSON object representing the serialized geometry.
  22335. * @return {CapsuleGeometry} A new instance.
  22336. */
  22337. static fromJSON( data ) {
  22338. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22339. }
  22340. }
  22341. /**
  22342. * A simple shape of Euclidean geometry. It is constructed from a
  22343. * number of triangular segments that are oriented around a central point and
  22344. * extend as far out as a given radius. It is built counter-clockwise from a
  22345. * start angle and a given central angle. It can also be used to create
  22346. * regular polygons, where the number of segments determines the number of
  22347. * sides.
  22348. *
  22349. * ```js
  22350. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22351. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22352. * const circle = new THREE.Mesh( geometry, material );
  22353. * scene.add( circle )
  22354. * ```
  22355. *
  22356. * @augments BufferGeometry
  22357. */
  22358. class CircleGeometry extends BufferGeometry {
  22359. /**
  22360. * Constructs a new circle geometry.
  22361. *
  22362. * @param {number} [radius=1] - Radius of the circle.
  22363. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22364. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22365. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22366. * of the circular sector in radians. The default value results in a complete circle.
  22367. */
  22368. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22369. super();
  22370. this.type = 'CircleGeometry';
  22371. /**
  22372. * Holds the constructor parameters that have been
  22373. * used to generate the geometry. Any modification
  22374. * after instantiation does not change the geometry.
  22375. *
  22376. * @type {Object}
  22377. */
  22378. this.parameters = {
  22379. radius: radius,
  22380. segments: segments,
  22381. thetaStart: thetaStart,
  22382. thetaLength: thetaLength
  22383. };
  22384. segments = Math.max( 3, segments );
  22385. // buffers
  22386. const indices = [];
  22387. const vertices = [];
  22388. const normals = [];
  22389. const uvs = [];
  22390. // helper variables
  22391. const vertex = new Vector3();
  22392. const uv = new Vector2();
  22393. // center point
  22394. vertices.push( 0, 0, 0 );
  22395. normals.push( 0, 0, 1 );
  22396. uvs.push( 0.5, 0.5 );
  22397. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22398. const segment = thetaStart + s / segments * thetaLength;
  22399. // vertex
  22400. vertex.x = radius * Math.cos( segment );
  22401. vertex.y = radius * Math.sin( segment );
  22402. vertices.push( vertex.x, vertex.y, vertex.z );
  22403. // normal
  22404. normals.push( 0, 0, 1 );
  22405. // uvs
  22406. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22407. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22408. uvs.push( uv.x, uv.y );
  22409. }
  22410. // indices
  22411. for ( let i = 1; i <= segments; i ++ ) {
  22412. indices.push( i, i + 1, 0 );
  22413. }
  22414. // build geometry
  22415. this.setIndex( indices );
  22416. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22417. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22418. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22419. }
  22420. copy( source ) {
  22421. super.copy( source );
  22422. this.parameters = Object.assign( {}, source.parameters );
  22423. return this;
  22424. }
  22425. /**
  22426. * Factory method for creating an instance of this class from the given
  22427. * JSON object.
  22428. *
  22429. * @param {Object} data - A JSON object representing the serialized geometry.
  22430. * @return {CircleGeometry} A new instance.
  22431. */
  22432. static fromJSON( data ) {
  22433. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22434. }
  22435. }
  22436. /**
  22437. * A geometry class for representing a cylinder.
  22438. *
  22439. * ```js
  22440. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22441. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22442. * const cylinder = new THREE.Mesh( geometry, material );
  22443. * scene.add( cylinder );
  22444. * ```
  22445. *
  22446. * @augments BufferGeometry
  22447. */
  22448. class CylinderGeometry extends BufferGeometry {
  22449. /**
  22450. * Constructs a new cylinder geometry.
  22451. *
  22452. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22453. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22454. * @param {number} [height=1] - Height of the cylinder.
  22455. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22456. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22457. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22458. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22459. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22460. * The default value results in a complete cylinder.
  22461. */
  22462. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22463. super();
  22464. this.type = 'CylinderGeometry';
  22465. /**
  22466. * Holds the constructor parameters that have been
  22467. * used to generate the geometry. Any modification
  22468. * after instantiation does not change the geometry.
  22469. *
  22470. * @type {Object}
  22471. */
  22472. this.parameters = {
  22473. radiusTop: radiusTop,
  22474. radiusBottom: radiusBottom,
  22475. height: height,
  22476. radialSegments: radialSegments,
  22477. heightSegments: heightSegments,
  22478. openEnded: openEnded,
  22479. thetaStart: thetaStart,
  22480. thetaLength: thetaLength
  22481. };
  22482. const scope = this;
  22483. radialSegments = Math.floor( radialSegments );
  22484. heightSegments = Math.floor( heightSegments );
  22485. // buffers
  22486. const indices = [];
  22487. const vertices = [];
  22488. const normals = [];
  22489. const uvs = [];
  22490. // helper variables
  22491. let index = 0;
  22492. const indexArray = [];
  22493. const halfHeight = height / 2;
  22494. let groupStart = 0;
  22495. // generate geometry
  22496. generateTorso();
  22497. if ( openEnded === false ) {
  22498. if ( radiusTop > 0 ) generateCap( true );
  22499. if ( radiusBottom > 0 ) generateCap( false );
  22500. }
  22501. // build geometry
  22502. this.setIndex( indices );
  22503. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22504. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22505. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22506. function generateTorso() {
  22507. const normal = new Vector3();
  22508. const vertex = new Vector3();
  22509. let groupCount = 0;
  22510. // this will be used to calculate the normal
  22511. const slope = ( radiusBottom - radiusTop ) / height;
  22512. // generate vertices, normals and uvs
  22513. for ( let y = 0; y <= heightSegments; y ++ ) {
  22514. const indexRow = [];
  22515. const v = y / heightSegments;
  22516. // calculate the radius of the current row
  22517. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22518. for ( let x = 0; x <= radialSegments; x ++ ) {
  22519. const u = x / radialSegments;
  22520. const theta = u * thetaLength + thetaStart;
  22521. const sinTheta = Math.sin( theta );
  22522. const cosTheta = Math.cos( theta );
  22523. // vertex
  22524. vertex.x = radius * sinTheta;
  22525. vertex.y = - v * height + halfHeight;
  22526. vertex.z = radius * cosTheta;
  22527. vertices.push( vertex.x, vertex.y, vertex.z );
  22528. // normal
  22529. normal.set( sinTheta, slope, cosTheta ).normalize();
  22530. normals.push( normal.x, normal.y, normal.z );
  22531. // uv
  22532. uvs.push( u, 1 - v );
  22533. // save index of vertex in respective row
  22534. indexRow.push( index ++ );
  22535. }
  22536. // now save vertices of the row in our index array
  22537. indexArray.push( indexRow );
  22538. }
  22539. // generate indices
  22540. for ( let x = 0; x < radialSegments; x ++ ) {
  22541. for ( let y = 0; y < heightSegments; y ++ ) {
  22542. // we use the index array to access the correct indices
  22543. const a = indexArray[ y ][ x ];
  22544. const b = indexArray[ y + 1 ][ x ];
  22545. const c = indexArray[ y + 1 ][ x + 1 ];
  22546. const d = indexArray[ y ][ x + 1 ];
  22547. // faces
  22548. if ( radiusTop > 0 || y !== 0 ) {
  22549. indices.push( a, b, d );
  22550. groupCount += 3;
  22551. }
  22552. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22553. indices.push( b, c, d );
  22554. groupCount += 3;
  22555. }
  22556. }
  22557. }
  22558. // add a group to the geometry. this will ensure multi material support
  22559. scope.addGroup( groupStart, groupCount, 0 );
  22560. // calculate new start value for groups
  22561. groupStart += groupCount;
  22562. }
  22563. function generateCap( top ) {
  22564. // save the index of the first center vertex
  22565. const centerIndexStart = index;
  22566. const uv = new Vector2();
  22567. const vertex = new Vector3();
  22568. let groupCount = 0;
  22569. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22570. const sign = ( top === true ) ? 1 : -1;
  22571. // first we generate the center vertex data of the cap.
  22572. // because the geometry needs one set of uvs per face,
  22573. // we must generate a center vertex per face/segment
  22574. for ( let x = 1; x <= radialSegments; x ++ ) {
  22575. // vertex
  22576. vertices.push( 0, halfHeight * sign, 0 );
  22577. // normal
  22578. normals.push( 0, sign, 0 );
  22579. // uv
  22580. uvs.push( 0.5, 0.5 );
  22581. // increase index
  22582. index ++;
  22583. }
  22584. // save the index of the last center vertex
  22585. const centerIndexEnd = index;
  22586. // now we generate the surrounding vertices, normals and uvs
  22587. for ( let x = 0; x <= radialSegments; x ++ ) {
  22588. const u = x / radialSegments;
  22589. const theta = u * thetaLength + thetaStart;
  22590. const cosTheta = Math.cos( theta );
  22591. const sinTheta = Math.sin( theta );
  22592. // vertex
  22593. vertex.x = radius * sinTheta;
  22594. vertex.y = halfHeight * sign;
  22595. vertex.z = radius * cosTheta;
  22596. vertices.push( vertex.x, vertex.y, vertex.z );
  22597. // normal
  22598. normals.push( 0, sign, 0 );
  22599. // uv
  22600. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22601. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22602. uvs.push( uv.x, uv.y );
  22603. // increase index
  22604. index ++;
  22605. }
  22606. // generate indices
  22607. for ( let x = 0; x < radialSegments; x ++ ) {
  22608. const c = centerIndexStart + x;
  22609. const i = centerIndexEnd + x;
  22610. if ( top === true ) {
  22611. // face top
  22612. indices.push( i, i + 1, c );
  22613. } else {
  22614. // face bottom
  22615. indices.push( i + 1, i, c );
  22616. }
  22617. groupCount += 3;
  22618. }
  22619. // add a group to the geometry. this will ensure multi material support
  22620. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22621. // calculate new start value for groups
  22622. groupStart += groupCount;
  22623. }
  22624. }
  22625. copy( source ) {
  22626. super.copy( source );
  22627. this.parameters = Object.assign( {}, source.parameters );
  22628. return this;
  22629. }
  22630. /**
  22631. * Factory method for creating an instance of this class from the given
  22632. * JSON object.
  22633. *
  22634. * @param {Object} data - A JSON object representing the serialized geometry.
  22635. * @return {CylinderGeometry} A new instance.
  22636. */
  22637. static fromJSON( data ) {
  22638. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22639. }
  22640. }
  22641. /**
  22642. * A geometry class for representing a cone.
  22643. *
  22644. * ```js
  22645. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22646. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22647. * const cone = new THREE.Mesh(geometry, material );
  22648. * scene.add( cone );
  22649. * ```
  22650. *
  22651. * @augments CylinderGeometry
  22652. */
  22653. class ConeGeometry extends CylinderGeometry {
  22654. /**
  22655. * Constructs a new cone geometry.
  22656. *
  22657. * @param {number} [radius=1] - Radius of the cone base.
  22658. * @param {number} [height=1] - Height of the cone.
  22659. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22660. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22661. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22662. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22663. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22664. * The default value results in a complete cone.
  22665. */
  22666. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22667. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22668. this.type = 'ConeGeometry';
  22669. /**
  22670. * Holds the constructor parameters that have been
  22671. * used to generate the geometry. Any modification
  22672. * after instantiation does not change the geometry.
  22673. *
  22674. * @type {Object}
  22675. */
  22676. this.parameters = {
  22677. radius: radius,
  22678. height: height,
  22679. radialSegments: radialSegments,
  22680. heightSegments: heightSegments,
  22681. openEnded: openEnded,
  22682. thetaStart: thetaStart,
  22683. thetaLength: thetaLength
  22684. };
  22685. }
  22686. /**
  22687. * Factory method for creating an instance of this class from the given
  22688. * JSON object.
  22689. *
  22690. * @param {Object} data - A JSON object representing the serialized geometry.
  22691. * @return {ConeGeometry} A new instance.
  22692. */
  22693. static fromJSON( data ) {
  22694. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22695. }
  22696. }
  22697. /**
  22698. * A polyhedron is a solid in three dimensions with flat faces. This class
  22699. * will take an array of vertices, project them onto a sphere, and then
  22700. * divide them up to the desired level of detail.
  22701. *
  22702. * @augments BufferGeometry
  22703. */
  22704. class PolyhedronGeometry extends BufferGeometry {
  22705. /**
  22706. * Constructs a new polyhedron geometry.
  22707. *
  22708. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22709. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22710. * @param {number} [radius=1] - The radius of the shape.
  22711. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22712. */
  22713. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22714. super();
  22715. this.type = 'PolyhedronGeometry';
  22716. /**
  22717. * Holds the constructor parameters that have been
  22718. * used to generate the geometry. Any modification
  22719. * after instantiation does not change the geometry.
  22720. *
  22721. * @type {Object}
  22722. */
  22723. this.parameters = {
  22724. vertices: vertices,
  22725. indices: indices,
  22726. radius: radius,
  22727. detail: detail
  22728. };
  22729. // default buffer data
  22730. const vertexBuffer = [];
  22731. const uvBuffer = [];
  22732. // the subdivision creates the vertex buffer data
  22733. subdivide( detail );
  22734. // all vertices should lie on a conceptual sphere with a given radius
  22735. applyRadius( radius );
  22736. // finally, create the uv data
  22737. generateUVs();
  22738. // build non-indexed geometry
  22739. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22740. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22741. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22742. if ( detail === 0 ) {
  22743. this.computeVertexNormals(); // flat normals
  22744. } else {
  22745. this.normalizeNormals(); // smooth normals
  22746. }
  22747. // helper functions
  22748. function subdivide( detail ) {
  22749. const a = new Vector3();
  22750. const b = new Vector3();
  22751. const c = new Vector3();
  22752. // iterate over all faces and apply a subdivision with the given detail value
  22753. for ( let i = 0; i < indices.length; i += 3 ) {
  22754. // get the vertices of the face
  22755. getVertexByIndex( indices[ i + 0 ], a );
  22756. getVertexByIndex( indices[ i + 1 ], b );
  22757. getVertexByIndex( indices[ i + 2 ], c );
  22758. // perform subdivision
  22759. subdivideFace( a, b, c, detail );
  22760. }
  22761. }
  22762. function subdivideFace( a, b, c, detail ) {
  22763. const cols = detail + 1;
  22764. // we use this multidimensional array as a data structure for creating the subdivision
  22765. const v = [];
  22766. // construct all of the vertices for this subdivision
  22767. for ( let i = 0; i <= cols; i ++ ) {
  22768. v[ i ] = [];
  22769. const aj = a.clone().lerp( c, i / cols );
  22770. const bj = b.clone().lerp( c, i / cols );
  22771. const rows = cols - i;
  22772. for ( let j = 0; j <= rows; j ++ ) {
  22773. if ( j === 0 && i === cols ) {
  22774. v[ i ][ j ] = aj;
  22775. } else {
  22776. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22777. }
  22778. }
  22779. }
  22780. // construct all of the faces
  22781. for ( let i = 0; i < cols; i ++ ) {
  22782. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22783. const k = Math.floor( j / 2 );
  22784. if ( j % 2 === 0 ) {
  22785. pushVertex( v[ i ][ k + 1 ] );
  22786. pushVertex( v[ i + 1 ][ k ] );
  22787. pushVertex( v[ i ][ k ] );
  22788. } else {
  22789. pushVertex( v[ i ][ k + 1 ] );
  22790. pushVertex( v[ i + 1 ][ k + 1 ] );
  22791. pushVertex( v[ i + 1 ][ k ] );
  22792. }
  22793. }
  22794. }
  22795. }
  22796. function applyRadius( radius ) {
  22797. const vertex = new Vector3();
  22798. // iterate over the entire buffer and apply the radius to each vertex
  22799. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22800. vertex.x = vertexBuffer[ i + 0 ];
  22801. vertex.y = vertexBuffer[ i + 1 ];
  22802. vertex.z = vertexBuffer[ i + 2 ];
  22803. vertex.normalize().multiplyScalar( radius );
  22804. vertexBuffer[ i + 0 ] = vertex.x;
  22805. vertexBuffer[ i + 1 ] = vertex.y;
  22806. vertexBuffer[ i + 2 ] = vertex.z;
  22807. }
  22808. }
  22809. function generateUVs() {
  22810. const vertex = new Vector3();
  22811. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22812. vertex.x = vertexBuffer[ i + 0 ];
  22813. vertex.y = vertexBuffer[ i + 1 ];
  22814. vertex.z = vertexBuffer[ i + 2 ];
  22815. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22816. const v = inclination( vertex ) / Math.PI + 0.5;
  22817. uvBuffer.push( u, 1 - v );
  22818. }
  22819. correctUVs();
  22820. correctSeam();
  22821. }
  22822. function correctSeam() {
  22823. // handle case when face straddles the seam, see #3269
  22824. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22825. // uv data of a single face
  22826. const x0 = uvBuffer[ i + 0 ];
  22827. const x1 = uvBuffer[ i + 2 ];
  22828. const x2 = uvBuffer[ i + 4 ];
  22829. const max = Math.max( x0, x1, x2 );
  22830. const min = Math.min( x0, x1, x2 );
  22831. // 0.9 is somewhat arbitrary
  22832. if ( max > 0.9 && min < 0.1 ) {
  22833. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22834. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22835. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22836. }
  22837. }
  22838. }
  22839. function pushVertex( vertex ) {
  22840. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22841. }
  22842. function getVertexByIndex( index, vertex ) {
  22843. const stride = index * 3;
  22844. vertex.x = vertices[ stride + 0 ];
  22845. vertex.y = vertices[ stride + 1 ];
  22846. vertex.z = vertices[ stride + 2 ];
  22847. }
  22848. function correctUVs() {
  22849. const a = new Vector3();
  22850. const b = new Vector3();
  22851. const c = new Vector3();
  22852. const centroid = new Vector3();
  22853. const uvA = new Vector2();
  22854. const uvB = new Vector2();
  22855. const uvC = new Vector2();
  22856. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  22857. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  22858. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  22859. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  22860. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  22861. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  22862. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  22863. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  22864. const azi = azimuth( centroid );
  22865. correctUV( uvA, j + 0, a, azi );
  22866. correctUV( uvB, j + 2, b, azi );
  22867. correctUV( uvC, j + 4, c, azi );
  22868. }
  22869. }
  22870. function correctUV( uv, stride, vector, azimuth ) {
  22871. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  22872. uvBuffer[ stride ] = uv.x - 1;
  22873. }
  22874. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  22875. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  22876. }
  22877. }
  22878. // Angle around the Y axis, counter-clockwise when looking from above.
  22879. function azimuth( vector ) {
  22880. return Math.atan2( vector.z, - vector.x );
  22881. }
  22882. // Angle above the XZ plane.
  22883. function inclination( vector ) {
  22884. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  22885. }
  22886. }
  22887. copy( source ) {
  22888. super.copy( source );
  22889. this.parameters = Object.assign( {}, source.parameters );
  22890. return this;
  22891. }
  22892. /**
  22893. * Factory method for creating an instance of this class from the given
  22894. * JSON object.
  22895. *
  22896. * @param {Object} data - A JSON object representing the serialized geometry.
  22897. * @return {PolyhedronGeometry} A new instance.
  22898. */
  22899. static fromJSON( data ) {
  22900. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  22901. }
  22902. }
  22903. /**
  22904. * A geometry class for representing a dodecahedron.
  22905. *
  22906. * ```js
  22907. * const geometry = new THREE.DodecahedronGeometry();
  22908. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22909. * const dodecahedron = new THREE.Mesh( geometry, material );
  22910. * scene.add( dodecahedron );
  22911. * ```
  22912. *
  22913. * @augments PolyhedronGeometry
  22914. */
  22915. class DodecahedronGeometry extends PolyhedronGeometry {
  22916. /**
  22917. * Constructs a new dodecahedron geometry.
  22918. *
  22919. * @param {number} [radius=1] - Radius of the dodecahedron.
  22920. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  22921. */
  22922. constructor( radius = 1, detail = 0 ) {
  22923. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22924. const r = 1 / t;
  22925. const vertices = [
  22926. // (±1, ±1, ±1)
  22927. -1, -1, -1, -1, -1, 1,
  22928. -1, 1, -1, -1, 1, 1,
  22929. 1, -1, -1, 1, -1, 1,
  22930. 1, 1, -1, 1, 1, 1,
  22931. // (0, ±1/φ, ±φ)
  22932. 0, - r, - t, 0, - r, t,
  22933. 0, r, - t, 0, r, t,
  22934. // (±1/φ, ±φ, 0)
  22935. - r, - t, 0, - r, t, 0,
  22936. r, - t, 0, r, t, 0,
  22937. // (±φ, 0, ±1/φ)
  22938. - t, 0, - r, t, 0, - r,
  22939. - t, 0, r, t, 0, r
  22940. ];
  22941. const indices = [
  22942. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  22943. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  22944. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  22945. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  22946. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  22947. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  22948. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  22949. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  22950. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  22951. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  22952. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  22953. 1, 12, 14, 1, 14, 5, 1, 5, 9
  22954. ];
  22955. super( vertices, indices, radius, detail );
  22956. this.type = 'DodecahedronGeometry';
  22957. /**
  22958. * Holds the constructor parameters that have been
  22959. * used to generate the geometry. Any modification
  22960. * after instantiation does not change the geometry.
  22961. *
  22962. * @type {Object}
  22963. */
  22964. this.parameters = {
  22965. radius: radius,
  22966. detail: detail
  22967. };
  22968. }
  22969. /**
  22970. * Factory method for creating an instance of this class from the given
  22971. * JSON object.
  22972. *
  22973. * @param {Object} data - A JSON object representing the serialized geometry.
  22974. * @return {DodecahedronGeometry} A new instance.
  22975. */
  22976. static fromJSON( data ) {
  22977. return new DodecahedronGeometry( data.radius, data.detail );
  22978. }
  22979. }
  22980. const _v0$1 = /*@__PURE__*/ new Vector3();
  22981. const _v1$1 = /*@__PURE__*/ new Vector3();
  22982. const _normal = /*@__PURE__*/ new Vector3();
  22983. const _triangle = /*@__PURE__*/ new Triangle();
  22984. /**
  22985. * Can be used as a helper object to view the edges of a geometry.
  22986. *
  22987. * ```js
  22988. * const geometry = new THREE.BoxGeometry();
  22989. * const edges = new THREE.EdgesGeometry( geometry );
  22990. * const line = new THREE.LineSegments( edges );
  22991. * scene.add( line );
  22992. * ```
  22993. *
  22994. * Note: It is not yet possible to serialize/deserialize instances of this class.
  22995. *
  22996. * @augments BufferGeometry
  22997. */
  22998. class EdgesGeometry extends BufferGeometry {
  22999. /**
  23000. * Constructs a new edges geometry.
  23001. *
  23002. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23003. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23004. * between the face normals of the adjoining faces exceeds this value.
  23005. */
  23006. constructor( geometry = null, thresholdAngle = 1 ) {
  23007. super();
  23008. this.type = 'EdgesGeometry';
  23009. /**
  23010. * Holds the constructor parameters that have been
  23011. * used to generate the geometry. Any modification
  23012. * after instantiation does not change the geometry.
  23013. *
  23014. * @type {Object}
  23015. */
  23016. this.parameters = {
  23017. geometry: geometry,
  23018. thresholdAngle: thresholdAngle
  23019. };
  23020. if ( geometry !== null ) {
  23021. const precisionPoints = 4;
  23022. const precision = Math.pow( 10, precisionPoints );
  23023. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23024. const indexAttr = geometry.getIndex();
  23025. const positionAttr = geometry.getAttribute( 'position' );
  23026. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23027. const indexArr = [ 0, 0, 0 ];
  23028. const vertKeys = [ 'a', 'b', 'c' ];
  23029. const hashes = new Array( 3 );
  23030. const edgeData = {};
  23031. const vertices = [];
  23032. for ( let i = 0; i < indexCount; i += 3 ) {
  23033. if ( indexAttr ) {
  23034. indexArr[ 0 ] = indexAttr.getX( i );
  23035. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23036. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23037. } else {
  23038. indexArr[ 0 ] = i;
  23039. indexArr[ 1 ] = i + 1;
  23040. indexArr[ 2 ] = i + 2;
  23041. }
  23042. const { a, b, c } = _triangle;
  23043. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23044. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23045. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23046. _triangle.getNormal( _normal );
  23047. // create hashes for the edge from the vertices
  23048. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23049. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23050. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23051. // skip degenerate triangles
  23052. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23053. continue;
  23054. }
  23055. // iterate over every edge
  23056. for ( let j = 0; j < 3; j ++ ) {
  23057. // get the first and next vertex making up the edge
  23058. const jNext = ( j + 1 ) % 3;
  23059. const vecHash0 = hashes[ j ];
  23060. const vecHash1 = hashes[ jNext ];
  23061. const v0 = _triangle[ vertKeys[ j ] ];
  23062. const v1 = _triangle[ vertKeys[ jNext ] ];
  23063. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23064. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23065. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23066. // if we found a sibling edge add it into the vertex array if
  23067. // it meets the angle threshold and delete the edge from the map.
  23068. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23069. vertices.push( v0.x, v0.y, v0.z );
  23070. vertices.push( v1.x, v1.y, v1.z );
  23071. }
  23072. edgeData[ reverseHash ] = null;
  23073. } else if ( ! ( hash in edgeData ) ) {
  23074. // if we've already got an edge here then skip adding a new one
  23075. edgeData[ hash ] = {
  23076. index0: indexArr[ j ],
  23077. index1: indexArr[ jNext ],
  23078. normal: _normal.clone(),
  23079. };
  23080. }
  23081. }
  23082. }
  23083. // iterate over all remaining, unmatched edges and add them to the vertex array
  23084. for ( const key in edgeData ) {
  23085. if ( edgeData[ key ] ) {
  23086. const { index0, index1 } = edgeData[ key ];
  23087. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23088. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23089. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23090. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23091. }
  23092. }
  23093. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23094. }
  23095. }
  23096. copy( source ) {
  23097. super.copy( source );
  23098. this.parameters = Object.assign( {}, source.parameters );
  23099. return this;
  23100. }
  23101. }
  23102. /**
  23103. * An abstract base class for creating an analytic curve object that contains methods
  23104. * for interpolation.
  23105. *
  23106. * @abstract
  23107. */
  23108. class Curve {
  23109. /**
  23110. * Constructs a new curve.
  23111. */
  23112. constructor() {
  23113. /**
  23114. * The type property is used for detecting the object type
  23115. * in context of serialization/deserialization.
  23116. *
  23117. * @type {string}
  23118. * @readonly
  23119. */
  23120. this.type = 'Curve';
  23121. /**
  23122. * This value determines the amount of divisions when calculating the
  23123. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23124. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23125. * recommended to increase the value of this property if the curve is very large.
  23126. *
  23127. * @type {number}
  23128. * @default 200
  23129. */
  23130. this.arcLengthDivisions = 200;
  23131. /**
  23132. * Must be set to `true` if the curve parameters have changed.
  23133. *
  23134. * @type {boolean}
  23135. * @default false
  23136. */
  23137. this.needsUpdate = false;
  23138. /**
  23139. * An internal cache that holds precomputed curve length values.
  23140. *
  23141. * @private
  23142. * @type {?Array<number>}
  23143. * @default null
  23144. */
  23145. this.cacheArcLengths = null;
  23146. }
  23147. /**
  23148. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23149. * for the given interpolation factor.
  23150. *
  23151. * @abstract
  23152. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23153. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23154. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23155. */
  23156. getPoint( /* t, optionalTarget */ ) {
  23157. warn( 'Curve: .getPoint() not implemented.' );
  23158. }
  23159. /**
  23160. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23161. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23162. * of the curve which equidistant samples.
  23163. *
  23164. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23165. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23166. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23167. */
  23168. getPointAt( u, optionalTarget ) {
  23169. const t = this.getUtoTmapping( u );
  23170. return this.getPoint( t, optionalTarget );
  23171. }
  23172. /**
  23173. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23174. * the curve shape.
  23175. *
  23176. * @param {number} [divisions=5] - The number of divisions.
  23177. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23178. */
  23179. getPoints( divisions = 5 ) {
  23180. const points = [];
  23181. for ( let d = 0; d <= divisions; d ++ ) {
  23182. points.push( this.getPoint( d / divisions ) );
  23183. }
  23184. return points;
  23185. }
  23186. // Get sequence of points using getPointAt( u )
  23187. /**
  23188. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23189. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23190. * curve.
  23191. *
  23192. * @param {number} [divisions=5] - The number of divisions.
  23193. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23194. */
  23195. getSpacedPoints( divisions = 5 ) {
  23196. const points = [];
  23197. for ( let d = 0; d <= divisions; d ++ ) {
  23198. points.push( this.getPointAt( d / divisions ) );
  23199. }
  23200. return points;
  23201. }
  23202. /**
  23203. * Returns the total arc length of the curve.
  23204. *
  23205. * @return {number} The length of the curve.
  23206. */
  23207. getLength() {
  23208. const lengths = this.getLengths();
  23209. return lengths[ lengths.length - 1 ];
  23210. }
  23211. /**
  23212. * Returns an array of cumulative segment lengths of the curve.
  23213. *
  23214. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23215. * @return {Array<number>} An array holding the cumulative segment lengths.
  23216. */
  23217. getLengths( divisions = this.arcLengthDivisions ) {
  23218. if ( this.cacheArcLengths &&
  23219. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23220. ! this.needsUpdate ) {
  23221. return this.cacheArcLengths;
  23222. }
  23223. this.needsUpdate = false;
  23224. const cache = [];
  23225. let current, last = this.getPoint( 0 );
  23226. let sum = 0;
  23227. cache.push( 0 );
  23228. for ( let p = 1; p <= divisions; p ++ ) {
  23229. current = this.getPoint( p / divisions );
  23230. sum += current.distanceTo( last );
  23231. cache.push( sum );
  23232. last = current;
  23233. }
  23234. this.cacheArcLengths = cache;
  23235. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23236. }
  23237. /**
  23238. * Update the cumulative segment distance cache. The method must be called
  23239. * every time curve parameters are changed. If an updated curve is part of a
  23240. * composed curve like {@link CurvePath}, this method must be called on the
  23241. * composed curve, too.
  23242. */
  23243. updateArcLengths() {
  23244. this.needsUpdate = true;
  23245. this.getLengths();
  23246. }
  23247. /**
  23248. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23249. * interpolation factor in the same range that can be ued to sample equidistant points
  23250. * from a curve.
  23251. *
  23252. * @param {number} u - The interpolation factor.
  23253. * @param {?number} distance - An optional distance on the curve.
  23254. * @return {number} The updated interpolation factor.
  23255. */
  23256. getUtoTmapping( u, distance = null ) {
  23257. const arcLengths = this.getLengths();
  23258. let i = 0;
  23259. const il = arcLengths.length;
  23260. let targetArcLength; // The targeted u distance value to get
  23261. if ( distance ) {
  23262. targetArcLength = distance;
  23263. } else {
  23264. targetArcLength = u * arcLengths[ il - 1 ];
  23265. }
  23266. // binary search for the index with largest value smaller than target u distance
  23267. let low = 0, high = il - 1, comparison;
  23268. while ( low <= high ) {
  23269. 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
  23270. comparison = arcLengths[ i ] - targetArcLength;
  23271. if ( comparison < 0 ) {
  23272. low = i + 1;
  23273. } else if ( comparison > 0 ) {
  23274. high = i - 1;
  23275. } else {
  23276. high = i;
  23277. break;
  23278. // DONE
  23279. }
  23280. }
  23281. i = high;
  23282. if ( arcLengths[ i ] === targetArcLength ) {
  23283. return i / ( il - 1 );
  23284. }
  23285. // we could get finer grain at lengths, or use simple interpolation between two points
  23286. const lengthBefore = arcLengths[ i ];
  23287. const lengthAfter = arcLengths[ i + 1 ];
  23288. const segmentLength = lengthAfter - lengthBefore;
  23289. // determine where we are between the 'before' and 'after' points
  23290. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23291. // add that fractional amount to t
  23292. const t = ( i + segmentFraction ) / ( il - 1 );
  23293. return t;
  23294. }
  23295. /**
  23296. * Returns a unit vector tangent for the given interpolation factor.
  23297. * If the derived curve does not implement its tangent derivation,
  23298. * two points a small delta apart will be used to find its gradient
  23299. * which seems to give a reasonable approximation.
  23300. *
  23301. * @param {number} t - The interpolation factor.
  23302. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23303. * @return {(Vector2|Vector3)} The tangent vector.
  23304. */
  23305. getTangent( t, optionalTarget ) {
  23306. const delta = 0.0001;
  23307. let t1 = t - delta;
  23308. let t2 = t + delta;
  23309. // Capping in case of danger
  23310. if ( t1 < 0 ) t1 = 0;
  23311. if ( t2 > 1 ) t2 = 1;
  23312. const pt1 = this.getPoint( t1 );
  23313. const pt2 = this.getPoint( t2 );
  23314. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23315. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23316. return tangent;
  23317. }
  23318. /**
  23319. * Same as {@link Curve#getTangent} but with equidistant samples.
  23320. *
  23321. * @param {number} u - The interpolation factor.
  23322. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23323. * @return {(Vector2|Vector3)} The tangent vector.
  23324. * @see {@link Curve#getPointAt}
  23325. */
  23326. getTangentAt( u, optionalTarget ) {
  23327. const t = this.getUtoTmapping( u );
  23328. return this.getTangent( t, optionalTarget );
  23329. }
  23330. /**
  23331. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23332. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23333. *
  23334. * @param {number} segments - The number of segments.
  23335. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23336. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23337. */
  23338. computeFrenetFrames( segments, closed = false ) {
  23339. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23340. const normal = new Vector3();
  23341. const tangents = [];
  23342. const normals = [];
  23343. const binormals = [];
  23344. const vec = new Vector3();
  23345. const mat = new Matrix4();
  23346. // compute the tangent vectors for each segment on the curve
  23347. for ( let i = 0; i <= segments; i ++ ) {
  23348. const u = i / segments;
  23349. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23350. }
  23351. // select an initial normal vector perpendicular to the first tangent vector,
  23352. // and in the direction of the minimum tangent xyz component
  23353. normals[ 0 ] = new Vector3();
  23354. binormals[ 0 ] = new Vector3();
  23355. let min = Number.MAX_VALUE;
  23356. const tx = Math.abs( tangents[ 0 ].x );
  23357. const ty = Math.abs( tangents[ 0 ].y );
  23358. const tz = Math.abs( tangents[ 0 ].z );
  23359. if ( tx <= min ) {
  23360. min = tx;
  23361. normal.set( 1, 0, 0 );
  23362. }
  23363. if ( ty <= min ) {
  23364. min = ty;
  23365. normal.set( 0, 1, 0 );
  23366. }
  23367. if ( tz <= min ) {
  23368. normal.set( 0, 0, 1 );
  23369. }
  23370. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23371. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23372. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23373. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23374. for ( let i = 1; i <= segments; i ++ ) {
  23375. normals[ i ] = normals[ i - 1 ].clone();
  23376. binormals[ i ] = binormals[ i - 1 ].clone();
  23377. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23378. if ( vec.length() > Number.EPSILON ) {
  23379. vec.normalize();
  23380. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23381. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23382. }
  23383. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23384. }
  23385. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23386. if ( closed === true ) {
  23387. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23388. theta /= segments;
  23389. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23390. theta = - theta;
  23391. }
  23392. for ( let i = 1; i <= segments; i ++ ) {
  23393. // twist a little...
  23394. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23395. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23396. }
  23397. }
  23398. return {
  23399. tangents: tangents,
  23400. normals: normals,
  23401. binormals: binormals
  23402. };
  23403. }
  23404. /**
  23405. * Returns a new curve with copied values from this instance.
  23406. *
  23407. * @return {Curve} A clone of this instance.
  23408. */
  23409. clone() {
  23410. return new this.constructor().copy( this );
  23411. }
  23412. /**
  23413. * Copies the values of the given curve to this instance.
  23414. *
  23415. * @param {Curve} source - The curve to copy.
  23416. * @return {Curve} A reference to this curve.
  23417. */
  23418. copy( source ) {
  23419. this.arcLengthDivisions = source.arcLengthDivisions;
  23420. return this;
  23421. }
  23422. /**
  23423. * Serializes the curve into JSON.
  23424. *
  23425. * @return {Object} A JSON object representing the serialized curve.
  23426. * @see {@link ObjectLoader#parse}
  23427. */
  23428. toJSON() {
  23429. const data = {
  23430. metadata: {
  23431. version: 4.7,
  23432. type: 'Curve',
  23433. generator: 'Curve.toJSON'
  23434. }
  23435. };
  23436. data.arcLengthDivisions = this.arcLengthDivisions;
  23437. data.type = this.type;
  23438. return data;
  23439. }
  23440. /**
  23441. * Deserializes the curve from the given JSON.
  23442. *
  23443. * @param {Object} json - The JSON holding the serialized curve.
  23444. * @return {Curve} A reference to this curve.
  23445. */
  23446. fromJSON( json ) {
  23447. this.arcLengthDivisions = json.arcLengthDivisions;
  23448. return this;
  23449. }
  23450. }
  23451. /**
  23452. * A curve representing an ellipse.
  23453. *
  23454. * ```js
  23455. * const curve = new THREE.EllipseCurve(
  23456. * 0, 0,
  23457. * 10, 10,
  23458. * 0, 2 * Math.PI,
  23459. * false,
  23460. * 0
  23461. * );
  23462. *
  23463. * const points = curve.getPoints( 50 );
  23464. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23465. *
  23466. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23467. *
  23468. * // Create the final object to add to the scene
  23469. * const ellipse = new THREE.Line( geometry, material );
  23470. * ```
  23471. *
  23472. * @augments Curve
  23473. */
  23474. class EllipseCurve extends Curve {
  23475. /**
  23476. * Constructs a new ellipse curve.
  23477. *
  23478. * @param {number} [aX=0] - The X center of the ellipse.
  23479. * @param {number} [aY=0] - The Y center of the ellipse.
  23480. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23481. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23482. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23483. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23484. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23485. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23486. */
  23487. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23488. super();
  23489. /**
  23490. * This flag can be used for type testing.
  23491. *
  23492. * @type {boolean}
  23493. * @readonly
  23494. * @default true
  23495. */
  23496. this.isEllipseCurve = true;
  23497. this.type = 'EllipseCurve';
  23498. /**
  23499. * The X center of the ellipse.
  23500. *
  23501. * @type {number}
  23502. * @default 0
  23503. */
  23504. this.aX = aX;
  23505. /**
  23506. * The Y center of the ellipse.
  23507. *
  23508. * @type {number}
  23509. * @default 0
  23510. */
  23511. this.aY = aY;
  23512. /**
  23513. * The radius of the ellipse in the x direction.
  23514. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23515. *
  23516. * @type {number}
  23517. * @default 1
  23518. */
  23519. this.xRadius = xRadius;
  23520. /**
  23521. * The radius of the ellipse in the y direction.
  23522. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23523. *
  23524. * @type {number}
  23525. * @default 1
  23526. */
  23527. this.yRadius = yRadius;
  23528. /**
  23529. * The start angle of the curve in radians starting from the positive X axis.
  23530. *
  23531. * @type {number}
  23532. * @default 0
  23533. */
  23534. this.aStartAngle = aStartAngle;
  23535. /**
  23536. * The end angle of the curve in radians starting from the positive X axis.
  23537. *
  23538. * @type {number}
  23539. * @default Math.PI*2
  23540. */
  23541. this.aEndAngle = aEndAngle;
  23542. /**
  23543. * Whether the ellipse is drawn clockwise or not.
  23544. *
  23545. * @type {boolean}
  23546. * @default false
  23547. */
  23548. this.aClockwise = aClockwise;
  23549. /**
  23550. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23551. *
  23552. * @type {number}
  23553. * @default 0
  23554. */
  23555. this.aRotation = aRotation;
  23556. }
  23557. /**
  23558. * Returns a point on the curve.
  23559. *
  23560. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23561. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23562. * @return {Vector2} The position on the curve.
  23563. */
  23564. getPoint( t, optionalTarget = new Vector2() ) {
  23565. const point = optionalTarget;
  23566. const twoPi = Math.PI * 2;
  23567. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23568. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23569. // ensures that deltaAngle is 0 .. 2 PI
  23570. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23571. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23572. if ( deltaAngle < Number.EPSILON ) {
  23573. if ( samePoints ) {
  23574. deltaAngle = 0;
  23575. } else {
  23576. deltaAngle = twoPi;
  23577. }
  23578. }
  23579. if ( this.aClockwise === true && ! samePoints ) {
  23580. if ( deltaAngle === twoPi ) {
  23581. deltaAngle = - twoPi;
  23582. } else {
  23583. deltaAngle = deltaAngle - twoPi;
  23584. }
  23585. }
  23586. const angle = this.aStartAngle + t * deltaAngle;
  23587. let x = this.aX + this.xRadius * Math.cos( angle );
  23588. let y = this.aY + this.yRadius * Math.sin( angle );
  23589. if ( this.aRotation !== 0 ) {
  23590. const cos = Math.cos( this.aRotation );
  23591. const sin = Math.sin( this.aRotation );
  23592. const tx = x - this.aX;
  23593. const ty = y - this.aY;
  23594. // Rotate the point about the center of the ellipse.
  23595. x = tx * cos - ty * sin + this.aX;
  23596. y = tx * sin + ty * cos + this.aY;
  23597. }
  23598. return point.set( x, y );
  23599. }
  23600. copy( source ) {
  23601. super.copy( source );
  23602. this.aX = source.aX;
  23603. this.aY = source.aY;
  23604. this.xRadius = source.xRadius;
  23605. this.yRadius = source.yRadius;
  23606. this.aStartAngle = source.aStartAngle;
  23607. this.aEndAngle = source.aEndAngle;
  23608. this.aClockwise = source.aClockwise;
  23609. this.aRotation = source.aRotation;
  23610. return this;
  23611. }
  23612. toJSON() {
  23613. const data = super.toJSON();
  23614. data.aX = this.aX;
  23615. data.aY = this.aY;
  23616. data.xRadius = this.xRadius;
  23617. data.yRadius = this.yRadius;
  23618. data.aStartAngle = this.aStartAngle;
  23619. data.aEndAngle = this.aEndAngle;
  23620. data.aClockwise = this.aClockwise;
  23621. data.aRotation = this.aRotation;
  23622. return data;
  23623. }
  23624. fromJSON( json ) {
  23625. super.fromJSON( json );
  23626. this.aX = json.aX;
  23627. this.aY = json.aY;
  23628. this.xRadius = json.xRadius;
  23629. this.yRadius = json.yRadius;
  23630. this.aStartAngle = json.aStartAngle;
  23631. this.aEndAngle = json.aEndAngle;
  23632. this.aClockwise = json.aClockwise;
  23633. this.aRotation = json.aRotation;
  23634. return this;
  23635. }
  23636. }
  23637. /**
  23638. * A curve representing an arc.
  23639. *
  23640. * @augments EllipseCurve
  23641. */
  23642. class ArcCurve extends EllipseCurve {
  23643. /**
  23644. * Constructs a new arc curve.
  23645. *
  23646. * @param {number} [aX=0] - The X center of the ellipse.
  23647. * @param {number} [aY=0] - The Y center of the ellipse.
  23648. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23649. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23650. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23651. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23652. */
  23653. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23654. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23655. /**
  23656. * This flag can be used for type testing.
  23657. *
  23658. * @type {boolean}
  23659. * @readonly
  23660. * @default true
  23661. */
  23662. this.isArcCurve = true;
  23663. this.type = 'ArcCurve';
  23664. }
  23665. }
  23666. function CubicPoly() {
  23667. /**
  23668. * Centripetal CatmullRom Curve - which is useful for avoiding
  23669. * cusps and self-intersections in non-uniform catmull rom curves.
  23670. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23671. *
  23672. * curve.type accepts centripetal(default), chordal and catmullrom
  23673. * curve.tension is used for catmullrom which defaults to 0.5
  23674. */
  23675. /*
  23676. Based on an optimized c++ solution in
  23677. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23678. - http://ideone.com/NoEbVM
  23679. This CubicPoly class could be used for reusing some variables and calculations,
  23680. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23681. which can be placed in CurveUtils.
  23682. */
  23683. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23684. /*
  23685. * Compute coefficients for a cubic polynomial
  23686. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23687. * such that
  23688. * p(0) = x0, p(1) = x1
  23689. * and
  23690. * p'(0) = t0, p'(1) = t1.
  23691. */
  23692. function init( x0, x1, t0, t1 ) {
  23693. c0 = x0;
  23694. c1 = t0;
  23695. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23696. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23697. }
  23698. return {
  23699. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23700. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23701. },
  23702. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23703. // compute tangents when parameterized in [t1,t2]
  23704. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23705. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23706. // rescale tangents for parametrization in [0,1]
  23707. t1 *= dt1;
  23708. t2 *= dt1;
  23709. init( x1, x2, t1, t2 );
  23710. },
  23711. calc: function ( t ) {
  23712. const t2 = t * t;
  23713. const t3 = t2 * t;
  23714. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23715. }
  23716. };
  23717. }
  23718. //
  23719. const tmp = /*@__PURE__*/ new Vector3();
  23720. const px = /*@__PURE__*/ new CubicPoly();
  23721. const py = /*@__PURE__*/ new CubicPoly();
  23722. const pz = /*@__PURE__*/ new CubicPoly();
  23723. /**
  23724. * A curve representing a Catmull-Rom spline.
  23725. *
  23726. * ```js
  23727. * //Create a closed wavey loop
  23728. * const curve = new THREE.CatmullRomCurve3( [
  23729. * new THREE.Vector3( -10, 0, 10 ),
  23730. * new THREE.Vector3( -5, 5, 5 ),
  23731. * new THREE.Vector3( 0, 0, 0 ),
  23732. * new THREE.Vector3( 5, -5, 5 ),
  23733. * new THREE.Vector3( 10, 0, 10 )
  23734. * ] );
  23735. *
  23736. * const points = curve.getPoints( 50 );
  23737. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23738. *
  23739. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23740. *
  23741. * // Create the final object to add to the scene
  23742. * const curveObject = new THREE.Line( geometry, material );
  23743. * ```
  23744. *
  23745. * @augments Curve
  23746. */
  23747. class CatmullRomCurve3 extends Curve {
  23748. /**
  23749. * Constructs a new Catmull-Rom curve.
  23750. *
  23751. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23752. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23753. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23754. * @param {number} [tension=0.5] - Tension of the curve.
  23755. */
  23756. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23757. super();
  23758. /**
  23759. * This flag can be used for type testing.
  23760. *
  23761. * @type {boolean}
  23762. * @readonly
  23763. * @default true
  23764. */
  23765. this.isCatmullRomCurve3 = true;
  23766. this.type = 'CatmullRomCurve3';
  23767. /**
  23768. * An array of 3D points defining the curve.
  23769. *
  23770. * @type {Array<Vector3>}
  23771. */
  23772. this.points = points;
  23773. /**
  23774. * Whether the curve is closed or not.
  23775. *
  23776. * @type {boolean}
  23777. * @default false
  23778. */
  23779. this.closed = closed;
  23780. /**
  23781. * The curve type.
  23782. *
  23783. * @type {('centripetal'|'chordal'|'catmullrom')}
  23784. * @default 'centripetal'
  23785. */
  23786. this.curveType = curveType;
  23787. /**
  23788. * Tension of the curve.
  23789. *
  23790. * @type {number}
  23791. * @default 0.5
  23792. */
  23793. this.tension = tension;
  23794. }
  23795. /**
  23796. * Returns a point on the curve.
  23797. *
  23798. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23799. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23800. * @return {Vector3} The position on the curve.
  23801. */
  23802. getPoint( t, optionalTarget = new Vector3() ) {
  23803. const point = optionalTarget;
  23804. const points = this.points;
  23805. const l = points.length;
  23806. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23807. let intPoint = Math.floor( p );
  23808. let weight = p - intPoint;
  23809. if ( this.closed ) {
  23810. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23811. } else if ( weight === 0 && intPoint === l - 1 ) {
  23812. intPoint = l - 2;
  23813. weight = 1;
  23814. }
  23815. let p0, p3; // 4 points (p1 & p2 defined below)
  23816. if ( this.closed || intPoint > 0 ) {
  23817. p0 = points[ ( intPoint - 1 ) % l ];
  23818. } else {
  23819. // extrapolate first point
  23820. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23821. p0 = tmp;
  23822. }
  23823. const p1 = points[ intPoint % l ];
  23824. const p2 = points[ ( intPoint + 1 ) % l ];
  23825. if ( this.closed || intPoint + 2 < l ) {
  23826. p3 = points[ ( intPoint + 2 ) % l ];
  23827. } else {
  23828. // extrapolate last point
  23829. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23830. p3 = tmp;
  23831. }
  23832. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23833. // init Centripetal / Chordal Catmull-Rom
  23834. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23835. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23836. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23837. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23838. // safety check for repeated points
  23839. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23840. if ( dt0 < 1e-4 ) dt0 = dt1;
  23841. if ( dt2 < 1e-4 ) dt2 = dt1;
  23842. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23843. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23844. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23845. } else if ( this.curveType === 'catmullrom' ) {
  23846. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23847. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23848. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23849. }
  23850. point.set(
  23851. px.calc( weight ),
  23852. py.calc( weight ),
  23853. pz.calc( weight )
  23854. );
  23855. return point;
  23856. }
  23857. copy( source ) {
  23858. super.copy( source );
  23859. this.points = [];
  23860. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  23861. const point = source.points[ i ];
  23862. this.points.push( point.clone() );
  23863. }
  23864. this.closed = source.closed;
  23865. this.curveType = source.curveType;
  23866. this.tension = source.tension;
  23867. return this;
  23868. }
  23869. toJSON() {
  23870. const data = super.toJSON();
  23871. data.points = [];
  23872. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  23873. const point = this.points[ i ];
  23874. data.points.push( point.toArray() );
  23875. }
  23876. data.closed = this.closed;
  23877. data.curveType = this.curveType;
  23878. data.tension = this.tension;
  23879. return data;
  23880. }
  23881. fromJSON( json ) {
  23882. super.fromJSON( json );
  23883. this.points = [];
  23884. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  23885. const point = json.points[ i ];
  23886. this.points.push( new Vector3().fromArray( point ) );
  23887. }
  23888. this.closed = json.closed;
  23889. this.curveType = json.curveType;
  23890. this.tension = json.tension;
  23891. return this;
  23892. }
  23893. }
  23894. // Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  23895. /**
  23896. * Computes a point on a Catmull-Rom spline.
  23897. *
  23898. * @param {number} t - The interpolation factor.
  23899. * @param {number} p0 - The first control point.
  23900. * @param {number} p1 - The second control point.
  23901. * @param {number} p2 - The third control point.
  23902. * @param {number} p3 - The fourth control point.
  23903. * @return {number} The calculated point on a Catmull-Rom spline.
  23904. */
  23905. function CatmullRom( t, p0, p1, p2, p3 ) {
  23906. const v0 = ( p2 - p0 ) * 0.5;
  23907. const v1 = ( p3 - p1 ) * 0.5;
  23908. const t2 = t * t;
  23909. const t3 = t * t2;
  23910. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23911. }
  23912. //
  23913. function QuadraticBezierP0( t, p ) {
  23914. const k = 1 - t;
  23915. return k * k * p;
  23916. }
  23917. function QuadraticBezierP1( t, p ) {
  23918. return 2 * ( 1 - t ) * t * p;
  23919. }
  23920. function QuadraticBezierP2( t, p ) {
  23921. return t * t * p;
  23922. }
  23923. /**
  23924. * Computes a point on a Quadratic Bezier curve.
  23925. *
  23926. * @param {number} t - The interpolation factor.
  23927. * @param {number} p0 - The first control point.
  23928. * @param {number} p1 - The second control point.
  23929. * @param {number} p2 - The third control point.
  23930. * @return {number} The calculated point on a Quadratic Bezier curve.
  23931. */
  23932. function QuadraticBezier( t, p0, p1, p2 ) {
  23933. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23934. QuadraticBezierP2( t, p2 );
  23935. }
  23936. //
  23937. function CubicBezierP0( t, p ) {
  23938. const k = 1 - t;
  23939. return k * k * k * p;
  23940. }
  23941. function CubicBezierP1( t, p ) {
  23942. const k = 1 - t;
  23943. return 3 * k * k * t * p;
  23944. }
  23945. function CubicBezierP2( t, p ) {
  23946. return 3 * ( 1 - t ) * t * t * p;
  23947. }
  23948. function CubicBezierP3( t, p ) {
  23949. return t * t * t * p;
  23950. }
  23951. /**
  23952. * Computes a point on a Cubic Bezier curve.
  23953. *
  23954. * @param {number} t - The interpolation factor.
  23955. * @param {number} p0 - The first control point.
  23956. * @param {number} p1 - The second control point.
  23957. * @param {number} p2 - The third control point.
  23958. * @param {number} p3 - The fourth control point.
  23959. * @return {number} The calculated point on a Cubic Bezier curve.
  23960. */
  23961. function CubicBezier( t, p0, p1, p2, p3 ) {
  23962. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23963. CubicBezierP3( t, p3 );
  23964. }
  23965. /**
  23966. * A curve representing a 2D Cubic Bezier curve.
  23967. *
  23968. * ```js
  23969. * const curve = new THREE.CubicBezierCurve(
  23970. * new THREE.Vector2( - 0, 0 ),
  23971. * new THREE.Vector2( - 5, 15 ),
  23972. * new THREE.Vector2( 20, 15 ),
  23973. * new THREE.Vector2( 10, 0 )
  23974. * );
  23975. *
  23976. * const points = curve.getPoints( 50 );
  23977. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23978. *
  23979. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23980. *
  23981. * // Create the final object to add to the scene
  23982. * const curveObject = new THREE.Line( geometry, material );
  23983. * ```
  23984. *
  23985. * @augments Curve
  23986. */
  23987. class CubicBezierCurve extends Curve {
  23988. /**
  23989. * Constructs a new Cubic Bezier curve.
  23990. *
  23991. * @param {Vector2} [v0] - The start point.
  23992. * @param {Vector2} [v1] - The first control point.
  23993. * @param {Vector2} [v2] - The second control point.
  23994. * @param {Vector2} [v3] - The end point.
  23995. */
  23996. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  23997. super();
  23998. /**
  23999. * This flag can be used for type testing.
  24000. *
  24001. * @type {boolean}
  24002. * @readonly
  24003. * @default true
  24004. */
  24005. this.isCubicBezierCurve = true;
  24006. this.type = 'CubicBezierCurve';
  24007. /**
  24008. * The start point.
  24009. *
  24010. * @type {Vector2}
  24011. */
  24012. this.v0 = v0;
  24013. /**
  24014. * The first control point.
  24015. *
  24016. * @type {Vector2}
  24017. */
  24018. this.v1 = v1;
  24019. /**
  24020. * The second control point.
  24021. *
  24022. * @type {Vector2}
  24023. */
  24024. this.v2 = v2;
  24025. /**
  24026. * The end point.
  24027. *
  24028. * @type {Vector2}
  24029. */
  24030. this.v3 = v3;
  24031. }
  24032. /**
  24033. * Returns a point on the curve.
  24034. *
  24035. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24036. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24037. * @return {Vector2} The position on the curve.
  24038. */
  24039. getPoint( t, optionalTarget = new Vector2() ) {
  24040. const point = optionalTarget;
  24041. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24042. point.set(
  24043. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24044. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24045. );
  24046. return point;
  24047. }
  24048. copy( source ) {
  24049. super.copy( source );
  24050. this.v0.copy( source.v0 );
  24051. this.v1.copy( source.v1 );
  24052. this.v2.copy( source.v2 );
  24053. this.v3.copy( source.v3 );
  24054. return this;
  24055. }
  24056. toJSON() {
  24057. const data = super.toJSON();
  24058. data.v0 = this.v0.toArray();
  24059. data.v1 = this.v1.toArray();
  24060. data.v2 = this.v2.toArray();
  24061. data.v3 = this.v3.toArray();
  24062. return data;
  24063. }
  24064. fromJSON( json ) {
  24065. super.fromJSON( json );
  24066. this.v0.fromArray( json.v0 );
  24067. this.v1.fromArray( json.v1 );
  24068. this.v2.fromArray( json.v2 );
  24069. this.v3.fromArray( json.v3 );
  24070. return this;
  24071. }
  24072. }
  24073. /**
  24074. * A curve representing a 3D Cubic Bezier curve.
  24075. *
  24076. * @augments Curve
  24077. */
  24078. class CubicBezierCurve3 extends Curve {
  24079. /**
  24080. * Constructs a new Cubic Bezier curve.
  24081. *
  24082. * @param {Vector3} [v0] - The start point.
  24083. * @param {Vector3} [v1] - The first control point.
  24084. * @param {Vector3} [v2] - The second control point.
  24085. * @param {Vector3} [v3] - The end point.
  24086. */
  24087. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24088. super();
  24089. /**
  24090. * This flag can be used for type testing.
  24091. *
  24092. * @type {boolean}
  24093. * @readonly
  24094. * @default true
  24095. */
  24096. this.isCubicBezierCurve3 = true;
  24097. this.type = 'CubicBezierCurve3';
  24098. /**
  24099. * The start point.
  24100. *
  24101. * @type {Vector3}
  24102. */
  24103. this.v0 = v0;
  24104. /**
  24105. * The first control point.
  24106. *
  24107. * @type {Vector3}
  24108. */
  24109. this.v1 = v1;
  24110. /**
  24111. * The second control point.
  24112. *
  24113. * @type {Vector3}
  24114. */
  24115. this.v2 = v2;
  24116. /**
  24117. * The end point.
  24118. *
  24119. * @type {Vector3}
  24120. */
  24121. this.v3 = v3;
  24122. }
  24123. /**
  24124. * Returns a point on the curve.
  24125. *
  24126. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24127. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24128. * @return {Vector3} The position on the curve.
  24129. */
  24130. getPoint( t, optionalTarget = new Vector3() ) {
  24131. const point = optionalTarget;
  24132. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24133. point.set(
  24134. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24135. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24136. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24137. );
  24138. return point;
  24139. }
  24140. copy( source ) {
  24141. super.copy( source );
  24142. this.v0.copy( source.v0 );
  24143. this.v1.copy( source.v1 );
  24144. this.v2.copy( source.v2 );
  24145. this.v3.copy( source.v3 );
  24146. return this;
  24147. }
  24148. toJSON() {
  24149. const data = super.toJSON();
  24150. data.v0 = this.v0.toArray();
  24151. data.v1 = this.v1.toArray();
  24152. data.v2 = this.v2.toArray();
  24153. data.v3 = this.v3.toArray();
  24154. return data;
  24155. }
  24156. fromJSON( json ) {
  24157. super.fromJSON( json );
  24158. this.v0.fromArray( json.v0 );
  24159. this.v1.fromArray( json.v1 );
  24160. this.v2.fromArray( json.v2 );
  24161. this.v3.fromArray( json.v3 );
  24162. return this;
  24163. }
  24164. }
  24165. /**
  24166. * A curve representing a 2D line segment.
  24167. *
  24168. * @augments Curve
  24169. */
  24170. class LineCurve extends Curve {
  24171. /**
  24172. * Constructs a new line curve.
  24173. *
  24174. * @param {Vector2} [v1] - The start point.
  24175. * @param {Vector2} [v2] - The end point.
  24176. */
  24177. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24178. super();
  24179. /**
  24180. * This flag can be used for type testing.
  24181. *
  24182. * @type {boolean}
  24183. * @readonly
  24184. * @default true
  24185. */
  24186. this.isLineCurve = true;
  24187. this.type = 'LineCurve';
  24188. /**
  24189. * The start point.
  24190. *
  24191. * @type {Vector2}
  24192. */
  24193. this.v1 = v1;
  24194. /**
  24195. * The end point.
  24196. *
  24197. * @type {Vector2}
  24198. */
  24199. this.v2 = v2;
  24200. }
  24201. /**
  24202. * Returns a point on the line.
  24203. *
  24204. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24205. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24206. * @return {Vector2} The position on the line.
  24207. */
  24208. getPoint( t, optionalTarget = new Vector2() ) {
  24209. const point = optionalTarget;
  24210. if ( t === 1 ) {
  24211. point.copy( this.v2 );
  24212. } else {
  24213. point.copy( this.v2 ).sub( this.v1 );
  24214. point.multiplyScalar( t ).add( this.v1 );
  24215. }
  24216. return point;
  24217. }
  24218. // Line curve is linear, so we can overwrite default getPointAt
  24219. getPointAt( u, optionalTarget ) {
  24220. return this.getPoint( u, optionalTarget );
  24221. }
  24222. getTangent( t, optionalTarget = new Vector2() ) {
  24223. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24224. }
  24225. getTangentAt( u, optionalTarget ) {
  24226. return this.getTangent( u, optionalTarget );
  24227. }
  24228. copy( source ) {
  24229. super.copy( source );
  24230. this.v1.copy( source.v1 );
  24231. this.v2.copy( source.v2 );
  24232. return this;
  24233. }
  24234. toJSON() {
  24235. const data = super.toJSON();
  24236. data.v1 = this.v1.toArray();
  24237. data.v2 = this.v2.toArray();
  24238. return data;
  24239. }
  24240. fromJSON( json ) {
  24241. super.fromJSON( json );
  24242. this.v1.fromArray( json.v1 );
  24243. this.v2.fromArray( json.v2 );
  24244. return this;
  24245. }
  24246. }
  24247. /**
  24248. * A curve representing a 3D line segment.
  24249. *
  24250. * @augments Curve
  24251. */
  24252. class LineCurve3 extends Curve {
  24253. /**
  24254. * Constructs a new line curve.
  24255. *
  24256. * @param {Vector3} [v1] - The start point.
  24257. * @param {Vector3} [v2] - The end point.
  24258. */
  24259. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24260. super();
  24261. /**
  24262. * This flag can be used for type testing.
  24263. *
  24264. * @type {boolean}
  24265. * @readonly
  24266. * @default true
  24267. */
  24268. this.isLineCurve3 = true;
  24269. this.type = 'LineCurve3';
  24270. /**
  24271. * The start point.
  24272. *
  24273. * @type {Vector3}
  24274. */
  24275. this.v1 = v1;
  24276. /**
  24277. * The end point.
  24278. *
  24279. * @type {Vector2}
  24280. */
  24281. this.v2 = v2;
  24282. }
  24283. /**
  24284. * Returns a point on the line.
  24285. *
  24286. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24287. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24288. * @return {Vector3} The position on the line.
  24289. */
  24290. getPoint( t, optionalTarget = new Vector3() ) {
  24291. const point = optionalTarget;
  24292. if ( t === 1 ) {
  24293. point.copy( this.v2 );
  24294. } else {
  24295. point.copy( this.v2 ).sub( this.v1 );
  24296. point.multiplyScalar( t ).add( this.v1 );
  24297. }
  24298. return point;
  24299. }
  24300. // Line curve is linear, so we can overwrite default getPointAt
  24301. getPointAt( u, optionalTarget ) {
  24302. return this.getPoint( u, optionalTarget );
  24303. }
  24304. getTangent( t, optionalTarget = new Vector3() ) {
  24305. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24306. }
  24307. getTangentAt( u, optionalTarget ) {
  24308. return this.getTangent( u, optionalTarget );
  24309. }
  24310. copy( source ) {
  24311. super.copy( source );
  24312. this.v1.copy( source.v1 );
  24313. this.v2.copy( source.v2 );
  24314. return this;
  24315. }
  24316. toJSON() {
  24317. const data = super.toJSON();
  24318. data.v1 = this.v1.toArray();
  24319. data.v2 = this.v2.toArray();
  24320. return data;
  24321. }
  24322. fromJSON( json ) {
  24323. super.fromJSON( json );
  24324. this.v1.fromArray( json.v1 );
  24325. this.v2.fromArray( json.v2 );
  24326. return this;
  24327. }
  24328. }
  24329. /**
  24330. * A curve representing a 2D Quadratic Bezier curve.
  24331. *
  24332. * ```js
  24333. * const curve = new THREE.QuadraticBezierCurve(
  24334. * new THREE.Vector2( - 10, 0 ),
  24335. * new THREE.Vector2( 20, 15 ),
  24336. * new THREE.Vector2( 10, 0 )
  24337. * )
  24338. *
  24339. * const points = curve.getPoints( 50 );
  24340. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24341. *
  24342. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24343. *
  24344. * // Create the final object to add to the scene
  24345. * const curveObject = new THREE.Line( geometry, material );
  24346. * ```
  24347. *
  24348. * @augments Curve
  24349. */
  24350. class QuadraticBezierCurve extends Curve {
  24351. /**
  24352. * Constructs a new Quadratic Bezier curve.
  24353. *
  24354. * @param {Vector2} [v0] - The start point.
  24355. * @param {Vector2} [v1] - The control point.
  24356. * @param {Vector2} [v2] - The end point.
  24357. */
  24358. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24359. super();
  24360. /**
  24361. * This flag can be used for type testing.
  24362. *
  24363. * @type {boolean}
  24364. * @readonly
  24365. * @default true
  24366. */
  24367. this.isQuadraticBezierCurve = true;
  24368. this.type = 'QuadraticBezierCurve';
  24369. /**
  24370. * The start point.
  24371. *
  24372. * @type {Vector2}
  24373. */
  24374. this.v0 = v0;
  24375. /**
  24376. * The control point.
  24377. *
  24378. * @type {Vector2}
  24379. */
  24380. this.v1 = v1;
  24381. /**
  24382. * The end point.
  24383. *
  24384. * @type {Vector2}
  24385. */
  24386. this.v2 = v2;
  24387. }
  24388. /**
  24389. * Returns a point on the curve.
  24390. *
  24391. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24392. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24393. * @return {Vector2} The position on the curve.
  24394. */
  24395. getPoint( t, optionalTarget = new Vector2() ) {
  24396. const point = optionalTarget;
  24397. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24398. point.set(
  24399. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24400. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24401. );
  24402. return point;
  24403. }
  24404. copy( source ) {
  24405. super.copy( source );
  24406. this.v0.copy( source.v0 );
  24407. this.v1.copy( source.v1 );
  24408. this.v2.copy( source.v2 );
  24409. return this;
  24410. }
  24411. toJSON() {
  24412. const data = super.toJSON();
  24413. data.v0 = this.v0.toArray();
  24414. data.v1 = this.v1.toArray();
  24415. data.v2 = this.v2.toArray();
  24416. return data;
  24417. }
  24418. fromJSON( json ) {
  24419. super.fromJSON( json );
  24420. this.v0.fromArray( json.v0 );
  24421. this.v1.fromArray( json.v1 );
  24422. this.v2.fromArray( json.v2 );
  24423. return this;
  24424. }
  24425. }
  24426. /**
  24427. * A curve representing a 3D Quadratic Bezier curve.
  24428. *
  24429. * @augments Curve
  24430. */
  24431. class QuadraticBezierCurve3 extends Curve {
  24432. /**
  24433. * Constructs a new Quadratic Bezier curve.
  24434. *
  24435. * @param {Vector3} [v0] - The start point.
  24436. * @param {Vector3} [v1] - The control point.
  24437. * @param {Vector3} [v2] - The end point.
  24438. */
  24439. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24440. super();
  24441. /**
  24442. * This flag can be used for type testing.
  24443. *
  24444. * @type {boolean}
  24445. * @readonly
  24446. * @default true
  24447. */
  24448. this.isQuadraticBezierCurve3 = true;
  24449. this.type = 'QuadraticBezierCurve3';
  24450. /**
  24451. * The start point.
  24452. *
  24453. * @type {Vector3}
  24454. */
  24455. this.v0 = v0;
  24456. /**
  24457. * The control point.
  24458. *
  24459. * @type {Vector3}
  24460. */
  24461. this.v1 = v1;
  24462. /**
  24463. * The end point.
  24464. *
  24465. * @type {Vector3}
  24466. */
  24467. this.v2 = v2;
  24468. }
  24469. /**
  24470. * Returns a point on the curve.
  24471. *
  24472. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24473. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24474. * @return {Vector3} The position on the curve.
  24475. */
  24476. getPoint( t, optionalTarget = new Vector3() ) {
  24477. const point = optionalTarget;
  24478. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24479. point.set(
  24480. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24481. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24482. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24483. );
  24484. return point;
  24485. }
  24486. copy( source ) {
  24487. super.copy( source );
  24488. this.v0.copy( source.v0 );
  24489. this.v1.copy( source.v1 );
  24490. this.v2.copy( source.v2 );
  24491. return this;
  24492. }
  24493. toJSON() {
  24494. const data = super.toJSON();
  24495. data.v0 = this.v0.toArray();
  24496. data.v1 = this.v1.toArray();
  24497. data.v2 = this.v2.toArray();
  24498. return data;
  24499. }
  24500. fromJSON( json ) {
  24501. super.fromJSON( json );
  24502. this.v0.fromArray( json.v0 );
  24503. this.v1.fromArray( json.v1 );
  24504. this.v2.fromArray( json.v2 );
  24505. return this;
  24506. }
  24507. }
  24508. /**
  24509. * A curve representing a 2D spline curve.
  24510. *
  24511. * ```js
  24512. * // Create a sine-like wave
  24513. * const curve = new THREE.SplineCurve( [
  24514. * new THREE.Vector2( -10, 0 ),
  24515. * new THREE.Vector2( -5, 5 ),
  24516. * new THREE.Vector2( 0, 0 ),
  24517. * new THREE.Vector2( 5, -5 ),
  24518. * new THREE.Vector2( 10, 0 )
  24519. * ] );
  24520. *
  24521. * const points = curve.getPoints( 50 );
  24522. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24523. *
  24524. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24525. *
  24526. * // Create the final object to add to the scene
  24527. * const splineObject = new THREE.Line( geometry, material );
  24528. * ```
  24529. *
  24530. * @augments Curve
  24531. */
  24532. class SplineCurve extends Curve {
  24533. /**
  24534. * Constructs a new 2D spline curve.
  24535. *
  24536. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24537. */
  24538. constructor( points = [] ) {
  24539. super();
  24540. /**
  24541. * This flag can be used for type testing.
  24542. *
  24543. * @type {boolean}
  24544. * @readonly
  24545. * @default true
  24546. */
  24547. this.isSplineCurve = true;
  24548. this.type = 'SplineCurve';
  24549. /**
  24550. * An array of 2D points defining the curve.
  24551. *
  24552. * @type {Array<Vector2>}
  24553. */
  24554. this.points = points;
  24555. }
  24556. /**
  24557. * Returns a point on the curve.
  24558. *
  24559. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24560. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24561. * @return {Vector2} The position on the curve.
  24562. */
  24563. getPoint( t, optionalTarget = new Vector2() ) {
  24564. const point = optionalTarget;
  24565. const points = this.points;
  24566. const p = ( points.length - 1 ) * t;
  24567. const intPoint = Math.floor( p );
  24568. const weight = p - intPoint;
  24569. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24570. const p1 = points[ intPoint ];
  24571. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24572. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24573. point.set(
  24574. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24575. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24576. );
  24577. return point;
  24578. }
  24579. copy( source ) {
  24580. super.copy( source );
  24581. this.points = [];
  24582. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24583. const point = source.points[ i ];
  24584. this.points.push( point.clone() );
  24585. }
  24586. return this;
  24587. }
  24588. toJSON() {
  24589. const data = super.toJSON();
  24590. data.points = [];
  24591. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24592. const point = this.points[ i ];
  24593. data.points.push( point.toArray() );
  24594. }
  24595. return data;
  24596. }
  24597. fromJSON( json ) {
  24598. super.fromJSON( json );
  24599. this.points = [];
  24600. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24601. const point = json.points[ i ];
  24602. this.points.push( new Vector2().fromArray( point ) );
  24603. }
  24604. return this;
  24605. }
  24606. }
  24607. var Curves = /*#__PURE__*/Object.freeze({
  24608. __proto__: null,
  24609. ArcCurve: ArcCurve,
  24610. CatmullRomCurve3: CatmullRomCurve3,
  24611. CubicBezierCurve: CubicBezierCurve,
  24612. CubicBezierCurve3: CubicBezierCurve3,
  24613. EllipseCurve: EllipseCurve,
  24614. LineCurve: LineCurve,
  24615. LineCurve3: LineCurve3,
  24616. QuadraticBezierCurve: QuadraticBezierCurve,
  24617. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24618. SplineCurve: SplineCurve
  24619. });
  24620. /**
  24621. * A base class extending {@link Curve}. `CurvePath` is simply an
  24622. * array of connected curves, but retains the API of a curve.
  24623. *
  24624. * @augments Curve
  24625. */
  24626. class CurvePath extends Curve {
  24627. /**
  24628. * Constructs a new curve path.
  24629. */
  24630. constructor() {
  24631. super();
  24632. this.type = 'CurvePath';
  24633. /**
  24634. * An array of curves defining the
  24635. * path.
  24636. *
  24637. * @type {Array<Curve>}
  24638. */
  24639. this.curves = [];
  24640. /**
  24641. * Whether the path should automatically be closed
  24642. * by a line curve.
  24643. *
  24644. * @type {boolean}
  24645. * @default false
  24646. */
  24647. this.autoClose = false;
  24648. }
  24649. /**
  24650. * Adds a curve to this curve path.
  24651. *
  24652. * @param {Curve} curve - The curve to add.
  24653. */
  24654. add( curve ) {
  24655. this.curves.push( curve );
  24656. }
  24657. /**
  24658. * Adds a line curve to close the path.
  24659. *
  24660. * @return {CurvePath} A reference to this curve path.
  24661. */
  24662. closePath() {
  24663. // Add a line curve if start and end of lines are not connected
  24664. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24665. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24666. if ( ! startPoint.equals( endPoint ) ) {
  24667. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24668. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24669. }
  24670. return this;
  24671. }
  24672. /**
  24673. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24674. * for the given interpolation factor.
  24675. *
  24676. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24677. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24678. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24679. */
  24680. getPoint( t, optionalTarget ) {
  24681. // To get accurate point with reference to
  24682. // entire path distance at time t,
  24683. // following has to be done:
  24684. // 1. Length of each sub path have to be known
  24685. // 2. Locate and identify type of curve
  24686. // 3. Get t for the curve
  24687. // 4. Return curve.getPointAt(t')
  24688. const d = t * this.getLength();
  24689. const curveLengths = this.getCurveLengths();
  24690. let i = 0;
  24691. // To think about boundaries points.
  24692. while ( i < curveLengths.length ) {
  24693. if ( curveLengths[ i ] >= d ) {
  24694. const diff = curveLengths[ i ] - d;
  24695. const curve = this.curves[ i ];
  24696. const segmentLength = curve.getLength();
  24697. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24698. return curve.getPointAt( u, optionalTarget );
  24699. }
  24700. i ++;
  24701. }
  24702. return null;
  24703. // loop where sum != 0, sum > d , sum+1 <d
  24704. }
  24705. getLength() {
  24706. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24707. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24708. // getPoint() depends on getLength
  24709. const lens = this.getCurveLengths();
  24710. return lens[ lens.length - 1 ];
  24711. }
  24712. updateArcLengths() {
  24713. // cacheLengths must be recalculated.
  24714. this.needsUpdate = true;
  24715. this.cacheLengths = null;
  24716. this.getCurveLengths();
  24717. }
  24718. /**
  24719. * Returns list of cumulative curve lengths of the defined curves.
  24720. *
  24721. * @return {Array<number>} The curve lengths.
  24722. */
  24723. getCurveLengths() {
  24724. // Compute lengths and cache them
  24725. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24726. // We use cache values if curves and cache array are same length
  24727. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24728. return this.cacheLengths;
  24729. }
  24730. // Get length of sub-curve
  24731. // Push sums into cached array
  24732. const lengths = [];
  24733. let sums = 0;
  24734. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24735. sums += this.curves[ i ].getLength();
  24736. lengths.push( sums );
  24737. }
  24738. this.cacheLengths = lengths;
  24739. return lengths;
  24740. }
  24741. getSpacedPoints( divisions = 40 ) {
  24742. const points = [];
  24743. for ( let i = 0; i <= divisions; i ++ ) {
  24744. points.push( this.getPoint( i / divisions ) );
  24745. }
  24746. if ( this.autoClose ) {
  24747. points.push( points[ 0 ] );
  24748. }
  24749. return points;
  24750. }
  24751. getPoints( divisions = 12 ) {
  24752. const points = [];
  24753. let last;
  24754. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24755. const curve = curves[ i ];
  24756. const resolution = curve.isEllipseCurve ? divisions * 2
  24757. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24758. : curve.isSplineCurve ? divisions * curve.points.length
  24759. : divisions;
  24760. const pts = curve.getPoints( resolution );
  24761. for ( let j = 0; j < pts.length; j ++ ) {
  24762. const point = pts[ j ];
  24763. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24764. points.push( point );
  24765. last = point;
  24766. }
  24767. }
  24768. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24769. points.push( points[ 0 ] );
  24770. }
  24771. return points;
  24772. }
  24773. copy( source ) {
  24774. super.copy( source );
  24775. this.curves = [];
  24776. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24777. const curve = source.curves[ i ];
  24778. this.curves.push( curve.clone() );
  24779. }
  24780. this.autoClose = source.autoClose;
  24781. return this;
  24782. }
  24783. toJSON() {
  24784. const data = super.toJSON();
  24785. data.autoClose = this.autoClose;
  24786. data.curves = [];
  24787. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24788. const curve = this.curves[ i ];
  24789. data.curves.push( curve.toJSON() );
  24790. }
  24791. return data;
  24792. }
  24793. fromJSON( json ) {
  24794. super.fromJSON( json );
  24795. this.autoClose = json.autoClose;
  24796. this.curves = [];
  24797. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24798. const curve = json.curves[ i ];
  24799. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24800. }
  24801. return this;
  24802. }
  24803. }
  24804. /**
  24805. * A 2D path representation. The class provides methods for creating paths
  24806. * and contours of 2D shapes similar to the 2D Canvas API.
  24807. *
  24808. * ```js
  24809. * const path = new THREE.Path();
  24810. *
  24811. * path.lineTo( 0, 0.8 );
  24812. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24813. * path.lineTo( 1, 1 );
  24814. *
  24815. * const points = path.getPoints();
  24816. *
  24817. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24818. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24819. *
  24820. * const line = new THREE.Line( geometry, material );
  24821. * scene.add( line );
  24822. * ```
  24823. *
  24824. * @augments CurvePath
  24825. */
  24826. class Path extends CurvePath {
  24827. /**
  24828. * Constructs a new path.
  24829. *
  24830. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24831. */
  24832. constructor( points ) {
  24833. super();
  24834. this.type = 'Path';
  24835. /**
  24836. * The current offset of the path. Any new curve added will start here.
  24837. *
  24838. * @type {Vector2}
  24839. */
  24840. this.currentPoint = new Vector2();
  24841. if ( points ) {
  24842. this.setFromPoints( points );
  24843. }
  24844. }
  24845. /**
  24846. * Creates a path from the given list of points. The points are added
  24847. * to the path as instances of {@link LineCurve}.
  24848. *
  24849. * @param {Array<Vector2>} points - An array of 2D points.
  24850. * @return {Path} A reference to this path.
  24851. */
  24852. setFromPoints( points ) {
  24853. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24854. for ( let i = 1, l = points.length; i < l; i ++ ) {
  24855. this.lineTo( points[ i ].x, points[ i ].y );
  24856. }
  24857. return this;
  24858. }
  24859. /**
  24860. * Moves {@link Path#currentPoint} to the given point.
  24861. *
  24862. * @param {number} x - The x coordinate.
  24863. * @param {number} y - The y coordinate.
  24864. * @return {Path} A reference to this path.
  24865. */
  24866. moveTo( x, y ) {
  24867. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24868. return this;
  24869. }
  24870. /**
  24871. * Adds an instance of {@link LineCurve} to the path by connecting
  24872. * the current point with the given one.
  24873. *
  24874. * @param {number} x - The x coordinate of the end point.
  24875. * @param {number} y - The y coordinate of the end point.
  24876. * @return {Path} A reference to this path.
  24877. */
  24878. lineTo( x, y ) {
  24879. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24880. this.curves.push( curve );
  24881. this.currentPoint.set( x, y );
  24882. return this;
  24883. }
  24884. /**
  24885. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  24886. * the current point with the given one.
  24887. *
  24888. * @param {number} aCPx - The x coordinate of the control point.
  24889. * @param {number} aCPy - The y coordinate of the control point.
  24890. * @param {number} aX - The x coordinate of the end point.
  24891. * @param {number} aY - The y coordinate of the end point.
  24892. * @return {Path} A reference to this path.
  24893. */
  24894. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  24895. const curve = new QuadraticBezierCurve(
  24896. this.currentPoint.clone(),
  24897. new Vector2( aCPx, aCPy ),
  24898. new Vector2( aX, aY )
  24899. );
  24900. this.curves.push( curve );
  24901. this.currentPoint.set( aX, aY );
  24902. return this;
  24903. }
  24904. /**
  24905. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  24906. * the current point with the given one.
  24907. *
  24908. * @param {number} aCP1x - The x coordinate of the first control point.
  24909. * @param {number} aCP1y - The y coordinate of the first control point.
  24910. * @param {number} aCP2x - The x coordinate of the second control point.
  24911. * @param {number} aCP2y - The y coordinate of the second control point.
  24912. * @param {number} aX - The x coordinate of the end point.
  24913. * @param {number} aY - The y coordinate of the end point.
  24914. * @return {Path} A reference to this path.
  24915. */
  24916. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24917. const curve = new CubicBezierCurve(
  24918. this.currentPoint.clone(),
  24919. new Vector2( aCP1x, aCP1y ),
  24920. new Vector2( aCP2x, aCP2y ),
  24921. new Vector2( aX, aY )
  24922. );
  24923. this.curves.push( curve );
  24924. this.currentPoint.set( aX, aY );
  24925. return this;
  24926. }
  24927. /**
  24928. * Adds an instance of {@link SplineCurve} to the path by connecting
  24929. * the current point with the given list of points.
  24930. *
  24931. * @param {Array<Vector2>} pts - An array of points in 2D space.
  24932. * @return {Path} A reference to this path.
  24933. */
  24934. splineThru( pts ) {
  24935. const npts = [ this.currentPoint.clone() ].concat( pts );
  24936. const curve = new SplineCurve( npts );
  24937. this.curves.push( curve );
  24938. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24939. return this;
  24940. }
  24941. /**
  24942. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  24943. * to the current point.
  24944. *
  24945. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  24946. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  24947. * @param {number} [aRadius=1] - The radius of the arc.
  24948. * @param {number} [aStartAngle=0] - The start angle in radians.
  24949. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24950. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24951. * @return {Path} A reference to this path.
  24952. */
  24953. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24954. const x0 = this.currentPoint.x;
  24955. const y0 = this.currentPoint.y;
  24956. this.absarc( aX + x0, aY + y0, aRadius,
  24957. aStartAngle, aEndAngle, aClockwise );
  24958. return this;
  24959. }
  24960. /**
  24961. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  24962. *
  24963. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  24964. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  24965. * @param {number} [aRadius=1] - The radius of the arc.
  24966. * @param {number} [aStartAngle=0] - The start angle in radians.
  24967. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24968. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  24969. * @return {Path} A reference to this path.
  24970. */
  24971. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24972. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24973. return this;
  24974. }
  24975. /**
  24976. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  24977. * to the current point
  24978. *
  24979. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  24980. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  24981. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  24982. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  24983. * @param {number} [aStartAngle=0] - The start angle in radians.
  24984. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  24985. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  24986. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  24987. * @return {Path} A reference to this path.
  24988. */
  24989. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24990. const x0 = this.currentPoint.x;
  24991. const y0 = this.currentPoint.y;
  24992. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24993. return this;
  24994. }
  24995. /**
  24996. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  24997. *
  24998. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  24999. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25000. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25001. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25002. * @param {number} [aStartAngle=0] - The start angle in radians.
  25003. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25004. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25005. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25006. * @return {Path} A reference to this path.
  25007. */
  25008. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25009. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25010. if ( this.curves.length > 0 ) {
  25011. // if a previous curve is present, attempt to join
  25012. const firstPoint = curve.getPoint( 0 );
  25013. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25014. this.lineTo( firstPoint.x, firstPoint.y );
  25015. }
  25016. }
  25017. this.curves.push( curve );
  25018. const lastPoint = curve.getPoint( 1 );
  25019. this.currentPoint.copy( lastPoint );
  25020. return this;
  25021. }
  25022. copy( source ) {
  25023. super.copy( source );
  25024. this.currentPoint.copy( source.currentPoint );
  25025. return this;
  25026. }
  25027. toJSON() {
  25028. const data = super.toJSON();
  25029. data.currentPoint = this.currentPoint.toArray();
  25030. return data;
  25031. }
  25032. fromJSON( json ) {
  25033. super.fromJSON( json );
  25034. this.currentPoint.fromArray( json.currentPoint );
  25035. return this;
  25036. }
  25037. }
  25038. /**
  25039. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25040. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25041. * points, or to get triangulated faces.
  25042. *
  25043. * ```js
  25044. * const heartShape = new THREE.Shape();
  25045. *
  25046. * heartShape.moveTo( 25, 25 );
  25047. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25048. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25049. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25050. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25051. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25052. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25053. *
  25054. * const extrudeSettings = {
  25055. * depth: 8,
  25056. * bevelEnabled: true,
  25057. * bevelSegments: 2,
  25058. * steps: 2,
  25059. * bevelSize: 1,
  25060. * bevelThickness: 1
  25061. * };
  25062. *
  25063. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25064. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25065. * ```
  25066. *
  25067. * @augments Path
  25068. */
  25069. class Shape extends Path {
  25070. /**
  25071. * Constructs a new shape.
  25072. *
  25073. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25074. */
  25075. constructor( points ) {
  25076. super( points );
  25077. /**
  25078. * The UUID of the shape.
  25079. *
  25080. * @type {string}
  25081. * @readonly
  25082. */
  25083. this.uuid = generateUUID();
  25084. this.type = 'Shape';
  25085. /**
  25086. * Defines the holes in the shape. Hole definitions must use the
  25087. * opposite winding order (CW/CCW) than the outer shape.
  25088. *
  25089. * @type {Array<Path>}
  25090. * @readonly
  25091. */
  25092. this.holes = [];
  25093. }
  25094. /**
  25095. * Returns an array representing each contour of the holes
  25096. * as a list of 2D points.
  25097. *
  25098. * @param {number} divisions - The fineness of the result.
  25099. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25100. */
  25101. getPointsHoles( divisions ) {
  25102. const holesPts = [];
  25103. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25104. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25105. }
  25106. return holesPts;
  25107. }
  25108. // get points of shape and holes (keypoints based on segments parameter)
  25109. /**
  25110. * Returns an object that holds contour data for the shape and its holes as
  25111. * arrays of 2D points.
  25112. *
  25113. * @param {number} divisions - The fineness of the result.
  25114. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25115. */
  25116. extractPoints( divisions ) {
  25117. return {
  25118. shape: this.getPoints( divisions ),
  25119. holes: this.getPointsHoles( divisions )
  25120. };
  25121. }
  25122. copy( source ) {
  25123. super.copy( source );
  25124. this.holes = [];
  25125. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25126. const hole = source.holes[ i ];
  25127. this.holes.push( hole.clone() );
  25128. }
  25129. return this;
  25130. }
  25131. toJSON() {
  25132. const data = super.toJSON();
  25133. data.uuid = this.uuid;
  25134. data.holes = [];
  25135. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25136. const hole = this.holes[ i ];
  25137. data.holes.push( hole.toJSON() );
  25138. }
  25139. return data;
  25140. }
  25141. fromJSON( json ) {
  25142. super.fromJSON( json );
  25143. this.uuid = json.uuid;
  25144. this.holes = [];
  25145. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25146. const hole = json.holes[ i ];
  25147. this.holes.push( new Path().fromJSON( hole ) );
  25148. }
  25149. return this;
  25150. }
  25151. }
  25152. /* eslint-disable */
  25153. // copy of mapbox/earcut version 3.0.1
  25154. // https://github.com/mapbox/earcut/tree/v3.0.1
  25155. function earcut(data, holeIndices, dim = 2) {
  25156. const hasHoles = holeIndices && holeIndices.length;
  25157. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25158. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25159. const triangles = [];
  25160. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25161. let minX, minY, invSize;
  25162. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25163. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25164. if (data.length > 80 * dim) {
  25165. minX = Infinity;
  25166. minY = Infinity;
  25167. let maxX = -Infinity;
  25168. let maxY = -Infinity;
  25169. for (let i = dim; i < outerLen; i += dim) {
  25170. const x = data[i];
  25171. const y = data[i + 1];
  25172. if (x < minX) minX = x;
  25173. if (y < minY) minY = y;
  25174. if (x > maxX) maxX = x;
  25175. if (y > maxY) maxY = y;
  25176. }
  25177. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25178. invSize = Math.max(maxX - minX, maxY - minY);
  25179. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25180. }
  25181. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25182. return triangles;
  25183. }
  25184. // create a circular doubly linked list from polygon points in the specified winding order
  25185. function linkedList(data, start, end, dim, clockwise) {
  25186. let last;
  25187. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25188. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25189. } else {
  25190. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25191. }
  25192. if (last && equals(last, last.next)) {
  25193. removeNode(last);
  25194. last = last.next;
  25195. }
  25196. return last;
  25197. }
  25198. // eliminate colinear or duplicate points
  25199. function filterPoints(start, end) {
  25200. if (!start) return start;
  25201. if (!end) end = start;
  25202. let p = start,
  25203. again;
  25204. do {
  25205. again = false;
  25206. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25207. removeNode(p);
  25208. p = end = p.prev;
  25209. if (p === p.next) break;
  25210. again = true;
  25211. } else {
  25212. p = p.next;
  25213. }
  25214. } while (again || p !== end);
  25215. return end;
  25216. }
  25217. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25218. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25219. if (!ear) return;
  25220. // interlink polygon nodes in z-order
  25221. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25222. let stop = ear;
  25223. // iterate through ears, slicing them one by one
  25224. while (ear.prev !== ear.next) {
  25225. const prev = ear.prev;
  25226. const next = ear.next;
  25227. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25228. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25229. removeNode(ear);
  25230. // skipping the next vertex leads to less sliver triangles
  25231. ear = next.next;
  25232. stop = next.next;
  25233. continue;
  25234. }
  25235. ear = next;
  25236. // if we looped through the whole remaining polygon and can't find any more ears
  25237. if (ear === stop) {
  25238. // try filtering points and slicing again
  25239. if (!pass) {
  25240. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25241. // if this didn't work, try curing all small self-intersections locally
  25242. } else if (pass === 1) {
  25243. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25244. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25245. // as a last resort, try splitting the remaining polygon into two
  25246. } else if (pass === 2) {
  25247. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25248. }
  25249. break;
  25250. }
  25251. }
  25252. }
  25253. // check whether a polygon node forms a valid ear with adjacent nodes
  25254. function isEar(ear) {
  25255. const a = ear.prev,
  25256. b = ear,
  25257. c = ear.next;
  25258. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25259. // now make sure we don't have other points inside the potential ear
  25260. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25261. // triangle bbox
  25262. const x0 = Math.min(ax, bx, cx),
  25263. y0 = Math.min(ay, by, cy),
  25264. x1 = Math.max(ax, bx, cx),
  25265. y1 = Math.max(ay, by, cy);
  25266. let p = c.next;
  25267. while (p !== a) {
  25268. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25269. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25270. area(p.prev, p, p.next) >= 0) return false;
  25271. p = p.next;
  25272. }
  25273. return true;
  25274. }
  25275. function isEarHashed(ear, minX, minY, invSize) {
  25276. const a = ear.prev,
  25277. b = ear,
  25278. c = ear.next;
  25279. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25280. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25281. // triangle bbox
  25282. const x0 = Math.min(ax, bx, cx),
  25283. y0 = Math.min(ay, by, cy),
  25284. x1 = Math.max(ax, bx, cx),
  25285. y1 = Math.max(ay, by, cy);
  25286. // z-order range for the current triangle bbox;
  25287. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25288. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25289. let p = ear.prevZ,
  25290. n = ear.nextZ;
  25291. // look for points inside the triangle in both directions
  25292. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25293. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25294. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25295. p = p.prevZ;
  25296. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25297. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25298. n = n.nextZ;
  25299. }
  25300. // look for remaining points in decreasing z-order
  25301. while (p && p.z >= minZ) {
  25302. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25303. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25304. p = p.prevZ;
  25305. }
  25306. // look for remaining points in increasing z-order
  25307. while (n && n.z <= maxZ) {
  25308. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25309. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25310. n = n.nextZ;
  25311. }
  25312. return true;
  25313. }
  25314. // go through all polygon nodes and cure small local self-intersections
  25315. function cureLocalIntersections(start, triangles) {
  25316. let p = start;
  25317. do {
  25318. const a = p.prev,
  25319. b = p.next.next;
  25320. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25321. triangles.push(a.i, p.i, b.i);
  25322. // remove two nodes involved
  25323. removeNode(p);
  25324. removeNode(p.next);
  25325. p = start = b;
  25326. }
  25327. p = p.next;
  25328. } while (p !== start);
  25329. return filterPoints(p);
  25330. }
  25331. // try splitting polygon into two and triangulate them independently
  25332. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25333. // look for a valid diagonal that divides the polygon into two
  25334. let a = start;
  25335. do {
  25336. let b = a.next.next;
  25337. while (b !== a.prev) {
  25338. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25339. // split the polygon in two by the diagonal
  25340. let c = splitPolygon(a, b);
  25341. // filter colinear points around the cuts
  25342. a = filterPoints(a, a.next);
  25343. c = filterPoints(c, c.next);
  25344. // run earcut on each half
  25345. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25346. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25347. return;
  25348. }
  25349. b = b.next;
  25350. }
  25351. a = a.next;
  25352. } while (a !== start);
  25353. }
  25354. // link every hole into the outer loop, producing a single-ring polygon without holes
  25355. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25356. const queue = [];
  25357. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25358. const start = holeIndices[i] * dim;
  25359. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25360. const list = linkedList(data, start, end, dim, false);
  25361. if (list === list.next) list.steiner = true;
  25362. queue.push(getLeftmost(list));
  25363. }
  25364. queue.sort(compareXYSlope);
  25365. // process holes from left to right
  25366. for (let i = 0; i < queue.length; i++) {
  25367. outerNode = eliminateHole(queue[i], outerNode);
  25368. }
  25369. return outerNode;
  25370. }
  25371. function compareXYSlope(a, b) {
  25372. let result = a.x - b.x;
  25373. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25374. // the bridge to the outer shell is always the point that they meet at.
  25375. if (result === 0) {
  25376. result = a.y - b.y;
  25377. if (result === 0) {
  25378. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25379. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25380. result = aSlope - bSlope;
  25381. }
  25382. }
  25383. return result;
  25384. }
  25385. // find a bridge between vertices that connects hole with an outer ring and and link it
  25386. function eliminateHole(hole, outerNode) {
  25387. const bridge = findHoleBridge(hole, outerNode);
  25388. if (!bridge) {
  25389. return outerNode;
  25390. }
  25391. const bridgeReverse = splitPolygon(bridge, hole);
  25392. // filter collinear points around the cuts
  25393. filterPoints(bridgeReverse, bridgeReverse.next);
  25394. return filterPoints(bridge, bridge.next);
  25395. }
  25396. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25397. function findHoleBridge(hole, outerNode) {
  25398. let p = outerNode;
  25399. const hx = hole.x;
  25400. const hy = hole.y;
  25401. let qx = -Infinity;
  25402. let m;
  25403. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25404. // segment's endpoint with lesser x will be potential connection point
  25405. // unless they intersect at a vertex, then choose the vertex
  25406. if (equals(hole, p)) return p;
  25407. do {
  25408. if (equals(hole, p.next)) return p.next;
  25409. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25410. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25411. if (x <= hx && x > qx) {
  25412. qx = x;
  25413. m = p.x < p.next.x ? p : p.next;
  25414. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25415. }
  25416. }
  25417. p = p.next;
  25418. } while (p !== outerNode);
  25419. if (!m) return null;
  25420. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25421. // if there are no points found, we have a valid connection;
  25422. // otherwise choose the point of the minimum angle with the ray as connection point
  25423. const stop = m;
  25424. const mx = m.x;
  25425. const my = m.y;
  25426. let tanMin = Infinity;
  25427. p = m;
  25428. do {
  25429. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25430. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25431. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25432. if (locallyInside(p, hole) &&
  25433. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25434. m = p;
  25435. tanMin = tan;
  25436. }
  25437. }
  25438. p = p.next;
  25439. } while (p !== stop);
  25440. return m;
  25441. }
  25442. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25443. function sectorContainsSector(m, p) {
  25444. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25445. }
  25446. // interlink polygon nodes in z-order
  25447. function indexCurve(start, minX, minY, invSize) {
  25448. let p = start;
  25449. do {
  25450. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25451. p.prevZ = p.prev;
  25452. p.nextZ = p.next;
  25453. p = p.next;
  25454. } while (p !== start);
  25455. p.prevZ.nextZ = null;
  25456. p.prevZ = null;
  25457. sortLinked(p);
  25458. }
  25459. // Simon Tatham's linked list merge sort algorithm
  25460. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25461. function sortLinked(list) {
  25462. let numMerges;
  25463. let inSize = 1;
  25464. do {
  25465. let p = list;
  25466. let e;
  25467. list = null;
  25468. let tail = null;
  25469. numMerges = 0;
  25470. while (p) {
  25471. numMerges++;
  25472. let q = p;
  25473. let pSize = 0;
  25474. for (let i = 0; i < inSize; i++) {
  25475. pSize++;
  25476. q = q.nextZ;
  25477. if (!q) break;
  25478. }
  25479. let qSize = inSize;
  25480. while (pSize > 0 || (qSize > 0 && q)) {
  25481. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25482. e = p;
  25483. p = p.nextZ;
  25484. pSize--;
  25485. } else {
  25486. e = q;
  25487. q = q.nextZ;
  25488. qSize--;
  25489. }
  25490. if (tail) tail.nextZ = e;
  25491. else list = e;
  25492. e.prevZ = tail;
  25493. tail = e;
  25494. }
  25495. p = q;
  25496. }
  25497. tail.nextZ = null;
  25498. inSize *= 2;
  25499. } while (numMerges > 1);
  25500. return list;
  25501. }
  25502. // z-order of a point given coords and inverse of the longer side of data bbox
  25503. function zOrder(x, y, minX, minY, invSize) {
  25504. // coords are transformed into non-negative 15-bit integer range
  25505. x = (x - minX) * invSize | 0;
  25506. y = (y - minY) * invSize | 0;
  25507. x = (x | (x << 8)) & 0x00FF00FF;
  25508. x = (x | (x << 4)) & 0x0F0F0F0F;
  25509. x = (x | (x << 2)) & 0x33333333;
  25510. x = (x | (x << 1)) & 0x55555555;
  25511. y = (y | (y << 8)) & 0x00FF00FF;
  25512. y = (y | (y << 4)) & 0x0F0F0F0F;
  25513. y = (y | (y << 2)) & 0x33333333;
  25514. y = (y | (y << 1)) & 0x55555555;
  25515. return x | (y << 1);
  25516. }
  25517. // find the leftmost node of a polygon ring
  25518. function getLeftmost(start) {
  25519. let p = start,
  25520. leftmost = start;
  25521. do {
  25522. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25523. p = p.next;
  25524. } while (p !== start);
  25525. return leftmost;
  25526. }
  25527. // check if a point lies within a convex triangle
  25528. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25529. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25530. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25531. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25532. }
  25533. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25534. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25535. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25536. }
  25537. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25538. function isValidDiagonal(a, b) {
  25539. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25540. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25541. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25542. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25543. }
  25544. // signed area of a triangle
  25545. function area(p, q, r) {
  25546. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25547. }
  25548. // check if two points are equal
  25549. function equals(p1, p2) {
  25550. return p1.x === p2.x && p1.y === p2.y;
  25551. }
  25552. // check if two segments intersect
  25553. function intersects(p1, q1, p2, q2) {
  25554. const o1 = sign(area(p1, q1, p2));
  25555. const o2 = sign(area(p1, q1, q2));
  25556. const o3 = sign(area(p2, q2, p1));
  25557. const o4 = sign(area(p2, q2, q1));
  25558. if (o1 !== o2 && o3 !== o4) return true; // general case
  25559. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25560. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25561. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25562. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25563. return false;
  25564. }
  25565. // for collinear points p, q, r, check if point q lies on segment pr
  25566. function onSegment(p, q, r) {
  25567. 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);
  25568. }
  25569. function sign(num) {
  25570. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25571. }
  25572. // check if a polygon diagonal intersects any polygon segments
  25573. function intersectsPolygon(a, b) {
  25574. let p = a;
  25575. do {
  25576. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25577. intersects(p, p.next, a, b)) return true;
  25578. p = p.next;
  25579. } while (p !== a);
  25580. return false;
  25581. }
  25582. // check if a polygon diagonal is locally inside the polygon
  25583. function locallyInside(a, b) {
  25584. return area(a.prev, a, a.next) < 0 ?
  25585. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25586. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25587. }
  25588. // check if the middle point of a polygon diagonal is inside the polygon
  25589. function middleInside(a, b) {
  25590. let p = a;
  25591. let inside = false;
  25592. const px = (a.x + b.x) / 2;
  25593. const py = (a.y + b.y) / 2;
  25594. do {
  25595. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25596. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25597. inside = !inside;
  25598. p = p.next;
  25599. } while (p !== a);
  25600. return inside;
  25601. }
  25602. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25603. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25604. function splitPolygon(a, b) {
  25605. const a2 = createNode(a.i, a.x, a.y),
  25606. b2 = createNode(b.i, b.x, b.y),
  25607. an = a.next,
  25608. bp = b.prev;
  25609. a.next = b;
  25610. b.prev = a;
  25611. a2.next = an;
  25612. an.prev = a2;
  25613. b2.next = a2;
  25614. a2.prev = b2;
  25615. bp.next = b2;
  25616. b2.prev = bp;
  25617. return b2;
  25618. }
  25619. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25620. function insertNode(i, x, y, last) {
  25621. const p = createNode(i, x, y);
  25622. if (!last) {
  25623. p.prev = p;
  25624. p.next = p;
  25625. } else {
  25626. p.next = last.next;
  25627. p.prev = last;
  25628. last.next.prev = p;
  25629. last.next = p;
  25630. }
  25631. return p;
  25632. }
  25633. function removeNode(p) {
  25634. p.next.prev = p.prev;
  25635. p.prev.next = p.next;
  25636. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25637. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25638. }
  25639. function createNode(i, x, y) {
  25640. return {
  25641. i, // vertex index in coordinates array
  25642. x, y, // vertex coordinates
  25643. prev: null, // previous and next vertex nodes in a polygon ring
  25644. next: null,
  25645. z: 0, // z-order curve value
  25646. prevZ: null, // previous and next nodes in z-order
  25647. nextZ: null,
  25648. steiner: false // indicates whether this is a steiner point
  25649. };
  25650. }
  25651. function signedArea(data, start, end, dim) {
  25652. let sum = 0;
  25653. for (let i = start, j = end - dim; i < end; i += dim) {
  25654. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25655. j = i;
  25656. }
  25657. return sum;
  25658. }
  25659. class Earcut {
  25660. /**
  25661. * Triangulates the given shape definition by returning an array of triangles.
  25662. *
  25663. * @param {Array<number>} data - An array with 2D points.
  25664. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25665. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25666. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25667. * representing vertex indices.
  25668. */
  25669. static triangulate( data, holeIndices, dim = 2 ) {
  25670. return earcut( data, holeIndices, dim );
  25671. }
  25672. }
  25673. /**
  25674. * A class containing utility functions for shapes.
  25675. *
  25676. * @hideconstructor
  25677. */
  25678. class ShapeUtils {
  25679. /**
  25680. * Calculate area of a ( 2D ) contour polygon.
  25681. *
  25682. * @param {Array<Vector2>} contour - An array of 2D points.
  25683. * @return {number} The area.
  25684. */
  25685. static area( contour ) {
  25686. const n = contour.length;
  25687. let a = 0.0;
  25688. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25689. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25690. }
  25691. return a * 0.5;
  25692. }
  25693. /**
  25694. * Returns `true` if the given contour uses a clockwise winding order.
  25695. *
  25696. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25697. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25698. */
  25699. static isClockWise( pts ) {
  25700. return ShapeUtils.area( pts ) < 0;
  25701. }
  25702. /**
  25703. * Triangulates the given shape definition.
  25704. *
  25705. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25706. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25707. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25708. */
  25709. static triangulateShape( contour, holes ) {
  25710. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25711. const holeIndices = []; // array of hole indices
  25712. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25713. removeDupEndPts( contour );
  25714. addContour( vertices, contour );
  25715. //
  25716. let holeIndex = contour.length;
  25717. holes.forEach( removeDupEndPts );
  25718. for ( let i = 0; i < holes.length; i ++ ) {
  25719. holeIndices.push( holeIndex );
  25720. holeIndex += holes[ i ].length;
  25721. addContour( vertices, holes[ i ] );
  25722. }
  25723. //
  25724. const triangles = Earcut.triangulate( vertices, holeIndices );
  25725. //
  25726. for ( let i = 0; i < triangles.length; i += 3 ) {
  25727. faces.push( triangles.slice( i, i + 3 ) );
  25728. }
  25729. return faces;
  25730. }
  25731. }
  25732. function removeDupEndPts( points ) {
  25733. const l = points.length;
  25734. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25735. points.pop();
  25736. }
  25737. }
  25738. function addContour( vertices, contour ) {
  25739. for ( let i = 0; i < contour.length; i ++ ) {
  25740. vertices.push( contour[ i ].x );
  25741. vertices.push( contour[ i ].y );
  25742. }
  25743. }
  25744. /**
  25745. * Creates extruded geometry from a path shape.
  25746. *
  25747. * ```js
  25748. * const length = 12, width = 8;
  25749. *
  25750. * const shape = new THREE.Shape();
  25751. * shape.moveTo( 0,0 );
  25752. * shape.lineTo( 0, width );
  25753. * shape.lineTo( length, width );
  25754. * shape.lineTo( length, 0 );
  25755. * shape.lineTo( 0, 0 );
  25756. *
  25757. * const geometry = new THREE.ExtrudeGeometry( shape );
  25758. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25759. * const mesh = new THREE.Mesh( geometry, material ) ;
  25760. * scene.add( mesh );
  25761. * ```
  25762. *
  25763. * @augments BufferGeometry
  25764. */
  25765. class ExtrudeGeometry extends BufferGeometry {
  25766. /**
  25767. * Constructs a new extrude geometry.
  25768. *
  25769. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25770. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25771. */
  25772. 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 = {} ) {
  25773. super();
  25774. this.type = 'ExtrudeGeometry';
  25775. /**
  25776. * Holds the constructor parameters that have been
  25777. * used to generate the geometry. Any modification
  25778. * after instantiation does not change the geometry.
  25779. *
  25780. * @type {Object}
  25781. */
  25782. this.parameters = {
  25783. shapes: shapes,
  25784. options: options
  25785. };
  25786. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25787. const scope = this;
  25788. const verticesArray = [];
  25789. const uvArray = [];
  25790. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25791. const shape = shapes[ i ];
  25792. addShape( shape );
  25793. }
  25794. // build geometry
  25795. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25796. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25797. this.computeVertexNormals();
  25798. // functions
  25799. function addShape( shape ) {
  25800. const placeholder = [];
  25801. // options
  25802. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25803. const steps = options.steps !== undefined ? options.steps : 1;
  25804. const depth = options.depth !== undefined ? options.depth : 1;
  25805. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25806. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25807. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25808. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25809. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25810. const extrudePath = options.extrudePath;
  25811. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25812. //
  25813. let extrudePts, extrudeByPath = false;
  25814. let splineTube, binormal, normal, position2;
  25815. if ( extrudePath ) {
  25816. extrudePts = extrudePath.getSpacedPoints( steps );
  25817. extrudeByPath = true;
  25818. bevelEnabled = false; // bevels not supported for path extrusion
  25819. // SETUP TNB variables
  25820. // TODO1 - have a .isClosed in spline?
  25821. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25822. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25823. binormal = new Vector3();
  25824. normal = new Vector3();
  25825. position2 = new Vector3();
  25826. }
  25827. // Safeguards if bevels are not enabled
  25828. if ( ! bevelEnabled ) {
  25829. bevelSegments = 0;
  25830. bevelThickness = 0;
  25831. bevelSize = 0;
  25832. bevelOffset = 0;
  25833. }
  25834. // Variables initialization
  25835. const shapePoints = shape.extractPoints( curveSegments );
  25836. let vertices = shapePoints.shape;
  25837. const holes = shapePoints.holes;
  25838. const reverse = ! ShapeUtils.isClockWise( vertices );
  25839. if ( reverse ) {
  25840. vertices = vertices.reverse();
  25841. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  25842. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  25843. const ahole = holes[ h ];
  25844. if ( ShapeUtils.isClockWise( ahole ) ) {
  25845. holes[ h ] = ahole.reverse();
  25846. }
  25847. }
  25848. }
  25849. /**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.
  25850. * @param {Array<Vector2>} points
  25851. */
  25852. function mergeOverlappingPoints( points ) {
  25853. const THRESHOLD = 1e-10;
  25854. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  25855. let prevPos = points[ 0 ];
  25856. for ( let i = 1; i <= points.length; i ++ ) {
  25857. const currentIndex = i % points.length;
  25858. const currentPos = points[ currentIndex ];
  25859. const dx = currentPos.x - prevPos.x;
  25860. const dy = currentPos.y - prevPos.y;
  25861. const distSq = dx * dx + dy * dy;
  25862. const scalingFactorSqrt = Math.max(
  25863. Math.abs( currentPos.x ),
  25864. Math.abs( currentPos.y ),
  25865. Math.abs( prevPos.x ),
  25866. Math.abs( prevPos.y )
  25867. );
  25868. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  25869. if ( distSq <= thresholdSqScaled ) {
  25870. points.splice( currentIndex, 1 );
  25871. i --;
  25872. continue;
  25873. }
  25874. prevPos = currentPos;
  25875. }
  25876. }
  25877. mergeOverlappingPoints( vertices );
  25878. holes.forEach( mergeOverlappingPoints );
  25879. const numHoles = holes.length;
  25880. /* Vertices */
  25881. const contour = vertices; // vertices has all points but contour has only points of circumference
  25882. for ( let h = 0; h < numHoles; h ++ ) {
  25883. const ahole = holes[ h ];
  25884. vertices = vertices.concat( ahole );
  25885. }
  25886. function scalePt2( pt, vec, size ) {
  25887. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  25888. return pt.clone().addScaledVector( vec, size );
  25889. }
  25890. const vlen = vertices.length;
  25891. // Find directions for point movement
  25892. function getBevelVec( inPt, inPrev, inNext ) {
  25893. // computes for inPt the corresponding point inPt' on a new contour
  25894. // shifted by 1 unit (length of normalized vector) to the left
  25895. // if we walk along contour clockwise, this new contour is outside the old one
  25896. //
  25897. // inPt' is the intersection of the two lines parallel to the two
  25898. // adjacent edges of inPt at a distance of 1 unit on the left side.
  25899. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  25900. // good reading for geometry algorithms (here: line-line intersection)
  25901. // http://geomalgorithms.com/a05-_intersect-1.html
  25902. const v_prev_x = inPt.x - inPrev.x,
  25903. v_prev_y = inPt.y - inPrev.y;
  25904. const v_next_x = inNext.x - inPt.x,
  25905. v_next_y = inNext.y - inPt.y;
  25906. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  25907. // check for collinear edges
  25908. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25909. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  25910. // not collinear
  25911. // length of vectors for normalizing
  25912. const v_prev_len = Math.sqrt( v_prev_lensq );
  25913. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  25914. // shift adjacent points by unit vectors to the left
  25915. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  25916. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  25917. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  25918. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  25919. // scaling factor for v_prev to intersection point
  25920. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  25921. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  25922. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  25923. // vector from inPt to intersection point
  25924. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  25925. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  25926. // Don't normalize!, otherwise sharp corners become ugly
  25927. // but prevent crazy spikes
  25928. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  25929. if ( v_trans_lensq <= 2 ) {
  25930. return new Vector2( v_trans_x, v_trans_y );
  25931. } else {
  25932. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  25933. }
  25934. } else {
  25935. // handle special case of collinear edges
  25936. let direction_eq = false; // assumes: opposite
  25937. if ( v_prev_x > Number.EPSILON ) {
  25938. if ( v_next_x > Number.EPSILON ) {
  25939. direction_eq = true;
  25940. }
  25941. } else {
  25942. if ( v_prev_x < - Number.EPSILON ) {
  25943. if ( v_next_x < - Number.EPSILON ) {
  25944. direction_eq = true;
  25945. }
  25946. } else {
  25947. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  25948. direction_eq = true;
  25949. }
  25950. }
  25951. }
  25952. if ( direction_eq ) {
  25953. // log("Warning: lines are a straight sequence");
  25954. v_trans_x = - v_prev_y;
  25955. v_trans_y = v_prev_x;
  25956. shrink_by = Math.sqrt( v_prev_lensq );
  25957. } else {
  25958. // log("Warning: lines are a straight spike");
  25959. v_trans_x = v_prev_x;
  25960. v_trans_y = v_prev_y;
  25961. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  25962. }
  25963. }
  25964. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  25965. }
  25966. const contourMovements = [];
  25967. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25968. if ( j === il ) j = 0;
  25969. if ( k === il ) k = 0;
  25970. // (j)---(i)---(k)
  25971. // log('i,j,k', i, j , k)
  25972. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  25973. }
  25974. const holesMovements = [];
  25975. let oneHoleMovements, verticesMovements = contourMovements.concat();
  25976. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  25977. const ahole = holes[ h ];
  25978. oneHoleMovements = [];
  25979. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  25980. if ( j === il ) j = 0;
  25981. if ( k === il ) k = 0;
  25982. // (j)---(i)---(k)
  25983. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  25984. }
  25985. holesMovements.push( oneHoleMovements );
  25986. verticesMovements = verticesMovements.concat( oneHoleMovements );
  25987. }
  25988. let faces;
  25989. if ( bevelSegments === 0 ) {
  25990. faces = ShapeUtils.triangulateShape( contour, holes );
  25991. } else {
  25992. const contractedContourVertices = [];
  25993. const expandedHoleVertices = [];
  25994. // Loop bevelSegments, 1 for the front, 1 for the back
  25995. for ( let b = 0; b < bevelSegments; b ++ ) {
  25996. //for ( b = bevelSegments; b > 0; b -- ) {
  25997. const t = b / bevelSegments;
  25998. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  25999. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26000. // contract shape
  26001. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26002. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26003. v( vert.x, vert.y, - z );
  26004. if ( t === 0 ) contractedContourVertices.push( vert );
  26005. }
  26006. // expand holes
  26007. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26008. const ahole = holes[ h ];
  26009. oneHoleMovements = holesMovements[ h ];
  26010. const oneHoleVertices = [];
  26011. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26012. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26013. v( vert.x, vert.y, - z );
  26014. if ( t === 0 ) oneHoleVertices.push( vert );
  26015. }
  26016. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26017. }
  26018. }
  26019. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26020. }
  26021. const flen = faces.length;
  26022. const bs = bevelSize + bevelOffset;
  26023. // Back facing vertices
  26024. for ( let i = 0; i < vlen; i ++ ) {
  26025. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26026. if ( ! extrudeByPath ) {
  26027. v( vert.x, vert.y, 0 );
  26028. } else {
  26029. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26030. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26031. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26032. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26033. v( position2.x, position2.y, position2.z );
  26034. }
  26035. }
  26036. // Add stepped vertices...
  26037. // Including front facing vertices
  26038. for ( let s = 1; s <= steps; s ++ ) {
  26039. for ( let i = 0; i < vlen; i ++ ) {
  26040. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26041. if ( ! extrudeByPath ) {
  26042. v( vert.x, vert.y, depth / steps * s );
  26043. } else {
  26044. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26045. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26046. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26047. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26048. v( position2.x, position2.y, position2.z );
  26049. }
  26050. }
  26051. }
  26052. // Add bevel segments planes
  26053. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26054. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26055. const t = b / bevelSegments;
  26056. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26057. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26058. // contract shape
  26059. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26060. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26061. v( vert.x, vert.y, depth + z );
  26062. }
  26063. // expand holes
  26064. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26065. const ahole = holes[ h ];
  26066. oneHoleMovements = holesMovements[ h ];
  26067. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26068. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26069. if ( ! extrudeByPath ) {
  26070. v( vert.x, vert.y, depth + z );
  26071. } else {
  26072. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26073. }
  26074. }
  26075. }
  26076. }
  26077. /* Faces */
  26078. // Top and bottom faces
  26079. buildLidFaces();
  26080. // Sides faces
  26081. buildSideFaces();
  26082. ///// Internal functions
  26083. function buildLidFaces() {
  26084. const start = verticesArray.length / 3;
  26085. if ( bevelEnabled ) {
  26086. let layer = 0; // steps + 1
  26087. let offset = vlen * layer;
  26088. // Bottom faces
  26089. for ( let i = 0; i < flen; i ++ ) {
  26090. const face = faces[ i ];
  26091. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26092. }
  26093. layer = steps + bevelSegments * 2;
  26094. offset = vlen * layer;
  26095. // Top faces
  26096. for ( let i = 0; i < flen; i ++ ) {
  26097. const face = faces[ i ];
  26098. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26099. }
  26100. } else {
  26101. // Bottom faces
  26102. for ( let i = 0; i < flen; i ++ ) {
  26103. const face = faces[ i ];
  26104. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26105. }
  26106. // Top faces
  26107. for ( let i = 0; i < flen; i ++ ) {
  26108. const face = faces[ i ];
  26109. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26110. }
  26111. }
  26112. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26113. }
  26114. // Create faces for the z-sides of the shape
  26115. function buildSideFaces() {
  26116. const start = verticesArray.length / 3;
  26117. let layeroffset = 0;
  26118. sidewalls( contour, layeroffset );
  26119. layeroffset += contour.length;
  26120. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26121. const ahole = holes[ h ];
  26122. sidewalls( ahole, layeroffset );
  26123. //, true
  26124. layeroffset += ahole.length;
  26125. }
  26126. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26127. }
  26128. function sidewalls( contour, layeroffset ) {
  26129. let i = contour.length;
  26130. while ( -- i >= 0 ) {
  26131. const j = i;
  26132. let k = i - 1;
  26133. if ( k < 0 ) k = contour.length - 1;
  26134. //log('b', i,j, i-1, k,vertices.length);
  26135. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26136. const slen1 = vlen * s;
  26137. const slen2 = vlen * ( s + 1 );
  26138. const a = layeroffset + j + slen1,
  26139. b = layeroffset + k + slen1,
  26140. c = layeroffset + k + slen2,
  26141. d = layeroffset + j + slen2;
  26142. f4( a, b, c, d );
  26143. }
  26144. }
  26145. }
  26146. function v( x, y, z ) {
  26147. placeholder.push( x );
  26148. placeholder.push( y );
  26149. placeholder.push( z );
  26150. }
  26151. function f3( a, b, c ) {
  26152. addVertex( a );
  26153. addVertex( b );
  26154. addVertex( c );
  26155. const nextIndex = verticesArray.length / 3;
  26156. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26157. addUV( uvs[ 0 ] );
  26158. addUV( uvs[ 1 ] );
  26159. addUV( uvs[ 2 ] );
  26160. }
  26161. function f4( a, b, c, d ) {
  26162. addVertex( a );
  26163. addVertex( b );
  26164. addVertex( d );
  26165. addVertex( b );
  26166. addVertex( c );
  26167. addVertex( d );
  26168. const nextIndex = verticesArray.length / 3;
  26169. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26170. addUV( uvs[ 0 ] );
  26171. addUV( uvs[ 1 ] );
  26172. addUV( uvs[ 3 ] );
  26173. addUV( uvs[ 1 ] );
  26174. addUV( uvs[ 2 ] );
  26175. addUV( uvs[ 3 ] );
  26176. }
  26177. function addVertex( index ) {
  26178. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26179. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26180. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26181. }
  26182. function addUV( vector2 ) {
  26183. uvArray.push( vector2.x );
  26184. uvArray.push( vector2.y );
  26185. }
  26186. }
  26187. }
  26188. copy( source ) {
  26189. super.copy( source );
  26190. this.parameters = Object.assign( {}, source.parameters );
  26191. return this;
  26192. }
  26193. toJSON() {
  26194. const data = super.toJSON();
  26195. const shapes = this.parameters.shapes;
  26196. const options = this.parameters.options;
  26197. return toJSON$1( shapes, options, data );
  26198. }
  26199. /**
  26200. * Factory method for creating an instance of this class from the given
  26201. * JSON object.
  26202. *
  26203. * @param {Object} data - A JSON object representing the serialized geometry.
  26204. * @param {Array<Shape>} shapes - An array of shapes.
  26205. * @return {ExtrudeGeometry} A new instance.
  26206. */
  26207. static fromJSON( data, shapes ) {
  26208. const geometryShapes = [];
  26209. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26210. const shape = shapes[ data.shapes[ j ] ];
  26211. geometryShapes.push( shape );
  26212. }
  26213. const extrudePath = data.options.extrudePath;
  26214. if ( extrudePath !== undefined ) {
  26215. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26216. }
  26217. return new ExtrudeGeometry( geometryShapes, data.options );
  26218. }
  26219. }
  26220. const WorldUVGenerator = {
  26221. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26222. const a_x = vertices[ indexA * 3 ];
  26223. const a_y = vertices[ indexA * 3 + 1 ];
  26224. const b_x = vertices[ indexB * 3 ];
  26225. const b_y = vertices[ indexB * 3 + 1 ];
  26226. const c_x = vertices[ indexC * 3 ];
  26227. const c_y = vertices[ indexC * 3 + 1 ];
  26228. return [
  26229. new Vector2( a_x, a_y ),
  26230. new Vector2( b_x, b_y ),
  26231. new Vector2( c_x, c_y )
  26232. ];
  26233. },
  26234. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26235. const a_x = vertices[ indexA * 3 ];
  26236. const a_y = vertices[ indexA * 3 + 1 ];
  26237. const a_z = vertices[ indexA * 3 + 2 ];
  26238. const b_x = vertices[ indexB * 3 ];
  26239. const b_y = vertices[ indexB * 3 + 1 ];
  26240. const b_z = vertices[ indexB * 3 + 2 ];
  26241. const c_x = vertices[ indexC * 3 ];
  26242. const c_y = vertices[ indexC * 3 + 1 ];
  26243. const c_z = vertices[ indexC * 3 + 2 ];
  26244. const d_x = vertices[ indexD * 3 ];
  26245. const d_y = vertices[ indexD * 3 + 1 ];
  26246. const d_z = vertices[ indexD * 3 + 2 ];
  26247. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26248. return [
  26249. new Vector2( a_x, 1 - a_z ),
  26250. new Vector2( b_x, 1 - b_z ),
  26251. new Vector2( c_x, 1 - c_z ),
  26252. new Vector2( d_x, 1 - d_z )
  26253. ];
  26254. } else {
  26255. return [
  26256. new Vector2( a_y, 1 - a_z ),
  26257. new Vector2( b_y, 1 - b_z ),
  26258. new Vector2( c_y, 1 - c_z ),
  26259. new Vector2( d_y, 1 - d_z )
  26260. ];
  26261. }
  26262. }
  26263. };
  26264. function toJSON$1( shapes, options, data ) {
  26265. data.shapes = [];
  26266. if ( Array.isArray( shapes ) ) {
  26267. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26268. const shape = shapes[ i ];
  26269. data.shapes.push( shape.uuid );
  26270. }
  26271. } else {
  26272. data.shapes.push( shapes.uuid );
  26273. }
  26274. data.options = Object.assign( {}, options );
  26275. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26276. return data;
  26277. }
  26278. /**
  26279. * A geometry class for representing an icosahedron.
  26280. *
  26281. * ```js
  26282. * const geometry = new THREE.IcosahedronGeometry();
  26283. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26284. * const icosahedron = new THREE.Mesh( geometry, material );
  26285. * scene.add( icosahedron );
  26286. * ```
  26287. *
  26288. * @augments PolyhedronGeometry
  26289. */
  26290. class IcosahedronGeometry extends PolyhedronGeometry {
  26291. /**
  26292. * Constructs a new icosahedron geometry.
  26293. *
  26294. * @param {number} [radius=1] - Radius of the icosahedron.
  26295. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26296. */
  26297. constructor( radius = 1, detail = 0 ) {
  26298. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26299. const vertices = [
  26300. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26301. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26302. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26303. ];
  26304. const indices = [
  26305. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26306. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26307. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26308. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26309. ];
  26310. super( vertices, indices, radius, detail );
  26311. this.type = 'IcosahedronGeometry';
  26312. /**
  26313. * Holds the constructor parameters that have been
  26314. * used to generate the geometry. Any modification
  26315. * after instantiation does not change the geometry.
  26316. *
  26317. * @type {Object}
  26318. */
  26319. this.parameters = {
  26320. radius: radius,
  26321. detail: detail
  26322. };
  26323. }
  26324. /**
  26325. * Factory method for creating an instance of this class from the given
  26326. * JSON object.
  26327. *
  26328. * @param {Object} data - A JSON object representing the serialized geometry.
  26329. * @return {IcosahedronGeometry} A new instance.
  26330. */
  26331. static fromJSON( data ) {
  26332. return new IcosahedronGeometry( data.radius, data.detail );
  26333. }
  26334. }
  26335. /**
  26336. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26337. *
  26338. * ```js
  26339. * const points = [];
  26340. * for ( let i = 0; i < 10; i ++ ) {
  26341. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26342. * }
  26343. * const geometry = new THREE.LatheGeometry( points );
  26344. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26345. * const lathe = new THREE.Mesh( geometry, material );
  26346. * scene.add( lathe );
  26347. * ```
  26348. *
  26349. * @augments BufferGeometry
  26350. */
  26351. class LatheGeometry extends BufferGeometry {
  26352. /**
  26353. * Constructs a new lathe geometry.
  26354. *
  26355. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26356. * must be greater than zero.
  26357. * @param {number} [segments=12] - The number of circumference segments to generate.
  26358. * @param {number} [phiStart=0] - The starting angle in radians.
  26359. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26360. * closed lathe, less than 2PI is a portion.
  26361. */
  26362. 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 ) {
  26363. super();
  26364. this.type = 'LatheGeometry';
  26365. /**
  26366. * Holds the constructor parameters that have been
  26367. * used to generate the geometry. Any modification
  26368. * after instantiation does not change the geometry.
  26369. *
  26370. * @type {Object}
  26371. */
  26372. this.parameters = {
  26373. points: points,
  26374. segments: segments,
  26375. phiStart: phiStart,
  26376. phiLength: phiLength
  26377. };
  26378. segments = Math.floor( segments );
  26379. // clamp phiLength so it's in range of [ 0, 2PI ]
  26380. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26381. // buffers
  26382. const indices = [];
  26383. const vertices = [];
  26384. const uvs = [];
  26385. const initNormals = [];
  26386. const normals = [];
  26387. // helper variables
  26388. const inverseSegments = 1.0 / segments;
  26389. const vertex = new Vector3();
  26390. const uv = new Vector2();
  26391. const normal = new Vector3();
  26392. const curNormal = new Vector3();
  26393. const prevNormal = new Vector3();
  26394. let dx = 0;
  26395. let dy = 0;
  26396. // pre-compute normals for initial "meridian"
  26397. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26398. switch ( j ) {
  26399. case 0: // special handling for 1st vertex on path
  26400. dx = points[ j + 1 ].x - points[ j ].x;
  26401. dy = points[ j + 1 ].y - points[ j ].y;
  26402. normal.x = dy * 1.0;
  26403. normal.y = - dx;
  26404. normal.z = dy * 0.0;
  26405. prevNormal.copy( normal );
  26406. normal.normalize();
  26407. initNormals.push( normal.x, normal.y, normal.z );
  26408. break;
  26409. case ( points.length - 1 ): // special handling for last Vertex on path
  26410. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26411. break;
  26412. default: // default handling for all vertices in between
  26413. dx = points[ j + 1 ].x - points[ j ].x;
  26414. dy = points[ j + 1 ].y - points[ j ].y;
  26415. normal.x = dy * 1.0;
  26416. normal.y = - dx;
  26417. normal.z = dy * 0.0;
  26418. curNormal.copy( normal );
  26419. normal.x += prevNormal.x;
  26420. normal.y += prevNormal.y;
  26421. normal.z += prevNormal.z;
  26422. normal.normalize();
  26423. initNormals.push( normal.x, normal.y, normal.z );
  26424. prevNormal.copy( curNormal );
  26425. }
  26426. }
  26427. // generate vertices, uvs and normals
  26428. for ( let i = 0; i <= segments; i ++ ) {
  26429. const phi = phiStart + i * inverseSegments * phiLength;
  26430. const sin = Math.sin( phi );
  26431. const cos = Math.cos( phi );
  26432. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26433. // vertex
  26434. vertex.x = points[ j ].x * sin;
  26435. vertex.y = points[ j ].y;
  26436. vertex.z = points[ j ].x * cos;
  26437. vertices.push( vertex.x, vertex.y, vertex.z );
  26438. // uv
  26439. uv.x = i / segments;
  26440. uv.y = j / ( points.length - 1 );
  26441. uvs.push( uv.x, uv.y );
  26442. // normal
  26443. const x = initNormals[ 3 * j + 0 ] * sin;
  26444. const y = initNormals[ 3 * j + 1 ];
  26445. const z = initNormals[ 3 * j + 0 ] * cos;
  26446. normals.push( x, y, z );
  26447. }
  26448. }
  26449. // indices
  26450. for ( let i = 0; i < segments; i ++ ) {
  26451. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26452. const base = j + i * points.length;
  26453. const a = base;
  26454. const b = base + points.length;
  26455. const c = base + points.length + 1;
  26456. const d = base + 1;
  26457. // faces
  26458. indices.push( a, b, d );
  26459. indices.push( c, d, b );
  26460. }
  26461. }
  26462. // build geometry
  26463. this.setIndex( indices );
  26464. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26465. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26466. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26467. }
  26468. copy( source ) {
  26469. super.copy( source );
  26470. this.parameters = Object.assign( {}, source.parameters );
  26471. return this;
  26472. }
  26473. /**
  26474. * Factory method for creating an instance of this class from the given
  26475. * JSON object.
  26476. *
  26477. * @param {Object} data - A JSON object representing the serialized geometry.
  26478. * @return {LatheGeometry} A new instance.
  26479. */
  26480. static fromJSON( data ) {
  26481. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26482. }
  26483. }
  26484. /**
  26485. * A geometry class for representing an octahedron.
  26486. *
  26487. * ```js
  26488. * const geometry = new THREE.OctahedronGeometry();
  26489. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26490. * const octahedron = new THREE.Mesh( geometry, material );
  26491. * scene.add( octahedron );
  26492. * ```
  26493. *
  26494. * @augments PolyhedronGeometry
  26495. */
  26496. class OctahedronGeometry extends PolyhedronGeometry {
  26497. /**
  26498. * Constructs a new octahedron geometry.
  26499. *
  26500. * @param {number} [radius=1] - Radius of the octahedron.
  26501. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26502. */
  26503. constructor( radius = 1, detail = 0 ) {
  26504. const vertices = [
  26505. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26506. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26507. ];
  26508. const indices = [
  26509. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26510. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26511. 1, 3, 4, 1, 4, 2
  26512. ];
  26513. super( vertices, indices, radius, detail );
  26514. this.type = 'OctahedronGeometry';
  26515. /**
  26516. * Holds the constructor parameters that have been
  26517. * used to generate the geometry. Any modification
  26518. * after instantiation does not change the geometry.
  26519. *
  26520. * @type {Object}
  26521. */
  26522. this.parameters = {
  26523. radius: radius,
  26524. detail: detail
  26525. };
  26526. }
  26527. /**
  26528. * Factory method for creating an instance of this class from the given
  26529. * JSON object.
  26530. *
  26531. * @param {Object} data - A JSON object representing the serialized geometry.
  26532. * @return {OctahedronGeometry} A new instance.
  26533. */
  26534. static fromJSON( data ) {
  26535. return new OctahedronGeometry( data.radius, data.detail );
  26536. }
  26537. }
  26538. /**
  26539. * A geometry class for representing a plane.
  26540. *
  26541. * ```js
  26542. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26543. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26544. * const plane = new THREE.Mesh( geometry, material );
  26545. * scene.add( plane );
  26546. * ```
  26547. *
  26548. * @augments BufferGeometry
  26549. */
  26550. class PlaneGeometry extends BufferGeometry {
  26551. /**
  26552. * Constructs a new plane geometry.
  26553. *
  26554. * @param {number} [width=1] - The width along the X axis.
  26555. * @param {number} [height=1] - The height along the Y axis
  26556. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26557. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26558. */
  26559. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26560. super();
  26561. this.type = 'PlaneGeometry';
  26562. /**
  26563. * Holds the constructor parameters that have been
  26564. * used to generate the geometry. Any modification
  26565. * after instantiation does not change the geometry.
  26566. *
  26567. * @type {Object}
  26568. */
  26569. this.parameters = {
  26570. width: width,
  26571. height: height,
  26572. widthSegments: widthSegments,
  26573. heightSegments: heightSegments
  26574. };
  26575. const width_half = width / 2;
  26576. const height_half = height / 2;
  26577. const gridX = Math.floor( widthSegments );
  26578. const gridY = Math.floor( heightSegments );
  26579. const gridX1 = gridX + 1;
  26580. const gridY1 = gridY + 1;
  26581. const segment_width = width / gridX;
  26582. const segment_height = height / gridY;
  26583. //
  26584. const indices = [];
  26585. const vertices = [];
  26586. const normals = [];
  26587. const uvs = [];
  26588. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26589. const y = iy * segment_height - height_half;
  26590. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26591. const x = ix * segment_width - width_half;
  26592. vertices.push( x, - y, 0 );
  26593. normals.push( 0, 0, 1 );
  26594. uvs.push( ix / gridX );
  26595. uvs.push( 1 - ( iy / gridY ) );
  26596. }
  26597. }
  26598. for ( let iy = 0; iy < gridY; iy ++ ) {
  26599. for ( let ix = 0; ix < gridX; ix ++ ) {
  26600. const a = ix + gridX1 * iy;
  26601. const b = ix + gridX1 * ( iy + 1 );
  26602. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26603. const d = ( ix + 1 ) + gridX1 * iy;
  26604. indices.push( a, b, d );
  26605. indices.push( b, c, d );
  26606. }
  26607. }
  26608. this.setIndex( indices );
  26609. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26610. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26611. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26612. }
  26613. copy( source ) {
  26614. super.copy( source );
  26615. this.parameters = Object.assign( {}, source.parameters );
  26616. return this;
  26617. }
  26618. /**
  26619. * Factory method for creating an instance of this class from the given
  26620. * JSON object.
  26621. *
  26622. * @param {Object} data - A JSON object representing the serialized geometry.
  26623. * @return {PlaneGeometry} A new instance.
  26624. */
  26625. static fromJSON( data ) {
  26626. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26627. }
  26628. }
  26629. /**
  26630. * A class for generating a two-dimensional ring geometry.
  26631. *
  26632. * ```js
  26633. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26634. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26635. * const mesh = new THREE.Mesh( geometry, material );
  26636. * scene.add( mesh );
  26637. * ```
  26638. *
  26639. * @augments BufferGeometry
  26640. */
  26641. class RingGeometry extends BufferGeometry {
  26642. /**
  26643. * Constructs a new ring geometry.
  26644. *
  26645. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26646. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26647. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26648. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26649. * @param {number} [thetaStart=0] - Starting angle in radians.
  26650. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26651. */
  26652. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26653. super();
  26654. this.type = 'RingGeometry';
  26655. /**
  26656. * Holds the constructor parameters that have been
  26657. * used to generate the geometry. Any modification
  26658. * after instantiation does not change the geometry.
  26659. *
  26660. * @type {Object}
  26661. */
  26662. this.parameters = {
  26663. innerRadius: innerRadius,
  26664. outerRadius: outerRadius,
  26665. thetaSegments: thetaSegments,
  26666. phiSegments: phiSegments,
  26667. thetaStart: thetaStart,
  26668. thetaLength: thetaLength
  26669. };
  26670. thetaSegments = Math.max( 3, thetaSegments );
  26671. phiSegments = Math.max( 1, phiSegments );
  26672. // buffers
  26673. const indices = [];
  26674. const vertices = [];
  26675. const normals = [];
  26676. const uvs = [];
  26677. // some helper variables
  26678. let radius = innerRadius;
  26679. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26680. const vertex = new Vector3();
  26681. const uv = new Vector2();
  26682. // generate vertices, normals and uvs
  26683. for ( let j = 0; j <= phiSegments; j ++ ) {
  26684. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26685. // values are generate from the inside of the ring to the outside
  26686. const segment = thetaStart + i / thetaSegments * thetaLength;
  26687. // vertex
  26688. vertex.x = radius * Math.cos( segment );
  26689. vertex.y = radius * Math.sin( segment );
  26690. vertices.push( vertex.x, vertex.y, vertex.z );
  26691. // normal
  26692. normals.push( 0, 0, 1 );
  26693. // uv
  26694. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26695. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26696. uvs.push( uv.x, uv.y );
  26697. }
  26698. // increase the radius for next row of vertices
  26699. radius += radiusStep;
  26700. }
  26701. // indices
  26702. for ( let j = 0; j < phiSegments; j ++ ) {
  26703. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26704. for ( let i = 0; i < thetaSegments; i ++ ) {
  26705. const segment = i + thetaSegmentLevel;
  26706. const a = segment;
  26707. const b = segment + thetaSegments + 1;
  26708. const c = segment + thetaSegments + 2;
  26709. const d = segment + 1;
  26710. // faces
  26711. indices.push( a, b, d );
  26712. indices.push( b, c, d );
  26713. }
  26714. }
  26715. // build geometry
  26716. this.setIndex( indices );
  26717. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26718. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26719. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26720. }
  26721. copy( source ) {
  26722. super.copy( source );
  26723. this.parameters = Object.assign( {}, source.parameters );
  26724. return this;
  26725. }
  26726. /**
  26727. * Factory method for creating an instance of this class from the given
  26728. * JSON object.
  26729. *
  26730. * @param {Object} data - A JSON object representing the serialized geometry.
  26731. * @return {RingGeometry} A new instance.
  26732. */
  26733. static fromJSON( data ) {
  26734. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26735. }
  26736. }
  26737. /**
  26738. * Creates an one-sided polygonal geometry from one or more path shapes.
  26739. *
  26740. * ```js
  26741. * const arcShape = new THREE.Shape()
  26742. * .moveTo( 5, 1 )
  26743. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26744. *
  26745. * const geometry = new THREE.ShapeGeometry( arcShape );
  26746. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26747. * const mesh = new THREE.Mesh( geometry, material ) ;
  26748. * scene.add( mesh );
  26749. * ```
  26750. *
  26751. * @augments BufferGeometry
  26752. */
  26753. class ShapeGeometry extends BufferGeometry {
  26754. /**
  26755. * Constructs a new shape geometry.
  26756. *
  26757. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26758. * @param {number} [curveSegments=12] - Number of segments per shape.
  26759. */
  26760. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26761. super();
  26762. this.type = 'ShapeGeometry';
  26763. /**
  26764. * Holds the constructor parameters that have been
  26765. * used to generate the geometry. Any modification
  26766. * after instantiation does not change the geometry.
  26767. *
  26768. * @type {Object}
  26769. */
  26770. this.parameters = {
  26771. shapes: shapes,
  26772. curveSegments: curveSegments
  26773. };
  26774. // buffers
  26775. const indices = [];
  26776. const vertices = [];
  26777. const normals = [];
  26778. const uvs = [];
  26779. // helper variables
  26780. let groupStart = 0;
  26781. let groupCount = 0;
  26782. // allow single and array values for "shapes" parameter
  26783. if ( Array.isArray( shapes ) === false ) {
  26784. addShape( shapes );
  26785. } else {
  26786. for ( let i = 0; i < shapes.length; i ++ ) {
  26787. addShape( shapes[ i ] );
  26788. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26789. groupStart += groupCount;
  26790. groupCount = 0;
  26791. }
  26792. }
  26793. // build geometry
  26794. this.setIndex( indices );
  26795. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26796. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26797. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26798. // helper functions
  26799. function addShape( shape ) {
  26800. const indexOffset = vertices.length / 3;
  26801. const points = shape.extractPoints( curveSegments );
  26802. let shapeVertices = points.shape;
  26803. const shapeHoles = points.holes;
  26804. // check direction of vertices
  26805. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26806. shapeVertices = shapeVertices.reverse();
  26807. }
  26808. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26809. const shapeHole = shapeHoles[ i ];
  26810. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26811. shapeHoles[ i ] = shapeHole.reverse();
  26812. }
  26813. }
  26814. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26815. // join vertices of inner and outer paths to a single array
  26816. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26817. const shapeHole = shapeHoles[ i ];
  26818. shapeVertices = shapeVertices.concat( shapeHole );
  26819. }
  26820. // vertices, normals, uvs
  26821. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26822. const vertex = shapeVertices[ i ];
  26823. vertices.push( vertex.x, vertex.y, 0 );
  26824. normals.push( 0, 0, 1 );
  26825. uvs.push( vertex.x, vertex.y ); // world uvs
  26826. }
  26827. // indices
  26828. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26829. const face = faces[ i ];
  26830. const a = face[ 0 ] + indexOffset;
  26831. const b = face[ 1 ] + indexOffset;
  26832. const c = face[ 2 ] + indexOffset;
  26833. indices.push( a, b, c );
  26834. groupCount += 3;
  26835. }
  26836. }
  26837. }
  26838. copy( source ) {
  26839. super.copy( source );
  26840. this.parameters = Object.assign( {}, source.parameters );
  26841. return this;
  26842. }
  26843. toJSON() {
  26844. const data = super.toJSON();
  26845. const shapes = this.parameters.shapes;
  26846. return toJSON( shapes, data );
  26847. }
  26848. /**
  26849. * Factory method for creating an instance of this class from the given
  26850. * JSON object.
  26851. *
  26852. * @param {Object} data - A JSON object representing the serialized geometry.
  26853. * @param {Array<Shape>} shapes - An array of shapes.
  26854. * @return {ShapeGeometry} A new instance.
  26855. */
  26856. static fromJSON( data, shapes ) {
  26857. const geometryShapes = [];
  26858. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26859. const shape = shapes[ data.shapes[ j ] ];
  26860. geometryShapes.push( shape );
  26861. }
  26862. return new ShapeGeometry( geometryShapes, data.curveSegments );
  26863. }
  26864. }
  26865. function toJSON( shapes, data ) {
  26866. data.shapes = [];
  26867. if ( Array.isArray( shapes ) ) {
  26868. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26869. const shape = shapes[ i ];
  26870. data.shapes.push( shape.uuid );
  26871. }
  26872. } else {
  26873. data.shapes.push( shapes.uuid );
  26874. }
  26875. return data;
  26876. }
  26877. /**
  26878. * A class for generating a sphere geometry.
  26879. *
  26880. * ```js
  26881. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  26882. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26883. * const sphere = new THREE.Mesh( geometry, material );
  26884. * scene.add( sphere );
  26885. * ```
  26886. *
  26887. * @augments BufferGeometry
  26888. */
  26889. class SphereGeometry extends BufferGeometry {
  26890. /**
  26891. * Constructs a new sphere geometry.
  26892. *
  26893. * @param {number} [radius=1] - The sphere radius.
  26894. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  26895. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  26896. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  26897. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  26898. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  26899. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  26900. */
  26901. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  26902. super();
  26903. this.type = 'SphereGeometry';
  26904. /**
  26905. * Holds the constructor parameters that have been
  26906. * used to generate the geometry. Any modification
  26907. * after instantiation does not change the geometry.
  26908. *
  26909. * @type {Object}
  26910. */
  26911. this.parameters = {
  26912. radius: radius,
  26913. widthSegments: widthSegments,
  26914. heightSegments: heightSegments,
  26915. phiStart: phiStart,
  26916. phiLength: phiLength,
  26917. thetaStart: thetaStart,
  26918. thetaLength: thetaLength
  26919. };
  26920. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  26921. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  26922. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  26923. let index = 0;
  26924. const grid = [];
  26925. const vertex = new Vector3();
  26926. const normal = new Vector3();
  26927. // buffers
  26928. const indices = [];
  26929. const vertices = [];
  26930. const normals = [];
  26931. const uvs = [];
  26932. // generate vertices, normals and uvs
  26933. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  26934. const verticesRow = [];
  26935. const v = iy / heightSegments;
  26936. // special case for the poles
  26937. let uOffset = 0;
  26938. if ( iy === 0 && thetaStart === 0 ) {
  26939. uOffset = 0.5 / widthSegments;
  26940. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  26941. uOffset = -0.5 / widthSegments;
  26942. }
  26943. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  26944. const u = ix / widthSegments;
  26945. // vertex
  26946. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26947. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  26948. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  26949. vertices.push( vertex.x, vertex.y, vertex.z );
  26950. // normal
  26951. normal.copy( vertex ).normalize();
  26952. normals.push( normal.x, normal.y, normal.z );
  26953. // uv
  26954. uvs.push( u + uOffset, 1 - v );
  26955. verticesRow.push( index ++ );
  26956. }
  26957. grid.push( verticesRow );
  26958. }
  26959. // indices
  26960. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  26961. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  26962. const a = grid[ iy ][ ix + 1 ];
  26963. const b = grid[ iy ][ ix ];
  26964. const c = grid[ iy + 1 ][ ix ];
  26965. const d = grid[ iy + 1 ][ ix + 1 ];
  26966. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  26967. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  26968. }
  26969. }
  26970. // build geometry
  26971. this.setIndex( indices );
  26972. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26973. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26974. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26975. }
  26976. copy( source ) {
  26977. super.copy( source );
  26978. this.parameters = Object.assign( {}, source.parameters );
  26979. return this;
  26980. }
  26981. /**
  26982. * Factory method for creating an instance of this class from the given
  26983. * JSON object.
  26984. *
  26985. * @param {Object} data - A JSON object representing the serialized geometry.
  26986. * @return {SphereGeometry} A new instance.
  26987. */
  26988. static fromJSON( data ) {
  26989. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  26990. }
  26991. }
  26992. /**
  26993. * A geometry class for representing an tetrahedron.
  26994. *
  26995. * ```js
  26996. * const geometry = new THREE.TetrahedronGeometry();
  26997. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26998. * const tetrahedron = new THREE.Mesh( geometry, material );
  26999. * scene.add( tetrahedron );
  27000. * ```
  27001. *
  27002. * @augments PolyhedronGeometry
  27003. */
  27004. class TetrahedronGeometry extends PolyhedronGeometry {
  27005. /**
  27006. * Constructs a new tetrahedron geometry.
  27007. *
  27008. * @param {number} [radius=1] - Radius of the tetrahedron.
  27009. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27010. */
  27011. constructor( radius = 1, detail = 0 ) {
  27012. const vertices = [
  27013. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27014. ];
  27015. const indices = [
  27016. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27017. ];
  27018. super( vertices, indices, radius, detail );
  27019. this.type = 'TetrahedronGeometry';
  27020. /**
  27021. * Holds the constructor parameters that have been
  27022. * used to generate the geometry. Any modification
  27023. * after instantiation does not change the geometry.
  27024. *
  27025. * @type {Object}
  27026. */
  27027. this.parameters = {
  27028. radius: radius,
  27029. detail: detail
  27030. };
  27031. }
  27032. /**
  27033. * Factory method for creating an instance of this class from the given
  27034. * JSON object.
  27035. *
  27036. * @param {Object} data - A JSON object representing the serialized geometry.
  27037. * @return {TetrahedronGeometry} A new instance.
  27038. */
  27039. static fromJSON( data ) {
  27040. return new TetrahedronGeometry( data.radius, data.detail );
  27041. }
  27042. }
  27043. /**
  27044. * A geometry class for representing an torus.
  27045. *
  27046. * ```js
  27047. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27048. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27049. * const torus = new THREE.Mesh( geometry, material );
  27050. * scene.add( torus );
  27051. * ```
  27052. *
  27053. * @augments BufferGeometry
  27054. */
  27055. class TorusGeometry extends BufferGeometry {
  27056. /**
  27057. * Constructs a new torus geometry.
  27058. *
  27059. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27060. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27061. * @param {number} [radialSegments=12] - The number of radial segments.
  27062. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27063. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27064. */
  27065. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27066. super();
  27067. this.type = 'TorusGeometry';
  27068. /**
  27069. * Holds the constructor parameters that have been
  27070. * used to generate the geometry. Any modification
  27071. * after instantiation does not change the geometry.
  27072. *
  27073. * @type {Object}
  27074. */
  27075. this.parameters = {
  27076. radius: radius,
  27077. tube: tube,
  27078. radialSegments: radialSegments,
  27079. tubularSegments: tubularSegments,
  27080. arc: arc
  27081. };
  27082. radialSegments = Math.floor( radialSegments );
  27083. tubularSegments = Math.floor( tubularSegments );
  27084. // buffers
  27085. const indices = [];
  27086. const vertices = [];
  27087. const normals = [];
  27088. const uvs = [];
  27089. // helper variables
  27090. const center = new Vector3();
  27091. const vertex = new Vector3();
  27092. const normal = new Vector3();
  27093. // generate vertices, normals and uvs
  27094. for ( let j = 0; j <= radialSegments; j ++ ) {
  27095. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27096. const u = i / tubularSegments * arc;
  27097. const v = j / radialSegments * Math.PI * 2;
  27098. // vertex
  27099. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27100. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27101. vertex.z = tube * Math.sin( v );
  27102. vertices.push( vertex.x, vertex.y, vertex.z );
  27103. // normal
  27104. center.x = radius * Math.cos( u );
  27105. center.y = radius * Math.sin( u );
  27106. normal.subVectors( vertex, center ).normalize();
  27107. normals.push( normal.x, normal.y, normal.z );
  27108. // uv
  27109. uvs.push( i / tubularSegments );
  27110. uvs.push( j / radialSegments );
  27111. }
  27112. }
  27113. // generate indices
  27114. for ( let j = 1; j <= radialSegments; j ++ ) {
  27115. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27116. // indices
  27117. const a = ( tubularSegments + 1 ) * j + i - 1;
  27118. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27119. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27120. const d = ( tubularSegments + 1 ) * j + i;
  27121. // faces
  27122. indices.push( a, b, d );
  27123. indices.push( b, c, d );
  27124. }
  27125. }
  27126. // build geometry
  27127. this.setIndex( indices );
  27128. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27129. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27130. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27131. }
  27132. copy( source ) {
  27133. super.copy( source );
  27134. this.parameters = Object.assign( {}, source.parameters );
  27135. return this;
  27136. }
  27137. /**
  27138. * Factory method for creating an instance of this class from the given
  27139. * JSON object.
  27140. *
  27141. * @param {Object} data - A JSON object representing the serialized geometry.
  27142. * @return {TorusGeometry} A new instance.
  27143. */
  27144. static fromJSON( data ) {
  27145. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27146. }
  27147. }
  27148. /**
  27149. * Creates a torus knot, the particular shape of which is defined by a pair
  27150. * of coprime integers, p and q. If p and q are not coprime, the result will
  27151. * be a torus link.
  27152. *
  27153. * ```js
  27154. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27155. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27156. * const torusKnot = new THREE.Mesh( geometry, material );
  27157. * scene.add( torusKnot );
  27158. * ```
  27159. *
  27160. * @augments BufferGeometry
  27161. */
  27162. class TorusKnotGeometry extends BufferGeometry {
  27163. /**
  27164. * Constructs a new torus knot geometry.
  27165. *
  27166. * @param {number} [radius=1] - Radius of the torus knot.
  27167. * @param {number} [tube=0.4] - Radius of the tube.
  27168. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27169. * @param {number} [radialSegments=8] - The number of radial segments.
  27170. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27171. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27172. */
  27173. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27174. super();
  27175. this.type = 'TorusKnotGeometry';
  27176. /**
  27177. * Holds the constructor parameters that have been
  27178. * used to generate the geometry. Any modification
  27179. * after instantiation does not change the geometry.
  27180. *
  27181. * @type {Object}
  27182. */
  27183. this.parameters = {
  27184. radius: radius,
  27185. tube: tube,
  27186. tubularSegments: tubularSegments,
  27187. radialSegments: radialSegments,
  27188. p: p,
  27189. q: q
  27190. };
  27191. tubularSegments = Math.floor( tubularSegments );
  27192. radialSegments = Math.floor( radialSegments );
  27193. // buffers
  27194. const indices = [];
  27195. const vertices = [];
  27196. const normals = [];
  27197. const uvs = [];
  27198. // helper variables
  27199. const vertex = new Vector3();
  27200. const normal = new Vector3();
  27201. const P1 = new Vector3();
  27202. const P2 = new Vector3();
  27203. const B = new Vector3();
  27204. const T = new Vector3();
  27205. const N = new Vector3();
  27206. // generate vertices, normals and uvs
  27207. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27208. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27209. const u = i / tubularSegments * p * Math.PI * 2;
  27210. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27211. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27212. calculatePositionOnCurve( u, p, q, radius, P1 );
  27213. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27214. // calculate orthonormal basis
  27215. T.subVectors( P2, P1 );
  27216. N.addVectors( P2, P1 );
  27217. B.crossVectors( T, N );
  27218. N.crossVectors( B, T );
  27219. // normalize B, N. T can be ignored, we don't use it
  27220. B.normalize();
  27221. N.normalize();
  27222. for ( let j = 0; j <= radialSegments; ++ j ) {
  27223. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27224. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27225. const v = j / radialSegments * Math.PI * 2;
  27226. const cx = - tube * Math.cos( v );
  27227. const cy = tube * Math.sin( v );
  27228. // now calculate the final vertex position.
  27229. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27230. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27231. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27232. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27233. vertices.push( vertex.x, vertex.y, vertex.z );
  27234. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27235. normal.subVectors( vertex, P1 ).normalize();
  27236. normals.push( normal.x, normal.y, normal.z );
  27237. // uv
  27238. uvs.push( i / tubularSegments );
  27239. uvs.push( j / radialSegments );
  27240. }
  27241. }
  27242. // generate indices
  27243. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27244. for ( let i = 1; i <= radialSegments; i ++ ) {
  27245. // indices
  27246. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27247. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27248. const c = ( radialSegments + 1 ) * j + i;
  27249. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27250. // faces
  27251. indices.push( a, b, d );
  27252. indices.push( b, c, d );
  27253. }
  27254. }
  27255. // build geometry
  27256. this.setIndex( indices );
  27257. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27258. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27259. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27260. // this function calculates the current position on the torus curve
  27261. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27262. const cu = Math.cos( u );
  27263. const su = Math.sin( u );
  27264. const quOverP = q / p * u;
  27265. const cs = Math.cos( quOverP );
  27266. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27267. position.y = radius * ( 2 + cs ) * su * 0.5;
  27268. position.z = radius * Math.sin( quOverP ) * 0.5;
  27269. }
  27270. }
  27271. copy( source ) {
  27272. super.copy( source );
  27273. this.parameters = Object.assign( {}, source.parameters );
  27274. return this;
  27275. }
  27276. /**
  27277. * Factory method for creating an instance of this class from the given
  27278. * JSON object.
  27279. *
  27280. * @param {Object} data - A JSON object representing the serialized geometry.
  27281. * @return {TorusKnotGeometry} A new instance.
  27282. */
  27283. static fromJSON( data ) {
  27284. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27285. }
  27286. }
  27287. /**
  27288. * Creates a tube that extrudes along a 3D curve.
  27289. *
  27290. * ```js
  27291. * class CustomSinCurve extends THREE.Curve {
  27292. *
  27293. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27294. *
  27295. * const tx = t * 3 - 1.5;
  27296. * const ty = Math.sin( 2 * Math.PI * t );
  27297. * const tz = 0;
  27298. *
  27299. * return optionalTarget.set( tx, ty, tz );
  27300. * }
  27301. *
  27302. * }
  27303. *
  27304. * const path = new CustomSinCurve( 10 );
  27305. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27306. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27307. * const mesh = new THREE.Mesh( geometry, material );
  27308. * scene.add( mesh );
  27309. * ```
  27310. *
  27311. * @augments BufferGeometry
  27312. */
  27313. class TubeGeometry extends BufferGeometry {
  27314. /**
  27315. * Constructs a new tube geometry.
  27316. *
  27317. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27318. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27319. * @param {number} [radius=1] -The radius of the tube.
  27320. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27321. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27322. */
  27323. 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 ) {
  27324. super();
  27325. this.type = 'TubeGeometry';
  27326. /**
  27327. * Holds the constructor parameters that have been
  27328. * used to generate the geometry. Any modification
  27329. * after instantiation does not change the geometry.
  27330. *
  27331. * @type {Object}
  27332. */
  27333. this.parameters = {
  27334. path: path,
  27335. tubularSegments: tubularSegments,
  27336. radius: radius,
  27337. radialSegments: radialSegments,
  27338. closed: closed
  27339. };
  27340. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27341. // expose internals
  27342. this.tangents = frames.tangents;
  27343. this.normals = frames.normals;
  27344. this.binormals = frames.binormals;
  27345. // helper variables
  27346. const vertex = new Vector3();
  27347. const normal = new Vector3();
  27348. const uv = new Vector2();
  27349. let P = new Vector3();
  27350. // buffer
  27351. const vertices = [];
  27352. const normals = [];
  27353. const uvs = [];
  27354. const indices = [];
  27355. // create buffer data
  27356. generateBufferData();
  27357. // build geometry
  27358. this.setIndex( indices );
  27359. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27360. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27361. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27362. // functions
  27363. function generateBufferData() {
  27364. for ( let i = 0; i < tubularSegments; i ++ ) {
  27365. generateSegment( i );
  27366. }
  27367. // if the geometry is not closed, generate the last row of vertices and normals
  27368. // at the regular position on the given path
  27369. //
  27370. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27371. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27372. // uvs are generated in a separate function.
  27373. // this makes it easy compute correct values for closed geometries
  27374. generateUVs();
  27375. // finally create faces
  27376. generateIndices();
  27377. }
  27378. function generateSegment( i ) {
  27379. // we use getPointAt to sample evenly distributed points from the given path
  27380. P = path.getPointAt( i / tubularSegments, P );
  27381. // retrieve corresponding normal and binormal
  27382. const N = frames.normals[ i ];
  27383. const B = frames.binormals[ i ];
  27384. // generate normals and vertices for the current segment
  27385. for ( let j = 0; j <= radialSegments; j ++ ) {
  27386. const v = j / radialSegments * Math.PI * 2;
  27387. const sin = Math.sin( v );
  27388. const cos = - Math.cos( v );
  27389. // normal
  27390. normal.x = ( cos * N.x + sin * B.x );
  27391. normal.y = ( cos * N.y + sin * B.y );
  27392. normal.z = ( cos * N.z + sin * B.z );
  27393. normal.normalize();
  27394. normals.push( normal.x, normal.y, normal.z );
  27395. // vertex
  27396. vertex.x = P.x + radius * normal.x;
  27397. vertex.y = P.y + radius * normal.y;
  27398. vertex.z = P.z + radius * normal.z;
  27399. vertices.push( vertex.x, vertex.y, vertex.z );
  27400. }
  27401. }
  27402. function generateIndices() {
  27403. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27404. for ( let i = 1; i <= radialSegments; i ++ ) {
  27405. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27406. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27407. const c = ( radialSegments + 1 ) * j + i;
  27408. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27409. // faces
  27410. indices.push( a, b, d );
  27411. indices.push( b, c, d );
  27412. }
  27413. }
  27414. }
  27415. function generateUVs() {
  27416. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27417. for ( let j = 0; j <= radialSegments; j ++ ) {
  27418. uv.x = i / tubularSegments;
  27419. uv.y = j / radialSegments;
  27420. uvs.push( uv.x, uv.y );
  27421. }
  27422. }
  27423. }
  27424. }
  27425. copy( source ) {
  27426. super.copy( source );
  27427. this.parameters = Object.assign( {}, source.parameters );
  27428. return this;
  27429. }
  27430. toJSON() {
  27431. const data = super.toJSON();
  27432. data.path = this.parameters.path.toJSON();
  27433. return data;
  27434. }
  27435. /**
  27436. * Factory method for creating an instance of this class from the given
  27437. * JSON object.
  27438. *
  27439. * @param {Object} data - A JSON object representing the serialized geometry.
  27440. * @return {TubeGeometry} A new instance.
  27441. */
  27442. static fromJSON( data ) {
  27443. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27444. // User defined curves or instances of CurvePath will not be deserialized.
  27445. return new TubeGeometry(
  27446. new Curves[ data.path.type ]().fromJSON( data.path ),
  27447. data.tubularSegments,
  27448. data.radius,
  27449. data.radialSegments,
  27450. data.closed
  27451. );
  27452. }
  27453. }
  27454. /**
  27455. * Can be used as a helper object to visualize a geometry as a wireframe.
  27456. *
  27457. * ```js
  27458. * const geometry = new THREE.SphereGeometry();
  27459. *
  27460. * const wireframe = new THREE.WireframeGeometry( geometry );
  27461. *
  27462. * const line = new THREE.LineSegments( wireframe );
  27463. * line.material.depthWrite = false;
  27464. * line.material.opacity = 0.25;
  27465. * line.material.transparent = true;
  27466. *
  27467. * scene.add( line );
  27468. * ```
  27469. *
  27470. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27471. *
  27472. * @augments BufferGeometry
  27473. */
  27474. class WireframeGeometry extends BufferGeometry {
  27475. /**
  27476. * Constructs a new wireframe geometry.
  27477. *
  27478. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27479. */
  27480. constructor( geometry = null ) {
  27481. super();
  27482. this.type = 'WireframeGeometry';
  27483. /**
  27484. * Holds the constructor parameters that have been
  27485. * used to generate the geometry. Any modification
  27486. * after instantiation does not change the geometry.
  27487. *
  27488. * @type {Object}
  27489. */
  27490. this.parameters = {
  27491. geometry: geometry
  27492. };
  27493. if ( geometry !== null ) {
  27494. // buffer
  27495. const vertices = [];
  27496. const edges = new Set();
  27497. // helper variables
  27498. const start = new Vector3();
  27499. const end = new Vector3();
  27500. if ( geometry.index !== null ) {
  27501. // indexed BufferGeometry
  27502. const position = geometry.attributes.position;
  27503. const indices = geometry.index;
  27504. let groups = geometry.groups;
  27505. if ( groups.length === 0 ) {
  27506. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27507. }
  27508. // create a data structure that contains all edges without duplicates
  27509. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27510. const group = groups[ o ];
  27511. const groupStart = group.start;
  27512. const groupCount = group.count;
  27513. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27514. for ( let j = 0; j < 3; j ++ ) {
  27515. const index1 = indices.getX( i + j );
  27516. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27517. start.fromBufferAttribute( position, index1 );
  27518. end.fromBufferAttribute( position, index2 );
  27519. if ( isUniqueEdge( start, end, edges ) === true ) {
  27520. vertices.push( start.x, start.y, start.z );
  27521. vertices.push( end.x, end.y, end.z );
  27522. }
  27523. }
  27524. }
  27525. }
  27526. } else {
  27527. // non-indexed BufferGeometry
  27528. const position = geometry.attributes.position;
  27529. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27530. for ( let j = 0; j < 3; j ++ ) {
  27531. // three edges per triangle, an edge is represented as (index1, index2)
  27532. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27533. const index1 = 3 * i + j;
  27534. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27535. start.fromBufferAttribute( position, index1 );
  27536. end.fromBufferAttribute( position, index2 );
  27537. if ( isUniqueEdge( start, end, edges ) === true ) {
  27538. vertices.push( start.x, start.y, start.z );
  27539. vertices.push( end.x, end.y, end.z );
  27540. }
  27541. }
  27542. }
  27543. }
  27544. // build geometry
  27545. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27546. }
  27547. }
  27548. copy( source ) {
  27549. super.copy( source );
  27550. this.parameters = Object.assign( {}, source.parameters );
  27551. return this;
  27552. }
  27553. }
  27554. function isUniqueEdge( start, end, edges ) {
  27555. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27556. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27557. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27558. return false;
  27559. } else {
  27560. edges.add( hash1 );
  27561. edges.add( hash2 );
  27562. return true;
  27563. }
  27564. }
  27565. var Geometries = /*#__PURE__*/Object.freeze({
  27566. __proto__: null,
  27567. BoxGeometry: BoxGeometry,
  27568. CapsuleGeometry: CapsuleGeometry,
  27569. CircleGeometry: CircleGeometry,
  27570. ConeGeometry: ConeGeometry,
  27571. CylinderGeometry: CylinderGeometry,
  27572. DodecahedronGeometry: DodecahedronGeometry,
  27573. EdgesGeometry: EdgesGeometry,
  27574. ExtrudeGeometry: ExtrudeGeometry,
  27575. IcosahedronGeometry: IcosahedronGeometry,
  27576. LatheGeometry: LatheGeometry,
  27577. OctahedronGeometry: OctahedronGeometry,
  27578. PlaneGeometry: PlaneGeometry,
  27579. PolyhedronGeometry: PolyhedronGeometry,
  27580. RingGeometry: RingGeometry,
  27581. ShapeGeometry: ShapeGeometry,
  27582. SphereGeometry: SphereGeometry,
  27583. TetrahedronGeometry: TetrahedronGeometry,
  27584. TorusGeometry: TorusGeometry,
  27585. TorusKnotGeometry: TorusKnotGeometry,
  27586. TubeGeometry: TubeGeometry,
  27587. WireframeGeometry: WireframeGeometry
  27588. });
  27589. /**
  27590. * This material can receive shadows, but otherwise is completely transparent.
  27591. *
  27592. * ```js
  27593. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27594. * geometry.rotateX( - Math.PI / 2 );
  27595. *
  27596. * const material = new THREE.ShadowMaterial();
  27597. * material.opacity = 0.2;
  27598. *
  27599. * const plane = new THREE.Mesh( geometry, material );
  27600. * plane.position.y = -200;
  27601. * plane.receiveShadow = true;
  27602. * scene.add( plane );
  27603. * ```
  27604. *
  27605. * @augments Material
  27606. */
  27607. class ShadowMaterial extends Material {
  27608. /**
  27609. * Constructs a new shadow material.
  27610. *
  27611. * @param {Object} [parameters] - An object with one or more properties
  27612. * defining the material's appearance. Any property of the material
  27613. * (including any property from inherited materials) can be passed
  27614. * in here. Color values can be passed any type of value accepted
  27615. * by {@link Color#set}.
  27616. */
  27617. constructor( parameters ) {
  27618. super();
  27619. /**
  27620. * This flag can be used for type testing.
  27621. *
  27622. * @type {boolean}
  27623. * @readonly
  27624. * @default true
  27625. */
  27626. this.isShadowMaterial = true;
  27627. this.type = 'ShadowMaterial';
  27628. /**
  27629. * Color of the material.
  27630. *
  27631. * @type {Color}
  27632. * @default (0,0,0)
  27633. */
  27634. this.color = new Color( 0x000000 );
  27635. /**
  27636. * Overwritten since shadow materials are transparent
  27637. * by default.
  27638. *
  27639. * @type {boolean}
  27640. * @default true
  27641. */
  27642. this.transparent = true;
  27643. /**
  27644. * Whether the material is affected by fog or not.
  27645. *
  27646. * @type {boolean}
  27647. * @default true
  27648. */
  27649. this.fog = true;
  27650. this.setValues( parameters );
  27651. }
  27652. copy( source ) {
  27653. super.copy( source );
  27654. this.color.copy( source.color );
  27655. this.fog = source.fog;
  27656. return this;
  27657. }
  27658. }
  27659. /**
  27660. * This class works just like {@link ShaderMaterial}, except that definitions
  27661. * of built-in uniforms and attributes are not automatically prepended to the
  27662. * GLSL shader code.
  27663. *
  27664. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27665. *
  27666. * @augments ShaderMaterial
  27667. */
  27668. class RawShaderMaterial extends ShaderMaterial {
  27669. /**
  27670. * Constructs a new raw shader material.
  27671. *
  27672. * @param {Object} [parameters] - An object with one or more properties
  27673. * defining the material's appearance. Any property of the material
  27674. * (including any property from inherited materials) can be passed
  27675. * in here. Color values can be passed any type of value accepted
  27676. * by {@link Color#set}.
  27677. */
  27678. constructor( parameters ) {
  27679. super( parameters );
  27680. /**
  27681. * This flag can be used for type testing.
  27682. *
  27683. * @type {boolean}
  27684. * @readonly
  27685. * @default true
  27686. */
  27687. this.isRawShaderMaterial = true;
  27688. this.type = 'RawShaderMaterial';
  27689. }
  27690. }
  27691. /**
  27692. * A standard physically based material, using Metallic-Roughness workflow.
  27693. *
  27694. * Physically based rendering (PBR) has recently become the standard in many
  27695. * 3D applications, such as [Unity]{@link https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/},
  27696. * [Unreal]{@link https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/} and
  27697. * [3D Studio Max]{@link http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017}.
  27698. *
  27699. * This approach differs from older approaches in that instead of using
  27700. * approximations for the way in which light interacts with a surface, a
  27701. * physically correct model is used. The idea is that, instead of tweaking
  27702. * materials to look good under specific lighting, a material can be created
  27703. * that will react 'correctly' under all lighting scenarios.
  27704. *
  27705. * In practice this gives a more accurate and realistic looking result than
  27706. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27707. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27708. * shading.
  27709. *
  27710. * Note that for best results you should always specify an environment map when using this material.
  27711. *
  27712. * For a non-technical introduction to the concept of PBR and how to set up a
  27713. * PBR material, check out these articles by the people at [marmoset]{@link https://www.marmoset.co}:
  27714. *
  27715. * - [Basic Theory of Physically Based Rendering]{@link https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/}
  27716. * - [Physically Based Rendering and You Can Too]{@link https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/}
  27717. *
  27718. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27719. * [paper from Disney]{@link https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf}
  27720. * (pdf), by Brent Burley.
  27721. *
  27722. * @augments Material
  27723. */
  27724. class MeshStandardMaterial extends Material {
  27725. /**
  27726. * Constructs a new mesh standard material.
  27727. *
  27728. * @param {Object} [parameters] - An object with one or more properties
  27729. * defining the material's appearance. Any property of the material
  27730. * (including any property from inherited materials) can be passed
  27731. * in here. Color values can be passed any type of value accepted
  27732. * by {@link Color#set}.
  27733. */
  27734. constructor( parameters ) {
  27735. super();
  27736. /**
  27737. * This flag can be used for type testing.
  27738. *
  27739. * @type {boolean}
  27740. * @readonly
  27741. * @default true
  27742. */
  27743. this.isMeshStandardMaterial = true;
  27744. this.type = 'MeshStandardMaterial';
  27745. this.defines = { 'STANDARD': '' };
  27746. /**
  27747. * Color of the material.
  27748. *
  27749. * @type {Color}
  27750. * @default (1,1,1)
  27751. */
  27752. this.color = new Color( 0xffffff ); // diffuse
  27753. /**
  27754. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27755. * means fully diffuse. If `roughnessMap` is also provided,
  27756. * both values are multiplied.
  27757. *
  27758. * @type {number}
  27759. * @default 1
  27760. */
  27761. this.roughness = 1.0;
  27762. /**
  27763. * How much the material is like a metal. Non-metallic materials such as wood
  27764. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27765. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27766. * If `metalnessMap` is also provided, both values are multiplied.
  27767. *
  27768. * @type {number}
  27769. * @default 0
  27770. */
  27771. this.metalness = 0.0;
  27772. /**
  27773. * The color map. May optionally include an alpha channel, typically combined
  27774. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27775. * color is modulated by the diffuse `color`.
  27776. *
  27777. * @type {?Texture}
  27778. * @default null
  27779. */
  27780. this.map = null;
  27781. /**
  27782. * The light map. Requires a second set of UVs.
  27783. *
  27784. * @type {?Texture}
  27785. * @default null
  27786. */
  27787. this.lightMap = null;
  27788. /**
  27789. * Intensity of the baked light.
  27790. *
  27791. * @type {number}
  27792. * @default 1
  27793. */
  27794. this.lightMapIntensity = 1.0;
  27795. /**
  27796. * The red channel of this texture is used as the ambient occlusion map.
  27797. * Requires a second set of UVs.
  27798. *
  27799. * @type {?Texture}
  27800. * @default null
  27801. */
  27802. this.aoMap = null;
  27803. /**
  27804. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27805. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27806. * red channel is also `1`, ambient light is fully occluded on a surface.
  27807. *
  27808. * @type {number}
  27809. * @default 1
  27810. */
  27811. this.aoMapIntensity = 1.0;
  27812. /**
  27813. * Emissive (light) color of the material, essentially a solid color
  27814. * unaffected by other lighting.
  27815. *
  27816. * @type {Color}
  27817. * @default (0,0,0)
  27818. */
  27819. this.emissive = new Color( 0x000000 );
  27820. /**
  27821. * Intensity of the emissive light. Modulates the emissive color.
  27822. *
  27823. * @type {number}
  27824. * @default 1
  27825. */
  27826. this.emissiveIntensity = 1.0;
  27827. /**
  27828. * Set emissive (glow) map. The emissive map color is modulated by the
  27829. * emissive color and the emissive intensity. If you have an emissive map,
  27830. * be sure to set the emissive color to something other than black.
  27831. *
  27832. * @type {?Texture}
  27833. * @default null
  27834. */
  27835. this.emissiveMap = null;
  27836. /**
  27837. * The texture to create a bump map. The black and white values map to the
  27838. * perceived depth in relation to the lights. Bump doesn't actually affect
  27839. * the geometry of the object, only the lighting. If a normal map is defined
  27840. * this will be ignored.
  27841. *
  27842. * @type {?Texture}
  27843. * @default null
  27844. */
  27845. this.bumpMap = null;
  27846. /**
  27847. * How much the bump map affects the material. Typical range is `[0,1]`.
  27848. *
  27849. * @type {number}
  27850. * @default 1
  27851. */
  27852. this.bumpScale = 1;
  27853. /**
  27854. * The texture to create a normal map. The RGB values affect the surface
  27855. * normal for each pixel fragment and change the way the color is lit. Normal
  27856. * maps do not change the actual shape of the surface, only the lighting. In
  27857. * case the material has a normal map authored using the left handed
  27858. * convention, the `y` component of `normalScale` should be negated to compensate
  27859. * for the different handedness.
  27860. *
  27861. * @type {?Texture}
  27862. * @default null
  27863. */
  27864. this.normalMap = null;
  27865. /**
  27866. * The type of normal map.
  27867. *
  27868. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  27869. * @default TangentSpaceNormalMap
  27870. */
  27871. this.normalMapType = TangentSpaceNormalMap;
  27872. /**
  27873. * How much the normal map affects the material. Typical value range is `[0,1]`.
  27874. *
  27875. * @type {Vector2}
  27876. * @default (1,1)
  27877. */
  27878. this.normalScale = new Vector2( 1, 1 );
  27879. /**
  27880. * The displacement map affects the position of the mesh's vertices. Unlike
  27881. * other maps which only affect the light and shade of the material the
  27882. * displaced vertices can cast shadows, block other objects, and otherwise
  27883. * act as real geometry. The displacement texture is an image where the value
  27884. * of each pixel (white being the highest) is mapped against, and
  27885. * repositions, the vertices of the mesh.
  27886. *
  27887. * @type {?Texture}
  27888. * @default null
  27889. */
  27890. this.displacementMap = null;
  27891. /**
  27892. * How much the displacement map affects the mesh (where black is no
  27893. * displacement, and white is maximum displacement). Without a displacement
  27894. * map set, this value is not applied.
  27895. *
  27896. * @type {number}
  27897. * @default 0
  27898. */
  27899. this.displacementScale = 1;
  27900. /**
  27901. * The offset of the displacement map's values on the mesh's vertices.
  27902. * The bias is added to the scaled sample of the displacement map.
  27903. * Without a displacement map set, this value is not applied.
  27904. *
  27905. * @type {number}
  27906. * @default 0
  27907. */
  27908. this.displacementBias = 0;
  27909. /**
  27910. * The green channel of this texture is used to alter the roughness of the
  27911. * material.
  27912. *
  27913. * @type {?Texture}
  27914. * @default null
  27915. */
  27916. this.roughnessMap = null;
  27917. /**
  27918. * The blue channel of this texture is used to alter the metalness of the
  27919. * material.
  27920. *
  27921. * @type {?Texture}
  27922. * @default null
  27923. */
  27924. this.metalnessMap = null;
  27925. /**
  27926. * The alpha map is a grayscale texture that controls the opacity across the
  27927. * surface (black: fully transparent; white: fully opaque).
  27928. *
  27929. * Only the color of the texture is used, ignoring the alpha channel if one
  27930. * exists. For RGB and RGBA textures, the renderer will use the green channel
  27931. * when sampling this texture due to the extra bit of precision provided for
  27932. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  27933. * luminance/alpha textures will also still work as expected.
  27934. *
  27935. * @type {?Texture}
  27936. * @default null
  27937. */
  27938. this.alphaMap = null;
  27939. /**
  27940. * The environment map. To ensure a physically correct rendering, environment maps
  27941. * are internally pre-processed with {@link PMREMGenerator}.
  27942. *
  27943. * @type {?Texture}
  27944. * @default null
  27945. */
  27946. this.envMap = null;
  27947. /**
  27948. * The rotation of the environment map in radians.
  27949. *
  27950. * @type {Euler}
  27951. * @default (0,0,0)
  27952. */
  27953. this.envMapRotation = new Euler();
  27954. /**
  27955. * Scales the effect of the environment map by multiplying its color.
  27956. *
  27957. * @type {number}
  27958. * @default 1
  27959. */
  27960. this.envMapIntensity = 1.0;
  27961. /**
  27962. * Renders the geometry as a wireframe.
  27963. *
  27964. * @type {boolean}
  27965. * @default false
  27966. */
  27967. this.wireframe = false;
  27968. /**
  27969. * Controls the thickness of the wireframe.
  27970. *
  27971. * Can only be used with {@link SVGRenderer}.
  27972. *
  27973. * @type {number}
  27974. * @default 1
  27975. */
  27976. this.wireframeLinewidth = 1;
  27977. /**
  27978. * Defines appearance of wireframe ends.
  27979. *
  27980. * Can only be used with {@link SVGRenderer}.
  27981. *
  27982. * @type {('round'|'bevel'|'miter')}
  27983. * @default 'round'
  27984. */
  27985. this.wireframeLinecap = 'round';
  27986. /**
  27987. * Defines appearance of wireframe joints.
  27988. *
  27989. * Can only be used with {@link SVGRenderer}.
  27990. *
  27991. * @type {('round'|'bevel'|'miter')}
  27992. * @default 'round'
  27993. */
  27994. this.wireframeLinejoin = 'round';
  27995. /**
  27996. * Whether the material is rendered with flat shading or not.
  27997. *
  27998. * @type {boolean}
  27999. * @default false
  28000. */
  28001. this.flatShading = false;
  28002. /**
  28003. * Whether the material is affected by fog or not.
  28004. *
  28005. * @type {boolean}
  28006. * @default true
  28007. */
  28008. this.fog = true;
  28009. this.setValues( parameters );
  28010. }
  28011. copy( source ) {
  28012. super.copy( source );
  28013. this.defines = { 'STANDARD': '' };
  28014. this.color.copy( source.color );
  28015. this.roughness = source.roughness;
  28016. this.metalness = source.metalness;
  28017. this.map = source.map;
  28018. this.lightMap = source.lightMap;
  28019. this.lightMapIntensity = source.lightMapIntensity;
  28020. this.aoMap = source.aoMap;
  28021. this.aoMapIntensity = source.aoMapIntensity;
  28022. this.emissive.copy( source.emissive );
  28023. this.emissiveMap = source.emissiveMap;
  28024. this.emissiveIntensity = source.emissiveIntensity;
  28025. this.bumpMap = source.bumpMap;
  28026. this.bumpScale = source.bumpScale;
  28027. this.normalMap = source.normalMap;
  28028. this.normalMapType = source.normalMapType;
  28029. this.normalScale.copy( source.normalScale );
  28030. this.displacementMap = source.displacementMap;
  28031. this.displacementScale = source.displacementScale;
  28032. this.displacementBias = source.displacementBias;
  28033. this.roughnessMap = source.roughnessMap;
  28034. this.metalnessMap = source.metalnessMap;
  28035. this.alphaMap = source.alphaMap;
  28036. this.envMap = source.envMap;
  28037. this.envMapRotation.copy( source.envMapRotation );
  28038. this.envMapIntensity = source.envMapIntensity;
  28039. this.wireframe = source.wireframe;
  28040. this.wireframeLinewidth = source.wireframeLinewidth;
  28041. this.wireframeLinecap = source.wireframeLinecap;
  28042. this.wireframeLinejoin = source.wireframeLinejoin;
  28043. this.flatShading = source.flatShading;
  28044. this.fog = source.fog;
  28045. return this;
  28046. }
  28047. }
  28048. /**
  28049. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28050. * physically-based rendering properties:
  28051. *
  28052. * - Anisotropy: Ability to represent the anisotropic property of materials
  28053. * as observable with brushed metals.
  28054. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28055. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28056. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28057. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28058. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28059. * wings of many insects.
  28060. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28061. * transparent materials are less reflective. Physically-based transmission provides a more
  28062. * realistic option for thin, transparent surfaces like glass.
  28063. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28064. * - Sheen: Can be used for representing cloth and fabric materials.
  28065. *
  28066. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28067. * higher performance cost, per pixel, than other three.js materials. Most
  28068. * effects are disabled by default, and add cost as they are enabled. For
  28069. * best results, always specify an environment map when using this material.
  28070. *
  28071. * @augments MeshStandardMaterial
  28072. */
  28073. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28074. /**
  28075. * Constructs a new mesh physical material.
  28076. *
  28077. * @param {Object} [parameters] - An object with one or more properties
  28078. * defining the material's appearance. Any property of the material
  28079. * (including any property from inherited materials) can be passed
  28080. * in here. Color values can be passed any type of value accepted
  28081. * by {@link Color#set}.
  28082. */
  28083. constructor( parameters ) {
  28084. super();
  28085. /**
  28086. * This flag can be used for type testing.
  28087. *
  28088. * @type {boolean}
  28089. * @readonly
  28090. * @default true
  28091. */
  28092. this.isMeshPhysicalMaterial = true;
  28093. this.defines = {
  28094. 'STANDARD': '',
  28095. 'PHYSICAL': ''
  28096. };
  28097. this.type = 'MeshPhysicalMaterial';
  28098. /**
  28099. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28100. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28101. * property provides additional rotation to the vectors in the texture.
  28102. *
  28103. * @type {number}
  28104. * @default 1
  28105. */
  28106. this.anisotropyRotation = 0;
  28107. /**
  28108. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28109. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28110. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28111. *
  28112. * @type {?Texture}
  28113. * @default null
  28114. */
  28115. this.anisotropyMap = null;
  28116. /**
  28117. * The red channel of this texture is multiplied against `clearcoat`,
  28118. * for per-pixel control over a coating's intensity.
  28119. *
  28120. * @type {?Texture}
  28121. * @default null
  28122. */
  28123. this.clearcoatMap = null;
  28124. /**
  28125. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28126. *
  28127. * @type {number}
  28128. * @default 0
  28129. */
  28130. this.clearcoatRoughness = 0.0;
  28131. /**
  28132. * The green channel of this texture is multiplied against
  28133. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28134. *
  28135. * @type {?Texture}
  28136. * @default null
  28137. */
  28138. this.clearcoatRoughnessMap = null;
  28139. /**
  28140. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28141. * `(0,0)` to `(1,1)`.
  28142. *
  28143. * @type {Vector2}
  28144. * @default (1,1)
  28145. */
  28146. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28147. /**
  28148. * Can be used to enable independent normals for the clear coat layer.
  28149. *
  28150. * @type {?Texture}
  28151. * @default null
  28152. */
  28153. this.clearcoatNormalMap = null;
  28154. /**
  28155. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28156. *
  28157. * @type {number}
  28158. * @default 1.5
  28159. */
  28160. this.ior = 1.5;
  28161. /**
  28162. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28163. * corresponds to an index-of-refraction of `1.5`.
  28164. *
  28165. * This models the reflectivity of non-metallic materials. It has no effect
  28166. * when `metalness` is `1.0`
  28167. *
  28168. * @name MeshPhysicalMaterial#reflectivity
  28169. * @type {number}
  28170. * @default 0.5
  28171. */
  28172. Object.defineProperty( this, 'reflectivity', {
  28173. get: function () {
  28174. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28175. },
  28176. set: function ( reflectivity ) {
  28177. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28178. }
  28179. } );
  28180. /**
  28181. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28182. * control over iridescence.
  28183. *
  28184. * @type {?Texture}
  28185. * @default null
  28186. */
  28187. this.iridescenceMap = null;
  28188. /**
  28189. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28190. * Between `1.0` to `2.333`.
  28191. *
  28192. * @type {number}
  28193. * @default 1.3
  28194. */
  28195. this.iridescenceIOR = 1.3;
  28196. /**
  28197. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28198. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28199. *
  28200. * @type {Array<number,number>}
  28201. * @default [100,400]
  28202. */
  28203. this.iridescenceThicknessRange = [ 100, 400 ];
  28204. /**
  28205. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28206. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28207. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28208. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28209. * - Values in-between will linearly interpolate between the elements of the array.
  28210. *
  28211. * @type {?Texture}
  28212. * @default null
  28213. */
  28214. this.iridescenceThicknessMap = null;
  28215. /**
  28216. * The sheen tint.
  28217. *
  28218. * @type {Color}
  28219. * @default (0,0,0)
  28220. */
  28221. this.sheenColor = new Color( 0x000000 );
  28222. /**
  28223. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28224. * over sheen tint.
  28225. *
  28226. * @type {?Texture}
  28227. * @default null
  28228. */
  28229. this.sheenColorMap = null;
  28230. /**
  28231. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28232. *
  28233. * @type {number}
  28234. * @default 1
  28235. */
  28236. this.sheenRoughness = 1.0;
  28237. /**
  28238. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28239. * over sheen roughness.
  28240. *
  28241. * @type {?Texture}
  28242. * @default null
  28243. */
  28244. this.sheenRoughnessMap = null;
  28245. /**
  28246. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28247. * optical transparency.
  28248. *
  28249. * @type {?Texture}
  28250. * @default null
  28251. */
  28252. this.transmissionMap = null;
  28253. /**
  28254. * The thickness of the volume beneath the surface. The value is given in the
  28255. * coordinate space of the mesh. If the value is `0` the material is
  28256. * thin-walled. Otherwise the material is a volume boundary.
  28257. *
  28258. * @type {number}
  28259. * @default 0
  28260. */
  28261. this.thickness = 0;
  28262. /**
  28263. * A texture that defines the thickness, stored in the green channel. This will
  28264. * be multiplied by `thickness`.
  28265. *
  28266. * @type {?Texture}
  28267. * @default null
  28268. */
  28269. this.thicknessMap = null;
  28270. /**
  28271. * Density of the medium given as the average distance that light travels in
  28272. * the medium before interacting with a particle. The value is given in world
  28273. * space units, and must be greater than zero.
  28274. *
  28275. * @type {number}
  28276. * @default Infinity
  28277. */
  28278. this.attenuationDistance = Infinity;
  28279. /**
  28280. * The color that white light turns into due to absorption when reaching the
  28281. * attenuation distance.
  28282. *
  28283. * @type {Color}
  28284. * @default (1,1,1)
  28285. */
  28286. this.attenuationColor = new Color( 1, 1, 1 );
  28287. /**
  28288. * A float that scales the amount of specular reflection for non-metals only.
  28289. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28290. *
  28291. * @type {number}
  28292. * @default 1
  28293. */
  28294. this.specularIntensity = 1.0;
  28295. /**
  28296. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28297. * for per-pixel control over specular intensity.
  28298. *
  28299. * @type {?Texture}
  28300. * @default null
  28301. */
  28302. this.specularIntensityMap = null;
  28303. /**
  28304. * Tints the specular reflection at normal incidence for non-metals only.
  28305. *
  28306. * @type {Color}
  28307. * @default (1,1,1)
  28308. */
  28309. this.specularColor = new Color( 1, 1, 1 );
  28310. /**
  28311. * The RGB channels of this texture are multiplied against `specularColor`,
  28312. * for per-pixel control over specular color.
  28313. *
  28314. * @type {?Texture}
  28315. * @default null
  28316. */
  28317. this.specularColorMap = null;
  28318. this._anisotropy = 0;
  28319. this._clearcoat = 0;
  28320. this._dispersion = 0;
  28321. this._iridescence = 0;
  28322. this._sheen = 0.0;
  28323. this._transmission = 0;
  28324. this.setValues( parameters );
  28325. }
  28326. /**
  28327. * The anisotropy strength, from `0.0` to `1.0`.
  28328. *
  28329. * @type {number}
  28330. * @default 0
  28331. */
  28332. get anisotropy() {
  28333. return this._anisotropy;
  28334. }
  28335. set anisotropy( value ) {
  28336. if ( this._anisotropy > 0 !== value > 0 ) {
  28337. this.version ++;
  28338. }
  28339. this._anisotropy = value;
  28340. }
  28341. /**
  28342. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28343. * clear coat related properties to enable multilayer materials that have a
  28344. * thin translucent layer over the base layer.
  28345. *
  28346. * @type {number}
  28347. * @default 0
  28348. */
  28349. get clearcoat() {
  28350. return this._clearcoat;
  28351. }
  28352. set clearcoat( value ) {
  28353. if ( this._clearcoat > 0 !== value > 0 ) {
  28354. this.version ++;
  28355. }
  28356. this._clearcoat = value;
  28357. }
  28358. /**
  28359. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28360. * the surface and the viewer, from `0.0` to `1.0`.
  28361. *
  28362. * @type {number}
  28363. * @default 0
  28364. */
  28365. get iridescence() {
  28366. return this._iridescence;
  28367. }
  28368. set iridescence( value ) {
  28369. if ( this._iridescence > 0 !== value > 0 ) {
  28370. this.version ++;
  28371. }
  28372. this._iridescence = value;
  28373. }
  28374. /**
  28375. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28376. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28377. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28378. *
  28379. * @type {number}
  28380. * @default 0
  28381. */
  28382. get dispersion() {
  28383. return this._dispersion;
  28384. }
  28385. set dispersion( value ) {
  28386. if ( this._dispersion > 0 !== value > 0 ) {
  28387. this.version ++;
  28388. }
  28389. this._dispersion = value;
  28390. }
  28391. /**
  28392. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28393. *
  28394. * @type {number}
  28395. * @default 0
  28396. */
  28397. get sheen() {
  28398. return this._sheen;
  28399. }
  28400. set sheen( value ) {
  28401. if ( this._sheen > 0 !== value > 0 ) {
  28402. this.version ++;
  28403. }
  28404. this._sheen = value;
  28405. }
  28406. /**
  28407. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28408. *
  28409. * Thin, transparent or semitransparent, plastic or glass materials remain
  28410. * largely reflective even if they are fully transmissive. The transmission
  28411. * property can be used to model these materials.
  28412. *
  28413. * When transmission is non-zero, `opacity` should be set to `1`.
  28414. *
  28415. * @type {number}
  28416. * @default 0
  28417. */
  28418. get transmission() {
  28419. return this._transmission;
  28420. }
  28421. set transmission( value ) {
  28422. if ( this._transmission > 0 !== value > 0 ) {
  28423. this.version ++;
  28424. }
  28425. this._transmission = value;
  28426. }
  28427. copy( source ) {
  28428. super.copy( source );
  28429. this.defines = {
  28430. 'STANDARD': '',
  28431. 'PHYSICAL': ''
  28432. };
  28433. this.anisotropy = source.anisotropy;
  28434. this.anisotropyRotation = source.anisotropyRotation;
  28435. this.anisotropyMap = source.anisotropyMap;
  28436. this.clearcoat = source.clearcoat;
  28437. this.clearcoatMap = source.clearcoatMap;
  28438. this.clearcoatRoughness = source.clearcoatRoughness;
  28439. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28440. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28441. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28442. this.dispersion = source.dispersion;
  28443. this.ior = source.ior;
  28444. this.iridescence = source.iridescence;
  28445. this.iridescenceMap = source.iridescenceMap;
  28446. this.iridescenceIOR = source.iridescenceIOR;
  28447. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28448. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28449. this.sheen = source.sheen;
  28450. this.sheenColor.copy( source.sheenColor );
  28451. this.sheenColorMap = source.sheenColorMap;
  28452. this.sheenRoughness = source.sheenRoughness;
  28453. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28454. this.transmission = source.transmission;
  28455. this.transmissionMap = source.transmissionMap;
  28456. this.thickness = source.thickness;
  28457. this.thicknessMap = source.thicknessMap;
  28458. this.attenuationDistance = source.attenuationDistance;
  28459. this.attenuationColor.copy( source.attenuationColor );
  28460. this.specularIntensity = source.specularIntensity;
  28461. this.specularIntensityMap = source.specularIntensityMap;
  28462. this.specularColor.copy( source.specularColor );
  28463. this.specularColorMap = source.specularColorMap;
  28464. return this;
  28465. }
  28466. }
  28467. /**
  28468. * A material for shiny surfaces with specular highlights.
  28469. *
  28470. * The material uses a non-physically based [Blinn-Phong]{@link https://en.wikipedia.org/wiki/Blinn-Phong_shading_model}
  28471. * model for calculating reflectance. Unlike the Lambertian model used in the
  28472. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28473. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28474. *
  28475. * Performance will generally be greater when using this material over the
  28476. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28477. * some graphical accuracy.
  28478. *
  28479. * @augments Material
  28480. */
  28481. class MeshPhongMaterial extends Material {
  28482. /**
  28483. * Constructs a new mesh phong material.
  28484. *
  28485. * @param {Object} [parameters] - An object with one or more properties
  28486. * defining the material's appearance. Any property of the material
  28487. * (including any property from inherited materials) can be passed
  28488. * in here. Color values can be passed any type of value accepted
  28489. * by {@link Color#set}.
  28490. */
  28491. constructor( parameters ) {
  28492. super();
  28493. /**
  28494. * This flag can be used for type testing.
  28495. *
  28496. * @type {boolean}
  28497. * @readonly
  28498. * @default true
  28499. */
  28500. this.isMeshPhongMaterial = true;
  28501. this.type = 'MeshPhongMaterial';
  28502. /**
  28503. * Color of the material.
  28504. *
  28505. * @type {Color}
  28506. * @default (1,1,1)
  28507. */
  28508. this.color = new Color( 0xffffff ); // diffuse
  28509. /**
  28510. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28511. *
  28512. * This defines how shiny the material is and the color of its shine.
  28513. *
  28514. * @type {Color}
  28515. */
  28516. this.specular = new Color( 0x111111 );
  28517. /**
  28518. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28519. *
  28520. * @type {number}
  28521. * @default 30
  28522. */
  28523. this.shininess = 30;
  28524. /**
  28525. * The color map. May optionally include an alpha channel, typically combined
  28526. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28527. * color is modulated by the diffuse `color`.
  28528. *
  28529. * @type {?Texture}
  28530. * @default null
  28531. */
  28532. this.map = null;
  28533. /**
  28534. * The light map. Requires a second set of UVs.
  28535. *
  28536. * @type {?Texture}
  28537. * @default null
  28538. */
  28539. this.lightMap = null;
  28540. /**
  28541. * Intensity of the baked light.
  28542. *
  28543. * @type {number}
  28544. * @default 1
  28545. */
  28546. this.lightMapIntensity = 1.0;
  28547. /**
  28548. * The red channel of this texture is used as the ambient occlusion map.
  28549. * Requires a second set of UVs.
  28550. *
  28551. * @type {?Texture}
  28552. * @default null
  28553. */
  28554. this.aoMap = null;
  28555. /**
  28556. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28557. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28558. * red channel is also `1`, ambient light is fully occluded on a surface.
  28559. *
  28560. * @type {number}
  28561. * @default 1
  28562. */
  28563. this.aoMapIntensity = 1.0;
  28564. /**
  28565. * Emissive (light) color of the material, essentially a solid color
  28566. * unaffected by other lighting.
  28567. *
  28568. * @type {Color}
  28569. * @default (0,0,0)
  28570. */
  28571. this.emissive = new Color( 0x000000 );
  28572. /**
  28573. * Intensity of the emissive light. Modulates the emissive color.
  28574. *
  28575. * @type {number}
  28576. * @default 1
  28577. */
  28578. this.emissiveIntensity = 1.0;
  28579. /**
  28580. * Set emissive (glow) map. The emissive map color is modulated by the
  28581. * emissive color and the emissive intensity. If you have an emissive map,
  28582. * be sure to set the emissive color to something other than black.
  28583. *
  28584. * @type {?Texture}
  28585. * @default null
  28586. */
  28587. this.emissiveMap = null;
  28588. /**
  28589. * The texture to create a bump map. The black and white values map to the
  28590. * perceived depth in relation to the lights. Bump doesn't actually affect
  28591. * the geometry of the object, only the lighting. If a normal map is defined
  28592. * this will be ignored.
  28593. *
  28594. * @type {?Texture}
  28595. * @default null
  28596. */
  28597. this.bumpMap = null;
  28598. /**
  28599. * How much the bump map affects the material. Typical range is `[0,1]`.
  28600. *
  28601. * @type {number}
  28602. * @default 1
  28603. */
  28604. this.bumpScale = 1;
  28605. /**
  28606. * The texture to create a normal map. The RGB values affect the surface
  28607. * normal for each pixel fragment and change the way the color is lit. Normal
  28608. * maps do not change the actual shape of the surface, only the lighting. In
  28609. * case the material has a normal map authored using the left handed
  28610. * convention, the `y` component of `normalScale` should be negated to compensate
  28611. * for the different handedness.
  28612. *
  28613. * @type {?Texture}
  28614. * @default null
  28615. */
  28616. this.normalMap = null;
  28617. /**
  28618. * The type of normal map.
  28619. *
  28620. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28621. * @default TangentSpaceNormalMap
  28622. */
  28623. this.normalMapType = TangentSpaceNormalMap;
  28624. /**
  28625. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28626. *
  28627. * @type {Vector2}
  28628. * @default (1,1)
  28629. */
  28630. this.normalScale = new Vector2( 1, 1 );
  28631. /**
  28632. * The displacement map affects the position of the mesh's vertices. Unlike
  28633. * other maps which only affect the light and shade of the material the
  28634. * displaced vertices can cast shadows, block other objects, and otherwise
  28635. * act as real geometry. The displacement texture is an image where the value
  28636. * of each pixel (white being the highest) is mapped against, and
  28637. * repositions, the vertices of the mesh.
  28638. *
  28639. * @type {?Texture}
  28640. * @default null
  28641. */
  28642. this.displacementMap = null;
  28643. /**
  28644. * How much the displacement map affects the mesh (where black is no
  28645. * displacement, and white is maximum displacement). Without a displacement
  28646. * map set, this value is not applied.
  28647. *
  28648. * @type {number}
  28649. * @default 0
  28650. */
  28651. this.displacementScale = 1;
  28652. /**
  28653. * The offset of the displacement map's values on the mesh's vertices.
  28654. * The bias is added to the scaled sample of the displacement map.
  28655. * Without a displacement map set, this value is not applied.
  28656. *
  28657. * @type {number}
  28658. * @default 0
  28659. */
  28660. this.displacementBias = 0;
  28661. /**
  28662. * The specular map value affects both how much the specular surface
  28663. * highlight contributes and how much of the environment map affects the
  28664. * surface.
  28665. *
  28666. * @type {?Texture}
  28667. * @default null
  28668. */
  28669. this.specularMap = null;
  28670. /**
  28671. * The alpha map is a grayscale texture that controls the opacity across the
  28672. * surface (black: fully transparent; white: fully opaque).
  28673. *
  28674. * Only the color of the texture is used, ignoring the alpha channel if one
  28675. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28676. * when sampling this texture due to the extra bit of precision provided for
  28677. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28678. * luminance/alpha textures will also still work as expected.
  28679. *
  28680. * @type {?Texture}
  28681. * @default null
  28682. */
  28683. this.alphaMap = null;
  28684. /**
  28685. * The environment map.
  28686. *
  28687. * @type {?Texture}
  28688. * @default null
  28689. */
  28690. this.envMap = null;
  28691. /**
  28692. * The rotation of the environment map in radians.
  28693. *
  28694. * @type {Euler}
  28695. * @default (0,0,0)
  28696. */
  28697. this.envMapRotation = new Euler();
  28698. /**
  28699. * How to combine the result of the surface's color with the environment map, if any.
  28700. *
  28701. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28702. * blend between the two colors.
  28703. *
  28704. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28705. * @default MultiplyOperation
  28706. */
  28707. this.combine = MultiplyOperation;
  28708. /**
  28709. * How much the environment map affects the surface.
  28710. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28711. *
  28712. * @type {number}
  28713. * @default 1
  28714. */
  28715. this.reflectivity = 1;
  28716. /**
  28717. * The index of refraction (IOR) of air (approximately 1) divided by the
  28718. * index of refraction of the material. It is used with environment mapping
  28719. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28720. * The refraction ratio should not exceed `1`.
  28721. *
  28722. * @type {number}
  28723. * @default 0.98
  28724. */
  28725. this.refractionRatio = 0.98;
  28726. /**
  28727. * Renders the geometry as a wireframe.
  28728. *
  28729. * @type {boolean}
  28730. * @default false
  28731. */
  28732. this.wireframe = false;
  28733. /**
  28734. * Controls the thickness of the wireframe.
  28735. *
  28736. * Can only be used with {@link SVGRenderer}.
  28737. *
  28738. * @type {number}
  28739. * @default 1
  28740. */
  28741. this.wireframeLinewidth = 1;
  28742. /**
  28743. * Defines appearance of wireframe ends.
  28744. *
  28745. * Can only be used with {@link SVGRenderer}.
  28746. *
  28747. * @type {('round'|'bevel'|'miter')}
  28748. * @default 'round'
  28749. */
  28750. this.wireframeLinecap = 'round';
  28751. /**
  28752. * Defines appearance of wireframe joints.
  28753. *
  28754. * Can only be used with {@link SVGRenderer}.
  28755. *
  28756. * @type {('round'|'bevel'|'miter')}
  28757. * @default 'round'
  28758. */
  28759. this.wireframeLinejoin = 'round';
  28760. /**
  28761. * Whether the material is rendered with flat shading or not.
  28762. *
  28763. * @type {boolean}
  28764. * @default false
  28765. */
  28766. this.flatShading = false;
  28767. /**
  28768. * Whether the material is affected by fog or not.
  28769. *
  28770. * @type {boolean}
  28771. * @default true
  28772. */
  28773. this.fog = true;
  28774. this.setValues( parameters );
  28775. }
  28776. copy( source ) {
  28777. super.copy( source );
  28778. this.color.copy( source.color );
  28779. this.specular.copy( source.specular );
  28780. this.shininess = source.shininess;
  28781. this.map = source.map;
  28782. this.lightMap = source.lightMap;
  28783. this.lightMapIntensity = source.lightMapIntensity;
  28784. this.aoMap = source.aoMap;
  28785. this.aoMapIntensity = source.aoMapIntensity;
  28786. this.emissive.copy( source.emissive );
  28787. this.emissiveMap = source.emissiveMap;
  28788. this.emissiveIntensity = source.emissiveIntensity;
  28789. this.bumpMap = source.bumpMap;
  28790. this.bumpScale = source.bumpScale;
  28791. this.normalMap = source.normalMap;
  28792. this.normalMapType = source.normalMapType;
  28793. this.normalScale.copy( source.normalScale );
  28794. this.displacementMap = source.displacementMap;
  28795. this.displacementScale = source.displacementScale;
  28796. this.displacementBias = source.displacementBias;
  28797. this.specularMap = source.specularMap;
  28798. this.alphaMap = source.alphaMap;
  28799. this.envMap = source.envMap;
  28800. this.envMapRotation.copy( source.envMapRotation );
  28801. this.combine = source.combine;
  28802. this.reflectivity = source.reflectivity;
  28803. this.refractionRatio = source.refractionRatio;
  28804. this.wireframe = source.wireframe;
  28805. this.wireframeLinewidth = source.wireframeLinewidth;
  28806. this.wireframeLinecap = source.wireframeLinecap;
  28807. this.wireframeLinejoin = source.wireframeLinejoin;
  28808. this.flatShading = source.flatShading;
  28809. this.fog = source.fog;
  28810. return this;
  28811. }
  28812. }
  28813. /**
  28814. * A material implementing toon shading.
  28815. *
  28816. * @augments Material
  28817. */
  28818. class MeshToonMaterial extends Material {
  28819. /**
  28820. * Constructs a new mesh toon material.
  28821. *
  28822. * @param {Object} [parameters] - An object with one or more properties
  28823. * defining the material's appearance. Any property of the material
  28824. * (including any property from inherited materials) can be passed
  28825. * in here. Color values can be passed any type of value accepted
  28826. * by {@link Color#set}.
  28827. */
  28828. constructor( parameters ) {
  28829. super();
  28830. /**
  28831. * This flag can be used for type testing.
  28832. *
  28833. * @type {boolean}
  28834. * @readonly
  28835. * @default true
  28836. */
  28837. this.isMeshToonMaterial = true;
  28838. this.defines = { 'TOON': '' };
  28839. this.type = 'MeshToonMaterial';
  28840. /**
  28841. * Color of the material.
  28842. *
  28843. * @type {Color}
  28844. * @default (1,1,1)
  28845. */
  28846. this.color = new Color( 0xffffff );
  28847. /**
  28848. * The color map. May optionally include an alpha channel, typically combined
  28849. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28850. * color is modulated by the diffuse `color`.
  28851. *
  28852. * @type {?Texture}
  28853. * @default null
  28854. */
  28855. this.map = null;
  28856. /**
  28857. * Gradient map for toon shading. It's required to set
  28858. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  28859. * when using this type of texture.
  28860. *
  28861. * @type {?Texture}
  28862. * @default null
  28863. */
  28864. this.gradientMap = null;
  28865. /**
  28866. * The light map. Requires a second set of UVs.
  28867. *
  28868. * @type {?Texture}
  28869. * @default null
  28870. */
  28871. this.lightMap = null;
  28872. /**
  28873. * Intensity of the baked light.
  28874. *
  28875. * @type {number}
  28876. * @default 1
  28877. */
  28878. this.lightMapIntensity = 1.0;
  28879. /**
  28880. * The red channel of this texture is used as the ambient occlusion map.
  28881. * Requires a second set of UVs.
  28882. *
  28883. * @type {?Texture}
  28884. * @default null
  28885. */
  28886. this.aoMap = null;
  28887. /**
  28888. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28889. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28890. * red channel is also `1`, ambient light is fully occluded on a surface.
  28891. *
  28892. * @type {number}
  28893. * @default 1
  28894. */
  28895. this.aoMapIntensity = 1.0;
  28896. /**
  28897. * Emissive (light) color of the material, essentially a solid color
  28898. * unaffected by other lighting.
  28899. *
  28900. * @type {Color}
  28901. * @default (0,0,0)
  28902. */
  28903. this.emissive = new Color( 0x000000 );
  28904. /**
  28905. * Intensity of the emissive light. Modulates the emissive color.
  28906. *
  28907. * @type {number}
  28908. * @default 1
  28909. */
  28910. this.emissiveIntensity = 1.0;
  28911. /**
  28912. * Set emissive (glow) map. The emissive map color is modulated by the
  28913. * emissive color and the emissive intensity. If you have an emissive map,
  28914. * be sure to set the emissive color to something other than black.
  28915. *
  28916. * @type {?Texture}
  28917. * @default null
  28918. */
  28919. this.emissiveMap = null;
  28920. /**
  28921. * The texture to create a bump map. The black and white values map to the
  28922. * perceived depth in relation to the lights. Bump doesn't actually affect
  28923. * the geometry of the object, only the lighting. If a normal map is defined
  28924. * this will be ignored.
  28925. *
  28926. * @type {?Texture}
  28927. * @default null
  28928. */
  28929. this.bumpMap = null;
  28930. /**
  28931. * How much the bump map affects the material. Typical range is `[0,1]`.
  28932. *
  28933. * @type {number}
  28934. * @default 1
  28935. */
  28936. this.bumpScale = 1;
  28937. /**
  28938. * The texture to create a normal map. The RGB values affect the surface
  28939. * normal for each pixel fragment and change the way the color is lit. Normal
  28940. * maps do not change the actual shape of the surface, only the lighting. In
  28941. * case the material has a normal map authored using the left handed
  28942. * convention, the `y` component of `normalScale` should be negated to compensate
  28943. * for the different handedness.
  28944. *
  28945. * @type {?Texture}
  28946. * @default null
  28947. */
  28948. this.normalMap = null;
  28949. /**
  28950. * The type of normal map.
  28951. *
  28952. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28953. * @default TangentSpaceNormalMap
  28954. */
  28955. this.normalMapType = TangentSpaceNormalMap;
  28956. /**
  28957. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28958. *
  28959. * @type {Vector2}
  28960. * @default (1,1)
  28961. */
  28962. this.normalScale = new Vector2( 1, 1 );
  28963. /**
  28964. * The displacement map affects the position of the mesh's vertices. Unlike
  28965. * other maps which only affect the light and shade of the material the
  28966. * displaced vertices can cast shadows, block other objects, and otherwise
  28967. * act as real geometry. The displacement texture is an image where the value
  28968. * of each pixel (white being the highest) is mapped against, and
  28969. * repositions, the vertices of the mesh.
  28970. *
  28971. * @type {?Texture}
  28972. * @default null
  28973. */
  28974. this.displacementMap = null;
  28975. /**
  28976. * How much the displacement map affects the mesh (where black is no
  28977. * displacement, and white is maximum displacement). Without a displacement
  28978. * map set, this value is not applied.
  28979. *
  28980. * @type {number}
  28981. * @default 0
  28982. */
  28983. this.displacementScale = 1;
  28984. /**
  28985. * The offset of the displacement map's values on the mesh's vertices.
  28986. * The bias is added to the scaled sample of the displacement map.
  28987. * Without a displacement map set, this value is not applied.
  28988. *
  28989. * @type {number}
  28990. * @default 0
  28991. */
  28992. this.displacementBias = 0;
  28993. /**
  28994. * The alpha map is a grayscale texture that controls the opacity across the
  28995. * surface (black: fully transparent; white: fully opaque).
  28996. *
  28997. * Only the color of the texture is used, ignoring the alpha channel if one
  28998. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28999. * when sampling this texture due to the extra bit of precision provided for
  29000. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29001. * luminance/alpha textures will also still work as expected.
  29002. *
  29003. * @type {?Texture}
  29004. * @default null
  29005. */
  29006. this.alphaMap = null;
  29007. /**
  29008. * Renders the geometry as a wireframe.
  29009. *
  29010. * @type {boolean}
  29011. * @default false
  29012. */
  29013. this.wireframe = false;
  29014. /**
  29015. * Controls the thickness of the wireframe.
  29016. *
  29017. * Can only be used with {@link SVGRenderer}.
  29018. *
  29019. * @type {number}
  29020. * @default 1
  29021. */
  29022. this.wireframeLinewidth = 1;
  29023. /**
  29024. * Defines appearance of wireframe ends.
  29025. *
  29026. * Can only be used with {@link SVGRenderer}.
  29027. *
  29028. * @type {('round'|'bevel'|'miter')}
  29029. * @default 'round'
  29030. */
  29031. this.wireframeLinecap = 'round';
  29032. /**
  29033. * Defines appearance of wireframe joints.
  29034. *
  29035. * Can only be used with {@link SVGRenderer}.
  29036. *
  29037. * @type {('round'|'bevel'|'miter')}
  29038. * @default 'round'
  29039. */
  29040. this.wireframeLinejoin = 'round';
  29041. /**
  29042. * Whether the material is affected by fog or not.
  29043. *
  29044. * @type {boolean}
  29045. * @default true
  29046. */
  29047. this.fog = true;
  29048. this.setValues( parameters );
  29049. }
  29050. copy( source ) {
  29051. super.copy( source );
  29052. this.color.copy( source.color );
  29053. this.map = source.map;
  29054. this.gradientMap = source.gradientMap;
  29055. this.lightMap = source.lightMap;
  29056. this.lightMapIntensity = source.lightMapIntensity;
  29057. this.aoMap = source.aoMap;
  29058. this.aoMapIntensity = source.aoMapIntensity;
  29059. this.emissive.copy( source.emissive );
  29060. this.emissiveMap = source.emissiveMap;
  29061. this.emissiveIntensity = source.emissiveIntensity;
  29062. this.bumpMap = source.bumpMap;
  29063. this.bumpScale = source.bumpScale;
  29064. this.normalMap = source.normalMap;
  29065. this.normalMapType = source.normalMapType;
  29066. this.normalScale.copy( source.normalScale );
  29067. this.displacementMap = source.displacementMap;
  29068. this.displacementScale = source.displacementScale;
  29069. this.displacementBias = source.displacementBias;
  29070. this.alphaMap = source.alphaMap;
  29071. this.wireframe = source.wireframe;
  29072. this.wireframeLinewidth = source.wireframeLinewidth;
  29073. this.wireframeLinecap = source.wireframeLinecap;
  29074. this.wireframeLinejoin = source.wireframeLinejoin;
  29075. this.fog = source.fog;
  29076. return this;
  29077. }
  29078. }
  29079. /**
  29080. * A material that maps the normal vectors to RGB colors.
  29081. *
  29082. * @augments Material
  29083. */
  29084. class MeshNormalMaterial extends Material {
  29085. /**
  29086. * Constructs a new mesh normal material.
  29087. *
  29088. * @param {Object} [parameters] - An object with one or more properties
  29089. * defining the material's appearance. Any property of the material
  29090. * (including any property from inherited materials) can be passed
  29091. * in here. Color values can be passed any type of value accepted
  29092. * by {@link Color#set}.
  29093. */
  29094. constructor( parameters ) {
  29095. super();
  29096. /**
  29097. * This flag can be used for type testing.
  29098. *
  29099. * @type {boolean}
  29100. * @readonly
  29101. * @default true
  29102. */
  29103. this.isMeshNormalMaterial = true;
  29104. this.type = 'MeshNormalMaterial';
  29105. /**
  29106. * The texture to create a bump map. The black and white values map to the
  29107. * perceived depth in relation to the lights. Bump doesn't actually affect
  29108. * the geometry of the object, only the lighting. If a normal map is defined
  29109. * this will be ignored.
  29110. *
  29111. * @type {?Texture}
  29112. * @default null
  29113. */
  29114. this.bumpMap = null;
  29115. /**
  29116. * How much the bump map affects the material. Typical range is `[0,1]`.
  29117. *
  29118. * @type {number}
  29119. * @default 1
  29120. */
  29121. this.bumpScale = 1;
  29122. /**
  29123. * The texture to create a normal map. The RGB values affect the surface
  29124. * normal for each pixel fragment and change the way the color is lit. Normal
  29125. * maps do not change the actual shape of the surface, only the lighting. In
  29126. * case the material has a normal map authored using the left handed
  29127. * convention, the `y` component of `normalScale` should be negated to compensate
  29128. * for the different handedness.
  29129. *
  29130. * @type {?Texture}
  29131. * @default null
  29132. */
  29133. this.normalMap = null;
  29134. /**
  29135. * The type of normal map.
  29136. *
  29137. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29138. * @default TangentSpaceNormalMap
  29139. */
  29140. this.normalMapType = TangentSpaceNormalMap;
  29141. /**
  29142. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29143. *
  29144. * @type {Vector2}
  29145. * @default (1,1)
  29146. */
  29147. this.normalScale = new Vector2( 1, 1 );
  29148. /**
  29149. * The displacement map affects the position of the mesh's vertices. Unlike
  29150. * other maps which only affect the light and shade of the material the
  29151. * displaced vertices can cast shadows, block other objects, and otherwise
  29152. * act as real geometry. The displacement texture is an image where the value
  29153. * of each pixel (white being the highest) is mapped against, and
  29154. * repositions, the vertices of the mesh.
  29155. *
  29156. * @type {?Texture}
  29157. * @default null
  29158. */
  29159. this.displacementMap = null;
  29160. /**
  29161. * How much the displacement map affects the mesh (where black is no
  29162. * displacement, and white is maximum displacement). Without a displacement
  29163. * map set, this value is not applied.
  29164. *
  29165. * @type {number}
  29166. * @default 0
  29167. */
  29168. this.displacementScale = 1;
  29169. /**
  29170. * The offset of the displacement map's values on the mesh's vertices.
  29171. * The bias is added to the scaled sample of the displacement map.
  29172. * Without a displacement map set, this value is not applied.
  29173. *
  29174. * @type {number}
  29175. * @default 0
  29176. */
  29177. this.displacementBias = 0;
  29178. /**
  29179. * Renders the geometry as a wireframe.
  29180. *
  29181. * @type {boolean}
  29182. * @default false
  29183. */
  29184. this.wireframe = false;
  29185. /**
  29186. * Controls the thickness of the wireframe.
  29187. *
  29188. * WebGL and WebGPU ignore this property and always render
  29189. * 1 pixel wide lines.
  29190. *
  29191. * @type {number}
  29192. * @default 1
  29193. */
  29194. this.wireframeLinewidth = 1;
  29195. /**
  29196. * Whether the material is rendered with flat shading or not.
  29197. *
  29198. * @type {boolean}
  29199. * @default false
  29200. */
  29201. this.flatShading = false;
  29202. this.setValues( parameters );
  29203. }
  29204. copy( source ) {
  29205. super.copy( source );
  29206. this.bumpMap = source.bumpMap;
  29207. this.bumpScale = source.bumpScale;
  29208. this.normalMap = source.normalMap;
  29209. this.normalMapType = source.normalMapType;
  29210. this.normalScale.copy( source.normalScale );
  29211. this.displacementMap = source.displacementMap;
  29212. this.displacementScale = source.displacementScale;
  29213. this.displacementBias = source.displacementBias;
  29214. this.wireframe = source.wireframe;
  29215. this.wireframeLinewidth = source.wireframeLinewidth;
  29216. this.flatShading = source.flatShading;
  29217. return this;
  29218. }
  29219. }
  29220. /**
  29221. * A material for non-shiny surfaces, without specular highlights.
  29222. *
  29223. * The material uses a non-physically based [Lambertian]{@link https://en.wikipedia.org/wiki/Lambertian_reflectance}
  29224. * model for calculating reflectance. This can simulate some surfaces (such
  29225. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29226. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29227. * shading.
  29228. *
  29229. * Due to the simplicity of the reflectance and illumination models,
  29230. * performance will be greater when using this material over the
  29231. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29232. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29233. *
  29234. * @augments Material
  29235. */
  29236. class MeshLambertMaterial extends Material {
  29237. /**
  29238. * Constructs a new mesh lambert material.
  29239. *
  29240. * @param {Object} [parameters] - An object with one or more properties
  29241. * defining the material's appearance. Any property of the material
  29242. * (including any property from inherited materials) can be passed
  29243. * in here. Color values can be passed any type of value accepted
  29244. * by {@link Color#set}.
  29245. */
  29246. constructor( parameters ) {
  29247. super();
  29248. /**
  29249. * This flag can be used for type testing.
  29250. *
  29251. * @type {boolean}
  29252. * @readonly
  29253. * @default true
  29254. */
  29255. this.isMeshLambertMaterial = true;
  29256. this.type = 'MeshLambertMaterial';
  29257. /**
  29258. * Color of the material.
  29259. *
  29260. * @type {Color}
  29261. * @default (1,1,1)
  29262. */
  29263. this.color = new Color( 0xffffff ); // diffuse
  29264. /**
  29265. * The color map. May optionally include an alpha channel, typically combined
  29266. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29267. * color is modulated by the diffuse `color`.
  29268. *
  29269. * @type {?Texture}
  29270. * @default null
  29271. */
  29272. this.map = null;
  29273. /**
  29274. * The light map. Requires a second set of UVs.
  29275. *
  29276. * @type {?Texture}
  29277. * @default null
  29278. */
  29279. this.lightMap = null;
  29280. /**
  29281. * Intensity of the baked light.
  29282. *
  29283. * @type {number}
  29284. * @default 1
  29285. */
  29286. this.lightMapIntensity = 1.0;
  29287. /**
  29288. * The red channel of this texture is used as the ambient occlusion map.
  29289. * Requires a second set of UVs.
  29290. *
  29291. * @type {?Texture}
  29292. * @default null
  29293. */
  29294. this.aoMap = null;
  29295. /**
  29296. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29297. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29298. * red channel is also `1`, ambient light is fully occluded on a surface.
  29299. *
  29300. * @type {number}
  29301. * @default 1
  29302. */
  29303. this.aoMapIntensity = 1.0;
  29304. /**
  29305. * Emissive (light) color of the material, essentially a solid color
  29306. * unaffected by other lighting.
  29307. *
  29308. * @type {Color}
  29309. * @default (0,0,0)
  29310. */
  29311. this.emissive = new Color( 0x000000 );
  29312. /**
  29313. * Intensity of the emissive light. Modulates the emissive color.
  29314. *
  29315. * @type {number}
  29316. * @default 1
  29317. */
  29318. this.emissiveIntensity = 1.0;
  29319. /**
  29320. * Set emissive (glow) map. The emissive map color is modulated by the
  29321. * emissive color and the emissive intensity. If you have an emissive map,
  29322. * be sure to set the emissive color to something other than black.
  29323. *
  29324. * @type {?Texture}
  29325. * @default null
  29326. */
  29327. this.emissiveMap = null;
  29328. /**
  29329. * The texture to create a bump map. The black and white values map to the
  29330. * perceived depth in relation to the lights. Bump doesn't actually affect
  29331. * the geometry of the object, only the lighting. If a normal map is defined
  29332. * this will be ignored.
  29333. *
  29334. * @type {?Texture}
  29335. * @default null
  29336. */
  29337. this.bumpMap = null;
  29338. /**
  29339. * How much the bump map affects the material. Typical range is `[0,1]`.
  29340. *
  29341. * @type {number}
  29342. * @default 1
  29343. */
  29344. this.bumpScale = 1;
  29345. /**
  29346. * The texture to create a normal map. The RGB values affect the surface
  29347. * normal for each pixel fragment and change the way the color is lit. Normal
  29348. * maps do not change the actual shape of the surface, only the lighting. In
  29349. * case the material has a normal map authored using the left handed
  29350. * convention, the `y` component of `normalScale` should be negated to compensate
  29351. * for the different handedness.
  29352. *
  29353. * @type {?Texture}
  29354. * @default null
  29355. */
  29356. this.normalMap = null;
  29357. /**
  29358. * The type of normal map.
  29359. *
  29360. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29361. * @default TangentSpaceNormalMap
  29362. */
  29363. this.normalMapType = TangentSpaceNormalMap;
  29364. /**
  29365. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29366. *
  29367. * @type {Vector2}
  29368. * @default (1,1)
  29369. */
  29370. this.normalScale = new Vector2( 1, 1 );
  29371. /**
  29372. * The displacement map affects the position of the mesh's vertices. Unlike
  29373. * other maps which only affect the light and shade of the material the
  29374. * displaced vertices can cast shadows, block other objects, and otherwise
  29375. * act as real geometry. The displacement texture is an image where the value
  29376. * of each pixel (white being the highest) is mapped against, and
  29377. * repositions, the vertices of the mesh.
  29378. *
  29379. * @type {?Texture}
  29380. * @default null
  29381. */
  29382. this.displacementMap = null;
  29383. /**
  29384. * How much the displacement map affects the mesh (where black is no
  29385. * displacement, and white is maximum displacement). Without a displacement
  29386. * map set, this value is not applied.
  29387. *
  29388. * @type {number}
  29389. * @default 0
  29390. */
  29391. this.displacementScale = 1;
  29392. /**
  29393. * The offset of the displacement map's values on the mesh's vertices.
  29394. * The bias is added to the scaled sample of the displacement map.
  29395. * Without a displacement map set, this value is not applied.
  29396. *
  29397. * @type {number}
  29398. * @default 0
  29399. */
  29400. this.displacementBias = 0;
  29401. /**
  29402. * Specular map used by the material.
  29403. *
  29404. * @type {?Texture}
  29405. * @default null
  29406. */
  29407. this.specularMap = null;
  29408. /**
  29409. * The alpha map is a grayscale texture that controls the opacity across the
  29410. * surface (black: fully transparent; white: fully opaque).
  29411. *
  29412. * Only the color of the texture is used, ignoring the alpha channel if one
  29413. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29414. * when sampling this texture due to the extra bit of precision provided for
  29415. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29416. * luminance/alpha textures will also still work as expected.
  29417. *
  29418. * @type {?Texture}
  29419. * @default null
  29420. */
  29421. this.alphaMap = null;
  29422. /**
  29423. * The environment map.
  29424. *
  29425. * @type {?Texture}
  29426. * @default null
  29427. */
  29428. this.envMap = null;
  29429. /**
  29430. * The rotation of the environment map in radians.
  29431. *
  29432. * @type {Euler}
  29433. * @default (0,0,0)
  29434. */
  29435. this.envMapRotation = new Euler();
  29436. /**
  29437. * How to combine the result of the surface's color with the environment map, if any.
  29438. *
  29439. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29440. * blend between the two colors.
  29441. *
  29442. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29443. * @default MultiplyOperation
  29444. */
  29445. this.combine = MultiplyOperation;
  29446. /**
  29447. * How much the environment map affects the surface.
  29448. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29449. *
  29450. * @type {number}
  29451. * @default 1
  29452. */
  29453. this.reflectivity = 1;
  29454. /**
  29455. * The index of refraction (IOR) of air (approximately 1) divided by the
  29456. * index of refraction of the material. It is used with environment mapping
  29457. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29458. * The refraction ratio should not exceed `1`.
  29459. *
  29460. * @type {number}
  29461. * @default 0.98
  29462. */
  29463. this.refractionRatio = 0.98;
  29464. /**
  29465. * Renders the geometry as a wireframe.
  29466. *
  29467. * @type {boolean}
  29468. * @default false
  29469. */
  29470. this.wireframe = false;
  29471. /**
  29472. * Controls the thickness of the wireframe.
  29473. *
  29474. * Can only be used with {@link SVGRenderer}.
  29475. *
  29476. * @type {number}
  29477. * @default 1
  29478. */
  29479. this.wireframeLinewidth = 1;
  29480. /**
  29481. * Defines appearance of wireframe ends.
  29482. *
  29483. * Can only be used with {@link SVGRenderer}.
  29484. *
  29485. * @type {('round'|'bevel'|'miter')}
  29486. * @default 'round'
  29487. */
  29488. this.wireframeLinecap = 'round';
  29489. /**
  29490. * Defines appearance of wireframe joints.
  29491. *
  29492. * Can only be used with {@link SVGRenderer}.
  29493. *
  29494. * @type {('round'|'bevel'|'miter')}
  29495. * @default 'round'
  29496. */
  29497. this.wireframeLinejoin = 'round';
  29498. /**
  29499. * Whether the material is rendered with flat shading or not.
  29500. *
  29501. * @type {boolean}
  29502. * @default false
  29503. */
  29504. this.flatShading = false;
  29505. /**
  29506. * Whether the material is affected by fog or not.
  29507. *
  29508. * @type {boolean}
  29509. * @default true
  29510. */
  29511. this.fog = true;
  29512. this.setValues( parameters );
  29513. }
  29514. copy( source ) {
  29515. super.copy( source );
  29516. this.color.copy( source.color );
  29517. this.map = source.map;
  29518. this.lightMap = source.lightMap;
  29519. this.lightMapIntensity = source.lightMapIntensity;
  29520. this.aoMap = source.aoMap;
  29521. this.aoMapIntensity = source.aoMapIntensity;
  29522. this.emissive.copy( source.emissive );
  29523. this.emissiveMap = source.emissiveMap;
  29524. this.emissiveIntensity = source.emissiveIntensity;
  29525. this.bumpMap = source.bumpMap;
  29526. this.bumpScale = source.bumpScale;
  29527. this.normalMap = source.normalMap;
  29528. this.normalMapType = source.normalMapType;
  29529. this.normalScale.copy( source.normalScale );
  29530. this.displacementMap = source.displacementMap;
  29531. this.displacementScale = source.displacementScale;
  29532. this.displacementBias = source.displacementBias;
  29533. this.specularMap = source.specularMap;
  29534. this.alphaMap = source.alphaMap;
  29535. this.envMap = source.envMap;
  29536. this.envMapRotation.copy( source.envMapRotation );
  29537. this.combine = source.combine;
  29538. this.reflectivity = source.reflectivity;
  29539. this.refractionRatio = source.refractionRatio;
  29540. this.wireframe = source.wireframe;
  29541. this.wireframeLinewidth = source.wireframeLinewidth;
  29542. this.wireframeLinecap = source.wireframeLinecap;
  29543. this.wireframeLinejoin = source.wireframeLinejoin;
  29544. this.flatShading = source.flatShading;
  29545. this.fog = source.fog;
  29546. return this;
  29547. }
  29548. }
  29549. /**
  29550. * A material for drawing geometry by depth. Depth is based off of the camera
  29551. * near and far plane. White is nearest, black is farthest.
  29552. *
  29553. * @augments Material
  29554. */
  29555. class MeshDepthMaterial extends Material {
  29556. /**
  29557. * Constructs a new mesh depth material.
  29558. *
  29559. * @param {Object} [parameters] - An object with one or more properties
  29560. * defining the material's appearance. Any property of the material
  29561. * (including any property from inherited materials) can be passed
  29562. * in here. Color values can be passed any type of value accepted
  29563. * by {@link Color#set}.
  29564. */
  29565. constructor( parameters ) {
  29566. super();
  29567. /**
  29568. * This flag can be used for type testing.
  29569. *
  29570. * @type {boolean}
  29571. * @readonly
  29572. * @default true
  29573. */
  29574. this.isMeshDepthMaterial = true;
  29575. this.type = 'MeshDepthMaterial';
  29576. /**
  29577. * Type for depth packing.
  29578. *
  29579. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29580. * @default BasicDepthPacking
  29581. */
  29582. this.depthPacking = BasicDepthPacking;
  29583. /**
  29584. * The color map. May optionally include an alpha channel, typically combined
  29585. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29586. *
  29587. * @type {?Texture}
  29588. * @default null
  29589. */
  29590. this.map = null;
  29591. /**
  29592. * The alpha map is a grayscale texture that controls the opacity across the
  29593. * surface (black: fully transparent; white: fully opaque).
  29594. *
  29595. * Only the color of the texture is used, ignoring the alpha channel if one
  29596. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29597. * when sampling this texture due to the extra bit of precision provided for
  29598. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29599. * luminance/alpha textures will also still work as expected.
  29600. *
  29601. * @type {?Texture}
  29602. * @default null
  29603. */
  29604. this.alphaMap = null;
  29605. /**
  29606. * The displacement map affects the position of the mesh's vertices. Unlike
  29607. * other maps which only affect the light and shade of the material the
  29608. * displaced vertices can cast shadows, block other objects, and otherwise
  29609. * act as real geometry. The displacement texture is an image where the value
  29610. * of each pixel (white being the highest) is mapped against, and
  29611. * repositions, the vertices of the mesh.
  29612. *
  29613. * @type {?Texture}
  29614. * @default null
  29615. */
  29616. this.displacementMap = null;
  29617. /**
  29618. * How much the displacement map affects the mesh (where black is no
  29619. * displacement, and white is maximum displacement). Without a displacement
  29620. * map set, this value is not applied.
  29621. *
  29622. * @type {number}
  29623. * @default 0
  29624. */
  29625. this.displacementScale = 1;
  29626. /**
  29627. * The offset of the displacement map's values on the mesh's vertices.
  29628. * The bias is added to the scaled sample of the displacement map.
  29629. * Without a displacement map set, this value is not applied.
  29630. *
  29631. * @type {number}
  29632. * @default 0
  29633. */
  29634. this.displacementBias = 0;
  29635. /**
  29636. * Renders the geometry as a wireframe.
  29637. *
  29638. * @type {boolean}
  29639. * @default false
  29640. */
  29641. this.wireframe = false;
  29642. /**
  29643. * Controls the thickness of the wireframe.
  29644. *
  29645. * WebGL and WebGPU ignore this property and always render
  29646. * 1 pixel wide lines.
  29647. *
  29648. * @type {number}
  29649. * @default 1
  29650. */
  29651. this.wireframeLinewidth = 1;
  29652. this.setValues( parameters );
  29653. }
  29654. copy( source ) {
  29655. super.copy( source );
  29656. this.depthPacking = source.depthPacking;
  29657. this.map = source.map;
  29658. this.alphaMap = source.alphaMap;
  29659. this.displacementMap = source.displacementMap;
  29660. this.displacementScale = source.displacementScale;
  29661. this.displacementBias = source.displacementBias;
  29662. this.wireframe = source.wireframe;
  29663. this.wireframeLinewidth = source.wireframeLinewidth;
  29664. return this;
  29665. }
  29666. }
  29667. /**
  29668. * A material used internally for implementing shadow mapping with
  29669. * point lights.
  29670. *
  29671. * Can also be used to customize the shadow casting of an object by assigning
  29672. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29673. * The following examples demonstrates this approach in order to ensure
  29674. * transparent parts of objects do not cast shadows.
  29675. *
  29676. * @augments Material
  29677. */
  29678. class MeshDistanceMaterial extends Material {
  29679. /**
  29680. * Constructs a new mesh distance material.
  29681. *
  29682. * @param {Object} [parameters] - An object with one or more properties
  29683. * defining the material's appearance. Any property of the material
  29684. * (including any property from inherited materials) can be passed
  29685. * in here. Color values can be passed any type of value accepted
  29686. * by {@link Color#set}.
  29687. */
  29688. constructor( parameters ) {
  29689. super();
  29690. /**
  29691. * This flag can be used for type testing.
  29692. *
  29693. * @type {boolean}
  29694. * @readonly
  29695. * @default true
  29696. */
  29697. this.isMeshDistanceMaterial = true;
  29698. this.type = 'MeshDistanceMaterial';
  29699. /**
  29700. * The color map. May optionally include an alpha channel, typically combined
  29701. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29702. *
  29703. * @type {?Texture}
  29704. * @default null
  29705. */
  29706. this.map = null;
  29707. /**
  29708. * The alpha map is a grayscale texture that controls the opacity across the
  29709. * surface (black: fully transparent; white: fully opaque).
  29710. *
  29711. * Only the color of the texture is used, ignoring the alpha channel if one
  29712. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29713. * when sampling this texture due to the extra bit of precision provided for
  29714. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29715. * luminance/alpha textures will also still work as expected.
  29716. *
  29717. * @type {?Texture}
  29718. * @default null
  29719. */
  29720. this.alphaMap = null;
  29721. /**
  29722. * The displacement map affects the position of the mesh's vertices. Unlike
  29723. * other maps which only affect the light and shade of the material the
  29724. * displaced vertices can cast shadows, block other objects, and otherwise
  29725. * act as real geometry. The displacement texture is an image where the value
  29726. * of each pixel (white being the highest) is mapped against, and
  29727. * repositions, the vertices of the mesh.
  29728. *
  29729. * @type {?Texture}
  29730. * @default null
  29731. */
  29732. this.displacementMap = null;
  29733. /**
  29734. * How much the displacement map affects the mesh (where black is no
  29735. * displacement, and white is maximum displacement). Without a displacement
  29736. * map set, this value is not applied.
  29737. *
  29738. * @type {number}
  29739. * @default 0
  29740. */
  29741. this.displacementScale = 1;
  29742. /**
  29743. * The offset of the displacement map's values on the mesh's vertices.
  29744. * The bias is added to the scaled sample of the displacement map.
  29745. * Without a displacement map set, this value is not applied.
  29746. *
  29747. * @type {number}
  29748. * @default 0
  29749. */
  29750. this.displacementBias = 0;
  29751. this.setValues( parameters );
  29752. }
  29753. copy( source ) {
  29754. super.copy( source );
  29755. this.map = source.map;
  29756. this.alphaMap = source.alphaMap;
  29757. this.displacementMap = source.displacementMap;
  29758. this.displacementScale = source.displacementScale;
  29759. this.displacementBias = source.displacementBias;
  29760. return this;
  29761. }
  29762. }
  29763. /**
  29764. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29765. * material color and shading.
  29766. *
  29767. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29768. * baked lighting. It will cast a shadow onto an object that receives shadows
  29769. * (and shadow clipping works), but it will not self-shadow or receive
  29770. * shadows.
  29771. *
  29772. * @augments Material
  29773. */
  29774. class MeshMatcapMaterial extends Material {
  29775. /**
  29776. * Constructs a new mesh matcap material.
  29777. *
  29778. * @param {Object} [parameters] - An object with one or more properties
  29779. * defining the material's appearance. Any property of the material
  29780. * (including any property from inherited materials) can be passed
  29781. * in here. Color values can be passed any type of value accepted
  29782. * by {@link Color#set}.
  29783. */
  29784. constructor( parameters ) {
  29785. super();
  29786. /**
  29787. * This flag can be used for type testing.
  29788. *
  29789. * @type {boolean}
  29790. * @readonly
  29791. * @default true
  29792. */
  29793. this.isMeshMatcapMaterial = true;
  29794. this.defines = { 'MATCAP': '' };
  29795. this.type = 'MeshMatcapMaterial';
  29796. /**
  29797. * Color of the material.
  29798. *
  29799. * @type {Color}
  29800. * @default (1,1,1)
  29801. */
  29802. this.color = new Color( 0xffffff ); // diffuse
  29803. /**
  29804. * The matcap map.
  29805. *
  29806. * @type {?Texture}
  29807. * @default null
  29808. */
  29809. this.matcap = null;
  29810. /**
  29811. * The color map. May optionally include an alpha channel, typically combined
  29812. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29813. * color is modulated by the diffuse `color`.
  29814. *
  29815. * @type {?Texture}
  29816. * @default null
  29817. */
  29818. this.map = null;
  29819. /**
  29820. * The texture to create a bump map. The black and white values map to the
  29821. * perceived depth in relation to the lights. Bump doesn't actually affect
  29822. * the geometry of the object, only the lighting. If a normal map is defined
  29823. * this will be ignored.
  29824. *
  29825. * @type {?Texture}
  29826. * @default null
  29827. */
  29828. this.bumpMap = null;
  29829. /**
  29830. * How much the bump map affects the material. Typical range is `[0,1]`.
  29831. *
  29832. * @type {number}
  29833. * @default 1
  29834. */
  29835. this.bumpScale = 1;
  29836. /**
  29837. * The texture to create a normal map. The RGB values affect the surface
  29838. * normal for each pixel fragment and change the way the color is lit. Normal
  29839. * maps do not change the actual shape of the surface, only the lighting. In
  29840. * case the material has a normal map authored using the left handed
  29841. * convention, the `y` component of `normalScale` should be negated to compensate
  29842. * for the different handedness.
  29843. *
  29844. * @type {?Texture}
  29845. * @default null
  29846. */
  29847. this.normalMap = null;
  29848. /**
  29849. * The type of normal map.
  29850. *
  29851. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29852. * @default TangentSpaceNormalMap
  29853. */
  29854. this.normalMapType = TangentSpaceNormalMap;
  29855. /**
  29856. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29857. *
  29858. * @type {Vector2}
  29859. * @default (1,1)
  29860. */
  29861. this.normalScale = new Vector2( 1, 1 );
  29862. /**
  29863. * The displacement map affects the position of the mesh's vertices. Unlike
  29864. * other maps which only affect the light and shade of the material the
  29865. * displaced vertices can cast shadows, block other objects, and otherwise
  29866. * act as real geometry. The displacement texture is an image where the value
  29867. * of each pixel (white being the highest) is mapped against, and
  29868. * repositions, the vertices of the mesh.
  29869. *
  29870. * @type {?Texture}
  29871. * @default null
  29872. */
  29873. this.displacementMap = null;
  29874. /**
  29875. * How much the displacement map affects the mesh (where black is no
  29876. * displacement, and white is maximum displacement). Without a displacement
  29877. * map set, this value is not applied.
  29878. *
  29879. * @type {number}
  29880. * @default 0
  29881. */
  29882. this.displacementScale = 1;
  29883. /**
  29884. * The offset of the displacement map's values on the mesh's vertices.
  29885. * The bias is added to the scaled sample of the displacement map.
  29886. * Without a displacement map set, this value is not applied.
  29887. *
  29888. * @type {number}
  29889. * @default 0
  29890. */
  29891. this.displacementBias = 0;
  29892. /**
  29893. * The alpha map is a grayscale texture that controls the opacity across the
  29894. * surface (black: fully transparent; white: fully opaque).
  29895. *
  29896. * Only the color of the texture is used, ignoring the alpha channel if one
  29897. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29898. * when sampling this texture due to the extra bit of precision provided for
  29899. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29900. * luminance/alpha textures will also still work as expected.
  29901. *
  29902. * @type {?Texture}
  29903. * @default null
  29904. */
  29905. this.alphaMap = null;
  29906. /**
  29907. * Whether the material is rendered with flat shading or not.
  29908. *
  29909. * @type {boolean}
  29910. * @default false
  29911. */
  29912. this.flatShading = false;
  29913. /**
  29914. * Whether the material is affected by fog or not.
  29915. *
  29916. * @type {boolean}
  29917. * @default true
  29918. */
  29919. this.fog = true;
  29920. this.setValues( parameters );
  29921. }
  29922. copy( source ) {
  29923. super.copy( source );
  29924. this.defines = { 'MATCAP': '' };
  29925. this.color.copy( source.color );
  29926. this.matcap = source.matcap;
  29927. this.map = source.map;
  29928. this.bumpMap = source.bumpMap;
  29929. this.bumpScale = source.bumpScale;
  29930. this.normalMap = source.normalMap;
  29931. this.normalMapType = source.normalMapType;
  29932. this.normalScale.copy( source.normalScale );
  29933. this.displacementMap = source.displacementMap;
  29934. this.displacementScale = source.displacementScale;
  29935. this.displacementBias = source.displacementBias;
  29936. this.alphaMap = source.alphaMap;
  29937. this.flatShading = source.flatShading;
  29938. this.fog = source.fog;
  29939. return this;
  29940. }
  29941. }
  29942. /**
  29943. * A material for rendering line primitives.
  29944. *
  29945. * Materials define the appearance of renderable 3D objects.
  29946. *
  29947. * ```js
  29948. * const material = new THREE.LineDashedMaterial( {
  29949. * color: 0xffffff,
  29950. * scale: 1,
  29951. * dashSize: 3,
  29952. * gapSize: 1,
  29953. * } );
  29954. * ```
  29955. *
  29956. * @augments LineBasicMaterial
  29957. */
  29958. class LineDashedMaterial extends LineBasicMaterial {
  29959. /**
  29960. * Constructs a new line dashed material.
  29961. *
  29962. * @param {Object} [parameters] - An object with one or more properties
  29963. * defining the material's appearance. Any property of the material
  29964. * (including any property from inherited materials) can be passed
  29965. * in here. Color values can be passed any type of value accepted
  29966. * by {@link Color#set}.
  29967. */
  29968. constructor( parameters ) {
  29969. super();
  29970. /**
  29971. * This flag can be used for type testing.
  29972. *
  29973. * @type {boolean}
  29974. * @readonly
  29975. * @default true
  29976. */
  29977. this.isLineDashedMaterial = true;
  29978. this.type = 'LineDashedMaterial';
  29979. /**
  29980. * The scale of the dashed part of a line.
  29981. *
  29982. * @type {number}
  29983. * @default 1
  29984. */
  29985. this.scale = 1;
  29986. /**
  29987. * The size of the dash. This is both the gap with the stroke.
  29988. *
  29989. * @type {number}
  29990. * @default 3
  29991. */
  29992. this.dashSize = 3;
  29993. /**
  29994. * The size of the gap.
  29995. *
  29996. * @type {number}
  29997. * @default 1
  29998. */
  29999. this.gapSize = 1;
  30000. this.setValues( parameters );
  30001. }
  30002. copy( source ) {
  30003. super.copy( source );
  30004. this.scale = source.scale;
  30005. this.dashSize = source.dashSize;
  30006. this.gapSize = source.gapSize;
  30007. return this;
  30008. }
  30009. }
  30010. /**
  30011. * Converts an array to a specific type.
  30012. *
  30013. * @param {TypedArray|Array} array - The array to convert.
  30014. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30015. * @return {TypedArray} The converted array.
  30016. */
  30017. function convertArray( array, type ) {
  30018. if ( ! array || array.constructor === type ) return array;
  30019. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30020. return new type( array ); // create typed array
  30021. }
  30022. return Array.prototype.slice.call( array ); // create Array
  30023. }
  30024. /**
  30025. * Returns `true` if the given object is a typed array.
  30026. *
  30027. * @param {any} object - The object to check.
  30028. * @return {boolean} Whether the given object is a typed array.
  30029. */
  30030. function isTypedArray( object ) {
  30031. return ArrayBuffer.isView( object ) && ! ( object instanceof DataView );
  30032. }
  30033. /**
  30034. * Returns an array by which times and values can be sorted.
  30035. *
  30036. * @param {Array<number>} times - The keyframe time values.
  30037. * @return {Array<number>} The array.
  30038. */
  30039. function getKeyframeOrder( times ) {
  30040. function compareTime( i, j ) {
  30041. return times[ i ] - times[ j ];
  30042. }
  30043. const n = times.length;
  30044. const result = new Array( n );
  30045. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30046. result.sort( compareTime );
  30047. return result;
  30048. }
  30049. /**
  30050. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30051. *
  30052. * @param {Array<number>} values - The values to sort.
  30053. * @param {number} stride - The stride.
  30054. * @param {Array<number>} order - The sort order.
  30055. * @return {Array<number>} The sorted values.
  30056. */
  30057. function sortedArray( values, stride, order ) {
  30058. const nValues = values.length;
  30059. const result = new values.constructor( nValues );
  30060. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30061. const srcOffset = order[ i ] * stride;
  30062. for ( let j = 0; j !== stride; ++ j ) {
  30063. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30064. }
  30065. }
  30066. return result;
  30067. }
  30068. /**
  30069. * Used for parsing AOS keyframe formats.
  30070. *
  30071. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30072. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30073. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30074. * @param {string} valuePropertyName - The name of the property to use.
  30075. */
  30076. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30077. let i = 1, key = jsonKeys[ 0 ];
  30078. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30079. key = jsonKeys[ i ++ ];
  30080. }
  30081. if ( key === undefined ) return; // no data
  30082. let value = key[ valuePropertyName ];
  30083. if ( value === undefined ) return; // no data
  30084. if ( Array.isArray( value ) ) {
  30085. do {
  30086. value = key[ valuePropertyName ];
  30087. if ( value !== undefined ) {
  30088. times.push( key.time );
  30089. values.push( ...value ); // push all elements
  30090. }
  30091. key = jsonKeys[ i ++ ];
  30092. } while ( key !== undefined );
  30093. } else if ( value.toArray !== undefined ) {
  30094. // ...assume THREE.Math-ish
  30095. do {
  30096. value = key[ valuePropertyName ];
  30097. if ( value !== undefined ) {
  30098. times.push( key.time );
  30099. value.toArray( values, values.length );
  30100. }
  30101. key = jsonKeys[ i ++ ];
  30102. } while ( key !== undefined );
  30103. } else {
  30104. // otherwise push as-is
  30105. do {
  30106. value = key[ valuePropertyName ];
  30107. if ( value !== undefined ) {
  30108. times.push( key.time );
  30109. values.push( value );
  30110. }
  30111. key = jsonKeys[ i ++ ];
  30112. } while ( key !== undefined );
  30113. }
  30114. }
  30115. /**
  30116. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30117. *
  30118. * @param {AnimationClip} sourceClip - The values to sort.
  30119. * @param {string} name - The name of the clip.
  30120. * @param {number} startFrame - The start frame.
  30121. * @param {number} endFrame - The end frame.
  30122. * @param {number} [fps=30] - The FPS.
  30123. * @return {AnimationClip} The new sub clip.
  30124. */
  30125. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30126. const clip = sourceClip.clone();
  30127. clip.name = name;
  30128. const tracks = [];
  30129. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30130. const track = clip.tracks[ i ];
  30131. const valueSize = track.getValueSize();
  30132. const times = [];
  30133. const values = [];
  30134. for ( let j = 0; j < track.times.length; ++ j ) {
  30135. const frame = track.times[ j ] * fps;
  30136. if ( frame < startFrame || frame >= endFrame ) continue;
  30137. times.push( track.times[ j ] );
  30138. for ( let k = 0; k < valueSize; ++ k ) {
  30139. values.push( track.values[ j * valueSize + k ] );
  30140. }
  30141. }
  30142. if ( times.length === 0 ) continue;
  30143. track.times = convertArray( times, track.times.constructor );
  30144. track.values = convertArray( values, track.values.constructor );
  30145. tracks.push( track );
  30146. }
  30147. clip.tracks = tracks;
  30148. // find minimum .times value across all tracks in the trimmed clip
  30149. let minStartTime = Infinity;
  30150. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30151. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30152. minStartTime = clip.tracks[ i ].times[ 0 ];
  30153. }
  30154. }
  30155. // shift all tracks such that clip begins at t=0
  30156. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30157. clip.tracks[ i ].shift( -1 * minStartTime );
  30158. }
  30159. clip.resetDuration();
  30160. return clip;
  30161. }
  30162. /**
  30163. * Converts the keyframes of the given animation clip to an additive format.
  30164. *
  30165. * @param {AnimationClip} targetClip - The clip to make additive.
  30166. * @param {number} [referenceFrame=0] - The reference frame.
  30167. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30168. * @param {number} [fps=30] - The FPS.
  30169. * @return {AnimationClip} The updated clip which is now additive.
  30170. */
  30171. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30172. if ( fps <= 0 ) fps = 30;
  30173. const numTracks = referenceClip.tracks.length;
  30174. const referenceTime = referenceFrame / fps;
  30175. // Make each track's values relative to the values at the reference frame
  30176. for ( let i = 0; i < numTracks; ++ i ) {
  30177. const referenceTrack = referenceClip.tracks[ i ];
  30178. const referenceTrackType = referenceTrack.ValueTypeName;
  30179. // Skip this track if it's non-numeric
  30180. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30181. // Find the track in the target clip whose name and type matches the reference track
  30182. const targetTrack = targetClip.tracks.find( function ( track ) {
  30183. return track.name === referenceTrack.name
  30184. && track.ValueTypeName === referenceTrackType;
  30185. } );
  30186. if ( targetTrack === undefined ) continue;
  30187. let referenceOffset = 0;
  30188. const referenceValueSize = referenceTrack.getValueSize();
  30189. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30190. referenceOffset = referenceValueSize / 3;
  30191. }
  30192. let targetOffset = 0;
  30193. const targetValueSize = targetTrack.getValueSize();
  30194. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30195. targetOffset = targetValueSize / 3;
  30196. }
  30197. const lastIndex = referenceTrack.times.length - 1;
  30198. let referenceValue;
  30199. // Find the value to subtract out of the track
  30200. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30201. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30202. const startIndex = referenceOffset;
  30203. const endIndex = referenceValueSize - referenceOffset;
  30204. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30205. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30206. // Reference frame is after the last keyframe, so just use the last keyframe
  30207. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30208. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30209. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30210. } else {
  30211. // Interpolate to the reference value
  30212. const interpolant = referenceTrack.createInterpolant();
  30213. const startIndex = referenceOffset;
  30214. const endIndex = referenceValueSize - referenceOffset;
  30215. interpolant.evaluate( referenceTime );
  30216. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30217. }
  30218. // Conjugate the quaternion
  30219. if ( referenceTrackType === 'quaternion' ) {
  30220. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30221. referenceQuat.toArray( referenceValue );
  30222. }
  30223. // Subtract the reference value from all of the track values
  30224. const numTimes = targetTrack.times.length;
  30225. for ( let j = 0; j < numTimes; ++ j ) {
  30226. const valueStart = j * targetValueSize + targetOffset;
  30227. if ( referenceTrackType === 'quaternion' ) {
  30228. // Multiply the conjugate for quaternion track types
  30229. Quaternion.multiplyQuaternionsFlat(
  30230. targetTrack.values,
  30231. valueStart,
  30232. referenceValue,
  30233. 0,
  30234. targetTrack.values,
  30235. valueStart
  30236. );
  30237. } else {
  30238. const valueEnd = targetValueSize - targetOffset * 2;
  30239. // Subtract each value for all other numeric track types
  30240. for ( let k = 0; k < valueEnd; ++ k ) {
  30241. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30242. }
  30243. }
  30244. }
  30245. }
  30246. targetClip.blendMode = AdditiveAnimationBlendMode;
  30247. return targetClip;
  30248. }
  30249. /**
  30250. * A class with various methods to assist with animations.
  30251. *
  30252. * @hideconstructor
  30253. */
  30254. class AnimationUtils {
  30255. /**
  30256. * Converts an array to a specific type
  30257. *
  30258. * @static
  30259. * @param {TypedArray|Array} array - The array to convert.
  30260. * @param {TypedArray.constructor} type - The constructor of a type array.
  30261. * @return {TypedArray} The converted array
  30262. */
  30263. static convertArray( array, type ) {
  30264. return convertArray( array, type );
  30265. }
  30266. /**
  30267. * Returns `true` if the given object is a typed array.
  30268. *
  30269. * @static
  30270. * @param {any} object - The object to check.
  30271. * @return {boolean} Whether the given object is a typed array.
  30272. */
  30273. static isTypedArray( object ) {
  30274. return isTypedArray( object );
  30275. }
  30276. /**
  30277. * Returns an array by which times and values can be sorted.
  30278. *
  30279. * @static
  30280. * @param {Array<number>} times - The keyframe time values.
  30281. * @return {Array<number>} The array.
  30282. */
  30283. static getKeyframeOrder( times ) {
  30284. return getKeyframeOrder( times );
  30285. }
  30286. /**
  30287. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30288. *
  30289. * @static
  30290. * @param {Array<number>} values - The values to sort.
  30291. * @param {number} stride - The stride.
  30292. * @param {Array<number>} order - The sort order.
  30293. * @return {Array<number>} The sorted values.
  30294. */
  30295. static sortedArray( values, stride, order ) {
  30296. return sortedArray( values, stride, order );
  30297. }
  30298. /**
  30299. * Used for parsing AOS keyframe formats.
  30300. *
  30301. * @static
  30302. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30303. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30304. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30305. * @param {string} valuePropertyName - The name of the property to use.
  30306. */
  30307. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30308. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30309. }
  30310. /**
  30311. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30312. *
  30313. * @static
  30314. * @param {AnimationClip} sourceClip - The values to sort.
  30315. * @param {string} name - The name of the clip.
  30316. * @param {number} startFrame - The start frame.
  30317. * @param {number} endFrame - The end frame.
  30318. * @param {number} [fps=30] - The FPS.
  30319. * @return {AnimationClip} The new sub clip.
  30320. */
  30321. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30322. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30323. }
  30324. /**
  30325. * Converts the keyframes of the given animation clip to an additive format.
  30326. *
  30327. * @static
  30328. * @param {AnimationClip} targetClip - The clip to make additive.
  30329. * @param {number} [referenceFrame=0] - The reference frame.
  30330. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30331. * @param {number} [fps=30] - The FPS.
  30332. * @return {AnimationClip} The updated clip which is now additive.
  30333. */
  30334. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30335. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30336. }
  30337. }
  30338. /**
  30339. * Abstract base class of interpolants over parametric samples.
  30340. *
  30341. * The parameter domain is one dimensional, typically the time or a path
  30342. * along a curve defined by the data.
  30343. *
  30344. * The sample values can have any dimensionality and derived classes may
  30345. * apply special interpretations to the data.
  30346. *
  30347. * This class provides the interval seek in a Template Method, deferring
  30348. * the actual interpolation to derived classes.
  30349. *
  30350. * Time complexity is O(1) for linear access crossing at most two points
  30351. * and O(log N) for random access, where N is the number of positions.
  30352. *
  30353. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30354. *
  30355. * @abstract
  30356. */
  30357. class Interpolant {
  30358. /**
  30359. * Constructs a new interpolant.
  30360. *
  30361. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30362. * @param {TypedArray} sampleValues - The sample values.
  30363. * @param {number} sampleSize - The sample size
  30364. * @param {TypedArray} [resultBuffer] - The result buffer.
  30365. */
  30366. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30367. /**
  30368. * The parameter positions.
  30369. *
  30370. * @type {TypedArray}
  30371. */
  30372. this.parameterPositions = parameterPositions;
  30373. /**
  30374. * A cache index.
  30375. *
  30376. * @private
  30377. * @type {number}
  30378. * @default 0
  30379. */
  30380. this._cachedIndex = 0;
  30381. /**
  30382. * The result buffer.
  30383. *
  30384. * @type {TypedArray}
  30385. */
  30386. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30387. /**
  30388. * The sample values.
  30389. *
  30390. * @type {TypedArray}
  30391. */
  30392. this.sampleValues = sampleValues;
  30393. /**
  30394. * The value size.
  30395. *
  30396. * @type {TypedArray}
  30397. */
  30398. this.valueSize = sampleSize;
  30399. /**
  30400. * The interpolation settings.
  30401. *
  30402. * @type {?Object}
  30403. * @default null
  30404. */
  30405. this.settings = null;
  30406. /**
  30407. * The default settings object.
  30408. *
  30409. * @type {Object}
  30410. */
  30411. this.DefaultSettings_ = {};
  30412. }
  30413. /**
  30414. * Evaluate the interpolant at position `t`.
  30415. *
  30416. * @param {number} t - The interpolation factor.
  30417. * @return {TypedArray} The result buffer.
  30418. */
  30419. evaluate( t ) {
  30420. const pp = this.parameterPositions;
  30421. let i1 = this._cachedIndex,
  30422. t1 = pp[ i1 ],
  30423. t0 = pp[ i1 - 1 ];
  30424. validate_interval: {
  30425. seek: {
  30426. let right;
  30427. linear_scan: {
  30428. //- See http://jsperf.com/comparison-to-undefined/3
  30429. //- slower code:
  30430. //-
  30431. //- if ( t >= t1 || t1 === undefined ) {
  30432. forward_scan: if ( ! ( t < t1 ) ) {
  30433. for ( let giveUpAt = i1 + 2; ; ) {
  30434. if ( t1 === undefined ) {
  30435. if ( t < t0 ) break forward_scan;
  30436. // after end
  30437. i1 = pp.length;
  30438. this._cachedIndex = i1;
  30439. return this.copySampleValue_( i1 - 1 );
  30440. }
  30441. if ( i1 === giveUpAt ) break; // this loop
  30442. t0 = t1;
  30443. t1 = pp[ ++ i1 ];
  30444. if ( t < t1 ) {
  30445. // we have arrived at the sought interval
  30446. break seek;
  30447. }
  30448. }
  30449. // prepare binary search on the right side of the index
  30450. right = pp.length;
  30451. break linear_scan;
  30452. }
  30453. //- slower code:
  30454. //- if ( t < t0 || t0 === undefined ) {
  30455. if ( ! ( t >= t0 ) ) {
  30456. // looping?
  30457. const t1global = pp[ 1 ];
  30458. if ( t < t1global ) {
  30459. i1 = 2; // + 1, using the scan for the details
  30460. t0 = t1global;
  30461. }
  30462. // linear reverse scan
  30463. for ( let giveUpAt = i1 - 2; ; ) {
  30464. if ( t0 === undefined ) {
  30465. // before start
  30466. this._cachedIndex = 0;
  30467. return this.copySampleValue_( 0 );
  30468. }
  30469. if ( i1 === giveUpAt ) break; // this loop
  30470. t1 = t0;
  30471. t0 = pp[ -- i1 - 1 ];
  30472. if ( t >= t0 ) {
  30473. // we have arrived at the sought interval
  30474. break seek;
  30475. }
  30476. }
  30477. // prepare binary search on the left side of the index
  30478. right = i1;
  30479. i1 = 0;
  30480. break linear_scan;
  30481. }
  30482. // the interval is valid
  30483. break validate_interval;
  30484. } // linear scan
  30485. // binary search
  30486. while ( i1 < right ) {
  30487. const mid = ( i1 + right ) >>> 1;
  30488. if ( t < pp[ mid ] ) {
  30489. right = mid;
  30490. } else {
  30491. i1 = mid + 1;
  30492. }
  30493. }
  30494. t1 = pp[ i1 ];
  30495. t0 = pp[ i1 - 1 ];
  30496. // check boundary cases, again
  30497. if ( t0 === undefined ) {
  30498. this._cachedIndex = 0;
  30499. return this.copySampleValue_( 0 );
  30500. }
  30501. if ( t1 === undefined ) {
  30502. i1 = pp.length;
  30503. this._cachedIndex = i1;
  30504. return this.copySampleValue_( i1 - 1 );
  30505. }
  30506. } // seek
  30507. this._cachedIndex = i1;
  30508. this.intervalChanged_( i1, t0, t1 );
  30509. } // validate_interval
  30510. return this.interpolate_( i1, t0, t, t1 );
  30511. }
  30512. /**
  30513. * Returns the interpolation settings.
  30514. *
  30515. * @return {Object} The interpolation settings.
  30516. */
  30517. getSettings_() {
  30518. return this.settings || this.DefaultSettings_;
  30519. }
  30520. /**
  30521. * Copies a sample value to the result buffer.
  30522. *
  30523. * @param {number} index - An index into the sample value buffer.
  30524. * @return {TypedArray} The result buffer.
  30525. */
  30526. copySampleValue_( index ) {
  30527. // copies a sample value to the result buffer
  30528. const result = this.resultBuffer,
  30529. values = this.sampleValues,
  30530. stride = this.valueSize,
  30531. offset = index * stride;
  30532. for ( let i = 0; i !== stride; ++ i ) {
  30533. result[ i ] = values[ offset + i ];
  30534. }
  30535. return result;
  30536. }
  30537. /**
  30538. * Copies a sample value to the result buffer.
  30539. *
  30540. * @abstract
  30541. * @param {number} i1 - An index into the sample value buffer.
  30542. * @param {number} t0 - The previous interpolation factor.
  30543. * @param {number} t - The current interpolation factor.
  30544. * @param {number} t1 - The next interpolation factor.
  30545. * @return {TypedArray} The result buffer.
  30546. */
  30547. interpolate_( /* i1, t0, t, t1 */ ) {
  30548. throw new Error( 'call to abstract method' );
  30549. // implementations shall return this.resultBuffer
  30550. }
  30551. /**
  30552. * Optional method that is executed when the interval has changed.
  30553. *
  30554. * @param {number} i1 - An index into the sample value buffer.
  30555. * @param {number} t0 - The previous interpolation factor.
  30556. * @param {number} t - The current interpolation factor.
  30557. */
  30558. intervalChanged_( /* i1, t0, t1 */ ) {
  30559. // empty
  30560. }
  30561. }
  30562. /**
  30563. * Fast and simple cubic spline interpolant.
  30564. *
  30565. * It was derived from a Hermitian construction setting the first derivative
  30566. * at each sample position to the linear slope between neighboring positions
  30567. * over their parameter interval.
  30568. *
  30569. * @augments Interpolant
  30570. */
  30571. class CubicInterpolant extends Interpolant {
  30572. /**
  30573. * Constructs a new cubic interpolant.
  30574. *
  30575. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30576. * @param {TypedArray} sampleValues - The sample values.
  30577. * @param {number} sampleSize - The sample size
  30578. * @param {TypedArray} [resultBuffer] - The result buffer.
  30579. */
  30580. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30581. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30582. this._weightPrev = -0;
  30583. this._offsetPrev = -0;
  30584. this._weightNext = -0;
  30585. this._offsetNext = -0;
  30586. this.DefaultSettings_ = {
  30587. endingStart: ZeroCurvatureEnding,
  30588. endingEnd: ZeroCurvatureEnding
  30589. };
  30590. }
  30591. intervalChanged_( i1, t0, t1 ) {
  30592. const pp = this.parameterPositions;
  30593. let iPrev = i1 - 2,
  30594. iNext = i1 + 1,
  30595. tPrev = pp[ iPrev ],
  30596. tNext = pp[ iNext ];
  30597. if ( tPrev === undefined ) {
  30598. switch ( this.getSettings_().endingStart ) {
  30599. case ZeroSlopeEnding:
  30600. // f'(t0) = 0
  30601. iPrev = i1;
  30602. tPrev = 2 * t0 - t1;
  30603. break;
  30604. case WrapAroundEnding:
  30605. // use the other end of the curve
  30606. iPrev = pp.length - 2;
  30607. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30608. break;
  30609. default: // ZeroCurvatureEnding
  30610. // f''(t0) = 0 a.k.a. Natural Spline
  30611. iPrev = i1;
  30612. tPrev = t1;
  30613. }
  30614. }
  30615. if ( tNext === undefined ) {
  30616. switch ( this.getSettings_().endingEnd ) {
  30617. case ZeroSlopeEnding:
  30618. // f'(tN) = 0
  30619. iNext = i1;
  30620. tNext = 2 * t1 - t0;
  30621. break;
  30622. case WrapAroundEnding:
  30623. // use the other end of the curve
  30624. iNext = 1;
  30625. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30626. break;
  30627. default: // ZeroCurvatureEnding
  30628. // f''(tN) = 0, a.k.a. Natural Spline
  30629. iNext = i1 - 1;
  30630. tNext = t0;
  30631. }
  30632. }
  30633. const halfDt = ( t1 - t0 ) * 0.5,
  30634. stride = this.valueSize;
  30635. this._weightPrev = halfDt / ( t0 - tPrev );
  30636. this._weightNext = halfDt / ( tNext - t1 );
  30637. this._offsetPrev = iPrev * stride;
  30638. this._offsetNext = iNext * stride;
  30639. }
  30640. interpolate_( i1, t0, t, t1 ) {
  30641. const result = this.resultBuffer,
  30642. values = this.sampleValues,
  30643. stride = this.valueSize,
  30644. o1 = i1 * stride, o0 = o1 - stride,
  30645. oP = this._offsetPrev, oN = this._offsetNext,
  30646. wP = this._weightPrev, wN = this._weightNext,
  30647. p = ( t - t0 ) / ( t1 - t0 ),
  30648. pp = p * p,
  30649. ppp = pp * p;
  30650. // evaluate polynomials
  30651. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30652. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30653. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30654. const sN = wN * ppp - wN * pp;
  30655. // combine data linearly
  30656. for ( let i = 0; i !== stride; ++ i ) {
  30657. result[ i ] =
  30658. sP * values[ oP + i ] +
  30659. s0 * values[ o0 + i ] +
  30660. s1 * values[ o1 + i ] +
  30661. sN * values[ oN + i ];
  30662. }
  30663. return result;
  30664. }
  30665. }
  30666. /**
  30667. * A basic linear interpolant.
  30668. *
  30669. * @augments Interpolant
  30670. */
  30671. class LinearInterpolant extends Interpolant {
  30672. /**
  30673. * Constructs a new linear interpolant.
  30674. *
  30675. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30676. * @param {TypedArray} sampleValues - The sample values.
  30677. * @param {number} sampleSize - The sample size
  30678. * @param {TypedArray} [resultBuffer] - The result buffer.
  30679. */
  30680. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30681. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30682. }
  30683. interpolate_( i1, t0, t, t1 ) {
  30684. const result = this.resultBuffer,
  30685. values = this.sampleValues,
  30686. stride = this.valueSize,
  30687. offset1 = i1 * stride,
  30688. offset0 = offset1 - stride,
  30689. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30690. weight0 = 1 - weight1;
  30691. for ( let i = 0; i !== stride; ++ i ) {
  30692. result[ i ] =
  30693. values[ offset0 + i ] * weight0 +
  30694. values[ offset1 + i ] * weight1;
  30695. }
  30696. return result;
  30697. }
  30698. }
  30699. /**
  30700. * Interpolant that evaluates to the sample value at the position preceding
  30701. * the parameter.
  30702. *
  30703. * @augments Interpolant
  30704. */
  30705. class DiscreteInterpolant extends Interpolant {
  30706. /**
  30707. * Constructs a new discrete interpolant.
  30708. *
  30709. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30710. * @param {TypedArray} sampleValues - The sample values.
  30711. * @param {number} sampleSize - The sample size
  30712. * @param {TypedArray} [resultBuffer] - The result buffer.
  30713. */
  30714. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30715. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30716. }
  30717. interpolate_( i1 /*, t0, t, t1 */ ) {
  30718. return this.copySampleValue_( i1 - 1 );
  30719. }
  30720. }
  30721. /**
  30722. * Represents s a timed sequence of keyframes, which are composed of lists of
  30723. * times and related values, and which are used to animate a specific property
  30724. * of an object.
  30725. */
  30726. class KeyframeTrack {
  30727. /**
  30728. * Constructs a new keyframe track.
  30729. *
  30730. * @param {string} name - The keyframe track's name.
  30731. * @param {Array<number>} times - A list of keyframe times.
  30732. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30733. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30734. */
  30735. constructor( name, times, values, interpolation ) {
  30736. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30737. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30738. /**
  30739. * The track's name can refer to morph targets or bones or
  30740. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30741. * for the forms of strings that can be parsed for property binding.
  30742. *
  30743. * @type {string}
  30744. */
  30745. this.name = name;
  30746. /**
  30747. * The keyframe times.
  30748. *
  30749. * @type {Float32Array}
  30750. */
  30751. this.times = convertArray( times, this.TimeBufferType );
  30752. /**
  30753. * The keyframe values.
  30754. *
  30755. * @type {Float32Array}
  30756. */
  30757. this.values = convertArray( values, this.ValueBufferType );
  30758. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30759. }
  30760. /**
  30761. * Converts the keyframe track to JSON.
  30762. *
  30763. * @static
  30764. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30765. * @return {Object} The serialized keyframe track as JSON.
  30766. */
  30767. static toJSON( track ) {
  30768. const trackType = track.constructor;
  30769. let json;
  30770. // derived classes can define a static toJSON method
  30771. if ( trackType.toJSON !== this.toJSON ) {
  30772. json = trackType.toJSON( track );
  30773. } else {
  30774. // by default, we assume the data can be serialized as-is
  30775. json = {
  30776. 'name': track.name,
  30777. 'times': convertArray( track.times, Array ),
  30778. 'values': convertArray( track.values, Array )
  30779. };
  30780. const interpolation = track.getInterpolation();
  30781. if ( interpolation !== track.DefaultInterpolation ) {
  30782. json.interpolation = interpolation;
  30783. }
  30784. }
  30785. json.type = track.ValueTypeName; // mandatory
  30786. return json;
  30787. }
  30788. /**
  30789. * Factory method for creating a new discrete interpolant.
  30790. *
  30791. * @static
  30792. * @param {TypedArray} [result] - The result buffer.
  30793. * @return {DiscreteInterpolant} The new interpolant.
  30794. */
  30795. InterpolantFactoryMethodDiscrete( result ) {
  30796. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30797. }
  30798. /**
  30799. * Factory method for creating a new linear interpolant.
  30800. *
  30801. * @static
  30802. * @param {TypedArray} [result] - The result buffer.
  30803. * @return {LinearInterpolant} The new interpolant.
  30804. */
  30805. InterpolantFactoryMethodLinear( result ) {
  30806. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30807. }
  30808. /**
  30809. * Factory method for creating a new smooth interpolant.
  30810. *
  30811. * @static
  30812. * @param {TypedArray} [result] - The result buffer.
  30813. * @return {CubicInterpolant} The new interpolant.
  30814. */
  30815. InterpolantFactoryMethodSmooth( result ) {
  30816. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  30817. }
  30818. /**
  30819. * Defines the interpolation factor method for this keyframe track.
  30820. *
  30821. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  30822. * @return {KeyframeTrack} A reference to this keyframe track.
  30823. */
  30824. setInterpolation( interpolation ) {
  30825. let factoryMethod;
  30826. switch ( interpolation ) {
  30827. case InterpolateDiscrete:
  30828. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  30829. break;
  30830. case InterpolateLinear:
  30831. factoryMethod = this.InterpolantFactoryMethodLinear;
  30832. break;
  30833. case InterpolateSmooth:
  30834. factoryMethod = this.InterpolantFactoryMethodSmooth;
  30835. break;
  30836. }
  30837. if ( factoryMethod === undefined ) {
  30838. const message = 'unsupported interpolation for ' +
  30839. this.ValueTypeName + ' keyframe track named ' + this.name;
  30840. if ( this.createInterpolant === undefined ) {
  30841. // fall back to default, unless the default itself is messed up
  30842. if ( interpolation !== this.DefaultInterpolation ) {
  30843. this.setInterpolation( this.DefaultInterpolation );
  30844. } else {
  30845. throw new Error( message ); // fatal, in this case
  30846. }
  30847. }
  30848. warn( 'KeyframeTrack:', message );
  30849. return this;
  30850. }
  30851. this.createInterpolant = factoryMethod;
  30852. return this;
  30853. }
  30854. /**
  30855. * Returns the current interpolation type.
  30856. *
  30857. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  30858. */
  30859. getInterpolation() {
  30860. switch ( this.createInterpolant ) {
  30861. case this.InterpolantFactoryMethodDiscrete:
  30862. return InterpolateDiscrete;
  30863. case this.InterpolantFactoryMethodLinear:
  30864. return InterpolateLinear;
  30865. case this.InterpolantFactoryMethodSmooth:
  30866. return InterpolateSmooth;
  30867. }
  30868. }
  30869. /**
  30870. * Returns the value size.
  30871. *
  30872. * @return {number} The value size.
  30873. */
  30874. getValueSize() {
  30875. return this.values.length / this.times.length;
  30876. }
  30877. /**
  30878. * Moves all keyframes either forward or backward in time.
  30879. *
  30880. * @param {number} timeOffset - The offset to move the time values.
  30881. * @return {KeyframeTrack} A reference to this keyframe track.
  30882. */
  30883. shift( timeOffset ) {
  30884. if ( timeOffset !== 0.0 ) {
  30885. const times = this.times;
  30886. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30887. times[ i ] += timeOffset;
  30888. }
  30889. }
  30890. return this;
  30891. }
  30892. /**
  30893. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  30894. *
  30895. * @param {number} timeScale - The time scale.
  30896. * @return {KeyframeTrack} A reference to this keyframe track.
  30897. */
  30898. scale( timeScale ) {
  30899. if ( timeScale !== 1.0 ) {
  30900. const times = this.times;
  30901. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  30902. times[ i ] *= timeScale;
  30903. }
  30904. }
  30905. return this;
  30906. }
  30907. /**
  30908. * Removes keyframes before and after animation without changing any values within the defined time range.
  30909. *
  30910. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  30911. * keys this will change their values
  30912. *
  30913. * @param {number} startTime - The start time.
  30914. * @param {number} endTime - The end time.
  30915. * @return {KeyframeTrack} A reference to this keyframe track.
  30916. */
  30917. trim( startTime, endTime ) {
  30918. const times = this.times,
  30919. nKeys = times.length;
  30920. let from = 0,
  30921. to = nKeys - 1;
  30922. while ( from !== nKeys && times[ from ] < startTime ) {
  30923. ++ from;
  30924. }
  30925. while ( to !== -1 && times[ to ] > endTime ) {
  30926. -- to;
  30927. }
  30928. ++ to; // inclusive -> exclusive bound
  30929. if ( from !== 0 || to !== nKeys ) {
  30930. // empty tracks are forbidden, so keep at least one keyframe
  30931. if ( from >= to ) {
  30932. to = Math.max( to, 1 );
  30933. from = to - 1;
  30934. }
  30935. const stride = this.getValueSize();
  30936. this.times = times.slice( from, to );
  30937. this.values = this.values.slice( from * stride, to * stride );
  30938. }
  30939. return this;
  30940. }
  30941. /**
  30942. * Performs minimal validation on the keyframe track. Returns `true` if the values
  30943. * are valid.
  30944. *
  30945. * @return {boolean} Whether the keyframes are valid or not.
  30946. */
  30947. validate() {
  30948. let valid = true;
  30949. const valueSize = this.getValueSize();
  30950. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  30951. error( 'KeyframeTrack: Invalid value size in track.', this );
  30952. valid = false;
  30953. }
  30954. const times = this.times,
  30955. values = this.values,
  30956. nKeys = times.length;
  30957. if ( nKeys === 0 ) {
  30958. error( 'KeyframeTrack: Track is empty.', this );
  30959. valid = false;
  30960. }
  30961. let prevTime = null;
  30962. for ( let i = 0; i !== nKeys; i ++ ) {
  30963. const currTime = times[ i ];
  30964. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  30965. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  30966. valid = false;
  30967. break;
  30968. }
  30969. if ( prevTime !== null && prevTime > currTime ) {
  30970. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  30971. valid = false;
  30972. break;
  30973. }
  30974. prevTime = currTime;
  30975. }
  30976. if ( values !== undefined ) {
  30977. if ( isTypedArray( values ) ) {
  30978. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  30979. const value = values[ i ];
  30980. if ( isNaN( value ) ) {
  30981. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  30982. valid = false;
  30983. break;
  30984. }
  30985. }
  30986. }
  30987. }
  30988. return valid;
  30989. }
  30990. /**
  30991. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  30992. * common in morph target sequences).
  30993. *
  30994. * @return {AnimationClip} A reference to this animation clip.
  30995. */
  30996. optimize() {
  30997. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  30998. // times or values may be shared with other tracks, so overwriting is unsafe
  30999. const times = this.times.slice(),
  31000. values = this.values.slice(),
  31001. stride = this.getValueSize(),
  31002. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31003. lastIndex = times.length - 1;
  31004. let writeIndex = 1;
  31005. for ( let i = 1; i < lastIndex; ++ i ) {
  31006. let keep = false;
  31007. const time = times[ i ];
  31008. const timeNext = times[ i + 1 ];
  31009. // remove adjacent keyframes scheduled at the same time
  31010. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31011. if ( ! smoothInterpolation ) {
  31012. // remove unnecessary keyframes same as their neighbors
  31013. const offset = i * stride,
  31014. offsetP = offset - stride,
  31015. offsetN = offset + stride;
  31016. for ( let j = 0; j !== stride; ++ j ) {
  31017. const value = values[ offset + j ];
  31018. if ( value !== values[ offsetP + j ] ||
  31019. value !== values[ offsetN + j ] ) {
  31020. keep = true;
  31021. break;
  31022. }
  31023. }
  31024. } else {
  31025. keep = true;
  31026. }
  31027. }
  31028. // in-place compaction
  31029. if ( keep ) {
  31030. if ( i !== writeIndex ) {
  31031. times[ writeIndex ] = times[ i ];
  31032. const readOffset = i * stride,
  31033. writeOffset = writeIndex * stride;
  31034. for ( let j = 0; j !== stride; ++ j ) {
  31035. values[ writeOffset + j ] = values[ readOffset + j ];
  31036. }
  31037. }
  31038. ++ writeIndex;
  31039. }
  31040. }
  31041. // flush last keyframe (compaction looks ahead)
  31042. if ( lastIndex > 0 ) {
  31043. times[ writeIndex ] = times[ lastIndex ];
  31044. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31045. values[ writeOffset + j ] = values[ readOffset + j ];
  31046. }
  31047. ++ writeIndex;
  31048. }
  31049. if ( writeIndex !== times.length ) {
  31050. this.times = times.slice( 0, writeIndex );
  31051. this.values = values.slice( 0, writeIndex * stride );
  31052. } else {
  31053. this.times = times;
  31054. this.values = values;
  31055. }
  31056. return this;
  31057. }
  31058. /**
  31059. * Returns a new keyframe track with copied values from this instance.
  31060. *
  31061. * @return {KeyframeTrack} A clone of this instance.
  31062. */
  31063. clone() {
  31064. const times = this.times.slice();
  31065. const values = this.values.slice();
  31066. const TypedKeyframeTrack = this.constructor;
  31067. const track = new TypedKeyframeTrack( this.name, times, values );
  31068. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31069. track.createInterpolant = this.createInterpolant;
  31070. return track;
  31071. }
  31072. }
  31073. /**
  31074. * The value type name.
  31075. *
  31076. * @type {String}
  31077. * @default ''
  31078. */
  31079. KeyframeTrack.prototype.ValueTypeName = '';
  31080. /**
  31081. * The time buffer type of this keyframe track.
  31082. *
  31083. * @type {TypedArray|Array}
  31084. * @default Float32Array.constructor
  31085. */
  31086. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31087. /**
  31088. * The value buffer type of this keyframe track.
  31089. *
  31090. * @type {TypedArray|Array}
  31091. * @default Float32Array.constructor
  31092. */
  31093. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31094. /**
  31095. * The default interpolation type of this keyframe track.
  31096. *
  31097. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31098. * @default InterpolateLinear
  31099. */
  31100. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31101. /**
  31102. * A track for boolean keyframe values.
  31103. *
  31104. * @augments KeyframeTrack
  31105. */
  31106. class BooleanKeyframeTrack extends KeyframeTrack {
  31107. /**
  31108. * Constructs a new boolean keyframe track.
  31109. *
  31110. * This keyframe track type has no `interpolation` parameter because the
  31111. * interpolation is always discrete.
  31112. *
  31113. * @param {string} name - The keyframe track's name.
  31114. * @param {Array<number>} times - A list of keyframe times.
  31115. * @param {Array<boolean>} values - A list of keyframe values.
  31116. */
  31117. constructor( name, times, values ) {
  31118. super( name, times, values );
  31119. }
  31120. }
  31121. /**
  31122. * The value type name.
  31123. *
  31124. * @type {String}
  31125. * @default 'bool'
  31126. */
  31127. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31128. /**
  31129. * The value buffer type of this keyframe track.
  31130. *
  31131. * @type {TypedArray|Array}
  31132. * @default Array.constructor
  31133. */
  31134. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31135. /**
  31136. * The default interpolation type of this keyframe track.
  31137. *
  31138. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31139. * @default InterpolateDiscrete
  31140. */
  31141. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31142. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31143. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31144. /**
  31145. * A track for color keyframe values.
  31146. *
  31147. * @augments KeyframeTrack
  31148. */
  31149. class ColorKeyframeTrack extends KeyframeTrack {
  31150. /**
  31151. * Constructs a new color keyframe track.
  31152. *
  31153. * @param {string} name - The keyframe track's name.
  31154. * @param {Array<number>} times - A list of keyframe times.
  31155. * @param {Array<number>} values - A list of keyframe values.
  31156. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31157. */
  31158. constructor( name, times, values, interpolation ) {
  31159. super( name, times, values, interpolation );
  31160. }
  31161. }
  31162. /**
  31163. * The value type name.
  31164. *
  31165. * @type {String}
  31166. * @default 'color'
  31167. */
  31168. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31169. /**
  31170. * A track for numeric keyframe values.
  31171. *
  31172. * @augments KeyframeTrack
  31173. */
  31174. class NumberKeyframeTrack extends KeyframeTrack {
  31175. /**
  31176. * Constructs a new number keyframe track.
  31177. *
  31178. * @param {string} name - The keyframe track's name.
  31179. * @param {Array<number>} times - A list of keyframe times.
  31180. * @param {Array<number>} values - A list of keyframe values.
  31181. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31182. */
  31183. constructor( name, times, values, interpolation ) {
  31184. super( name, times, values, interpolation );
  31185. }
  31186. }
  31187. /**
  31188. * The value type name.
  31189. *
  31190. * @type {String}
  31191. * @default 'number'
  31192. */
  31193. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31194. /**
  31195. * Spherical linear unit quaternion interpolant.
  31196. *
  31197. * @augments Interpolant
  31198. */
  31199. class QuaternionLinearInterpolant extends Interpolant {
  31200. /**
  31201. * Constructs a new SLERP interpolant.
  31202. *
  31203. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31204. * @param {TypedArray} sampleValues - The sample values.
  31205. * @param {number} sampleSize - The sample size
  31206. * @param {TypedArray} [resultBuffer] - The result buffer.
  31207. */
  31208. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31209. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31210. }
  31211. interpolate_( i1, t0, t, t1 ) {
  31212. const result = this.resultBuffer,
  31213. values = this.sampleValues,
  31214. stride = this.valueSize,
  31215. alpha = ( t - t0 ) / ( t1 - t0 );
  31216. let offset = i1 * stride;
  31217. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31218. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31219. }
  31220. return result;
  31221. }
  31222. }
  31223. /**
  31224. * A track for Quaternion keyframe values.
  31225. *
  31226. * @augments KeyframeTrack
  31227. */
  31228. class QuaternionKeyframeTrack extends KeyframeTrack {
  31229. /**
  31230. * Constructs a new Quaternion keyframe track.
  31231. *
  31232. * @param {string} name - The keyframe track's name.
  31233. * @param {Array<number>} times - A list of keyframe times.
  31234. * @param {Array<number>} values - A list of keyframe values.
  31235. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31236. */
  31237. constructor( name, times, values, interpolation ) {
  31238. super( name, times, values, interpolation );
  31239. }
  31240. /**
  31241. * Overwritten so the method returns Quaternion based interpolant.
  31242. *
  31243. * @static
  31244. * @param {TypedArray} [result] - The result buffer.
  31245. * @return {QuaternionLinearInterpolant} The new interpolant.
  31246. */
  31247. InterpolantFactoryMethodLinear( result ) {
  31248. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31249. }
  31250. }
  31251. /**
  31252. * The value type name.
  31253. *
  31254. * @type {String}
  31255. * @default 'quaternion'
  31256. */
  31257. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31258. // ValueBufferType is inherited
  31259. // DefaultInterpolation is inherited;
  31260. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31261. /**
  31262. * A track for string keyframe values.
  31263. *
  31264. * @augments KeyframeTrack
  31265. */
  31266. class StringKeyframeTrack extends KeyframeTrack {
  31267. /**
  31268. * Constructs a new string keyframe track.
  31269. *
  31270. * This keyframe track type has no `interpolation` parameter because the
  31271. * interpolation is always discrete.
  31272. *
  31273. * @param {string} name - The keyframe track's name.
  31274. * @param {Array<number>} times - A list of keyframe times.
  31275. * @param {Array<string>} values - A list of keyframe values.
  31276. */
  31277. constructor( name, times, values ) {
  31278. super( name, times, values );
  31279. }
  31280. }
  31281. /**
  31282. * The value type name.
  31283. *
  31284. * @type {String}
  31285. * @default 'string'
  31286. */
  31287. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31288. /**
  31289. * The value buffer type of this keyframe track.
  31290. *
  31291. * @type {TypedArray|Array}
  31292. * @default Array.constructor
  31293. */
  31294. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31295. /**
  31296. * The default interpolation type of this keyframe track.
  31297. *
  31298. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31299. * @default InterpolateDiscrete
  31300. */
  31301. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31302. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31303. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31304. /**
  31305. * A track for vector keyframe values.
  31306. *
  31307. * @augments KeyframeTrack
  31308. */
  31309. class VectorKeyframeTrack extends KeyframeTrack {
  31310. /**
  31311. * Constructs a new vector keyframe track.
  31312. *
  31313. * @param {string} name - The keyframe track's name.
  31314. * @param {Array<number>} times - A list of keyframe times.
  31315. * @param {Array<number>} values - A list of keyframe values.
  31316. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31317. */
  31318. constructor( name, times, values, interpolation ) {
  31319. super( name, times, values, interpolation );
  31320. }
  31321. }
  31322. /**
  31323. * The value type name.
  31324. *
  31325. * @type {String}
  31326. * @default 'vector'
  31327. */
  31328. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31329. /**
  31330. * A reusable set of keyframe tracks which represent an animation.
  31331. */
  31332. class AnimationClip {
  31333. /**
  31334. * Constructs a new animation clip.
  31335. *
  31336. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31337. * use the static interface of this class for creating clips. In most cases though, animation clips
  31338. * will automatically be created by loaders when importing animated 3D assets.
  31339. *
  31340. * @param {string} [name=''] - The clip's name.
  31341. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31342. * the duration will be calculated from the passed keyframes.
  31343. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31344. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31345. * is blended/combined when two or more animations are simultaneously played.
  31346. */
  31347. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31348. /**
  31349. * The clip's name.
  31350. *
  31351. * @type {string}
  31352. */
  31353. this.name = name;
  31354. /**
  31355. * An array of keyframe tracks.
  31356. *
  31357. * @type {Array<KeyframeTrack>}
  31358. */
  31359. this.tracks = tracks;
  31360. /**
  31361. * The clip's duration in seconds.
  31362. *
  31363. * @type {number}
  31364. */
  31365. this.duration = duration;
  31366. /**
  31367. * Defines how the animation is blended/combined when two or more animations
  31368. * are simultaneously played.
  31369. *
  31370. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31371. */
  31372. this.blendMode = blendMode;
  31373. /**
  31374. * The UUID of the animation clip.
  31375. *
  31376. * @type {string}
  31377. * @readonly
  31378. */
  31379. this.uuid = generateUUID();
  31380. /**
  31381. * An object that can be used to store custom data about the animation clip.
  31382. * It should not hold references to functions as these will not be cloned.
  31383. *
  31384. * @type {Object}
  31385. */
  31386. this.userData = {};
  31387. // this means it should figure out its duration by scanning the tracks
  31388. if ( this.duration < 0 ) {
  31389. this.resetDuration();
  31390. }
  31391. }
  31392. /**
  31393. * Factory method for creating an animation clip from the given JSON.
  31394. *
  31395. * @static
  31396. * @param {Object} json - The serialized animation clip.
  31397. * @return {AnimationClip} The new animation clip.
  31398. */
  31399. static parse( json ) {
  31400. const tracks = [],
  31401. jsonTracks = json.tracks,
  31402. frameTime = 1.0 / ( json.fps || 1.0 );
  31403. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31404. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31405. }
  31406. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31407. clip.uuid = json.uuid;
  31408. clip.userData = JSON.parse( json.userData || '{}' );
  31409. return clip;
  31410. }
  31411. /**
  31412. * Serializes the given animation clip into JSON.
  31413. *
  31414. * @static
  31415. * @param {AnimationClip} clip - The animation clip to serialize.
  31416. * @return {Object} The JSON object.
  31417. */
  31418. static toJSON( clip ) {
  31419. const tracks = [],
  31420. clipTracks = clip.tracks;
  31421. const json = {
  31422. 'name': clip.name,
  31423. 'duration': clip.duration,
  31424. 'tracks': tracks,
  31425. 'uuid': clip.uuid,
  31426. 'blendMode': clip.blendMode,
  31427. 'userData': JSON.stringify( clip.userData ),
  31428. };
  31429. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31430. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31431. }
  31432. return json;
  31433. }
  31434. /**
  31435. * Returns a new animation clip from the passed morph targets array of a
  31436. * geometry, taking a name and the number of frames per second.
  31437. *
  31438. * Note: The fps parameter is required, but the animation speed can be
  31439. * overridden via {@link AnimationAction#setDuration}.
  31440. *
  31441. * @static
  31442. * @param {string} name - The name of the animation clip.
  31443. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31444. * @param {number} fps - The Frames-Per-Second value.
  31445. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31446. * @return {AnimationClip} The new animation clip.
  31447. */
  31448. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31449. const numMorphTargets = morphTargetSequence.length;
  31450. const tracks = [];
  31451. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31452. let times = [];
  31453. let values = [];
  31454. times.push(
  31455. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31456. i,
  31457. ( i + 1 ) % numMorphTargets );
  31458. values.push( 0, 1, 0 );
  31459. const order = getKeyframeOrder( times );
  31460. times = sortedArray( times, 1, order );
  31461. values = sortedArray( values, 1, order );
  31462. // if there is a key at the first frame, duplicate it as the
  31463. // last frame as well for perfect loop.
  31464. if ( ! noLoop && times[ 0 ] === 0 ) {
  31465. times.push( numMorphTargets );
  31466. values.push( values[ 0 ] );
  31467. }
  31468. tracks.push(
  31469. new NumberKeyframeTrack(
  31470. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31471. times, values
  31472. ).scale( 1.0 / fps ) );
  31473. }
  31474. return new this( name, -1, tracks );
  31475. }
  31476. /**
  31477. * Searches for an animation clip by name, taking as its first parameter
  31478. * either an array of clips, or a mesh or geometry that contains an
  31479. * array named "animations" property.
  31480. *
  31481. * @static
  31482. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31483. * @param {string} name - The name to search for.
  31484. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31485. */
  31486. static findByName( objectOrClipArray, name ) {
  31487. let clipArray = objectOrClipArray;
  31488. if ( ! Array.isArray( objectOrClipArray ) ) {
  31489. const o = objectOrClipArray;
  31490. clipArray = o.geometry && o.geometry.animations || o.animations;
  31491. }
  31492. for ( let i = 0; i < clipArray.length; i ++ ) {
  31493. if ( clipArray[ i ].name === name ) {
  31494. return clipArray[ i ];
  31495. }
  31496. }
  31497. return null;
  31498. }
  31499. /**
  31500. * Returns an array of new AnimationClips created from the morph target
  31501. * sequences of a geometry, trying to sort morph target names into
  31502. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31503. *
  31504. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31505. *
  31506. * @static
  31507. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31508. * @param {number} fps - The Frames-Per-Second value.
  31509. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31510. * @return {Array<AnimationClip>} An array of new animation clips.
  31511. */
  31512. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31513. const animationToMorphTargets = {};
  31514. // tested with https://regex101.com/ on trick sequences
  31515. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31516. const pattern = /^([\w-]*?)([\d]+)$/;
  31517. // sort morph target names into animation groups based
  31518. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31519. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31520. const morphTarget = morphTargets[ i ];
  31521. const parts = morphTarget.name.match( pattern );
  31522. if ( parts && parts.length > 1 ) {
  31523. const name = parts[ 1 ];
  31524. let animationMorphTargets = animationToMorphTargets[ name ];
  31525. if ( ! animationMorphTargets ) {
  31526. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31527. }
  31528. animationMorphTargets.push( morphTarget );
  31529. }
  31530. }
  31531. const clips = [];
  31532. for ( const name in animationToMorphTargets ) {
  31533. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31534. }
  31535. return clips;
  31536. }
  31537. /**
  31538. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31539. *
  31540. * @static
  31541. * @deprecated since r175.
  31542. * @param {Object} animation - A serialized animation clip as JSON.
  31543. * @param {Array<Bones>} bones - An array of bones.
  31544. * @return {?AnimationClip} The new animation clip.
  31545. */
  31546. static parseAnimation( animation, bones ) {
  31547. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31548. if ( ! animation ) {
  31549. error( 'AnimationClip: No animation in JSONLoader data.' );
  31550. return null;
  31551. }
  31552. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31553. // only return track if there are actually keys.
  31554. if ( animationKeys.length !== 0 ) {
  31555. const times = [];
  31556. const values = [];
  31557. flattenJSON( animationKeys, times, values, propertyName );
  31558. // empty keys are filtered out, so check again
  31559. if ( times.length !== 0 ) {
  31560. destTracks.push( new trackType( trackName, times, values ) );
  31561. }
  31562. }
  31563. };
  31564. const tracks = [];
  31565. const clipName = animation.name || 'default';
  31566. const fps = animation.fps || 30;
  31567. const blendMode = animation.blendMode;
  31568. // automatic length determination in AnimationClip.
  31569. let duration = animation.length || -1;
  31570. const hierarchyTracks = animation.hierarchy || [];
  31571. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31572. const animationKeys = hierarchyTracks[ h ].keys;
  31573. // skip empty tracks
  31574. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31575. // process morph targets
  31576. if ( animationKeys[ 0 ].morphTargets ) {
  31577. // figure out all morph targets used in this track
  31578. const morphTargetNames = {};
  31579. let k;
  31580. for ( k = 0; k < animationKeys.length; k ++ ) {
  31581. if ( animationKeys[ k ].morphTargets ) {
  31582. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31583. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31584. }
  31585. }
  31586. }
  31587. // create a track for each morph target with all zero
  31588. // morphTargetInfluences except for the keys in which
  31589. // the morphTarget is named.
  31590. for ( const morphTargetName in morphTargetNames ) {
  31591. const times = [];
  31592. const values = [];
  31593. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31594. const animationKey = animationKeys[ k ];
  31595. times.push( animationKey.time );
  31596. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31597. }
  31598. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31599. }
  31600. duration = morphTargetNames.length * fps;
  31601. } else {
  31602. // ...assume skeletal animation
  31603. const boneName = '.bones[' + bones[ h ].name + ']';
  31604. addNonemptyTrack(
  31605. VectorKeyframeTrack, boneName + '.position',
  31606. animationKeys, 'pos', tracks );
  31607. addNonemptyTrack(
  31608. QuaternionKeyframeTrack, boneName + '.quaternion',
  31609. animationKeys, 'rot', tracks );
  31610. addNonemptyTrack(
  31611. VectorKeyframeTrack, boneName + '.scale',
  31612. animationKeys, 'scl', tracks );
  31613. }
  31614. }
  31615. if ( tracks.length === 0 ) {
  31616. return null;
  31617. }
  31618. const clip = new this( clipName, duration, tracks, blendMode );
  31619. return clip;
  31620. }
  31621. /**
  31622. * Sets the duration of this clip to the duration of its longest keyframe track.
  31623. *
  31624. * @return {AnimationClip} A reference to this animation clip.
  31625. */
  31626. resetDuration() {
  31627. const tracks = this.tracks;
  31628. let duration = 0;
  31629. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31630. const track = this.tracks[ i ];
  31631. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31632. }
  31633. this.duration = duration;
  31634. return this;
  31635. }
  31636. /**
  31637. * Trims all tracks to the clip's duration.
  31638. *
  31639. * @return {AnimationClip} A reference to this animation clip.
  31640. */
  31641. trim() {
  31642. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31643. this.tracks[ i ].trim( 0, this.duration );
  31644. }
  31645. return this;
  31646. }
  31647. /**
  31648. * Performs minimal validation on each track in the clip. Returns `true` if all
  31649. * tracks are valid.
  31650. *
  31651. * @return {boolean} Whether the clip's keyframes are valid or not.
  31652. */
  31653. validate() {
  31654. let valid = true;
  31655. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31656. valid = valid && this.tracks[ i ].validate();
  31657. }
  31658. return valid;
  31659. }
  31660. /**
  31661. * Optimizes each track by removing equivalent sequential keys (which are
  31662. * common in morph target sequences).
  31663. *
  31664. * @return {AnimationClip} A reference to this animation clip.
  31665. */
  31666. optimize() {
  31667. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31668. this.tracks[ i ].optimize();
  31669. }
  31670. return this;
  31671. }
  31672. /**
  31673. * Returns a new animation clip with copied values from this instance.
  31674. *
  31675. * @return {AnimationClip} A clone of this instance.
  31676. */
  31677. clone() {
  31678. const tracks = [];
  31679. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31680. tracks.push( this.tracks[ i ].clone() );
  31681. }
  31682. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31683. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31684. return clip;
  31685. }
  31686. /**
  31687. * Serializes this animation clip into JSON.
  31688. *
  31689. * @return {Object} The JSON object.
  31690. */
  31691. toJSON() {
  31692. return this.constructor.toJSON( this );
  31693. }
  31694. }
  31695. function getTrackTypeForValueTypeName( typeName ) {
  31696. switch ( typeName.toLowerCase() ) {
  31697. case 'scalar':
  31698. case 'double':
  31699. case 'float':
  31700. case 'number':
  31701. case 'integer':
  31702. return NumberKeyframeTrack;
  31703. case 'vector':
  31704. case 'vector2':
  31705. case 'vector3':
  31706. case 'vector4':
  31707. return VectorKeyframeTrack;
  31708. case 'color':
  31709. return ColorKeyframeTrack;
  31710. case 'quaternion':
  31711. return QuaternionKeyframeTrack;
  31712. case 'bool':
  31713. case 'boolean':
  31714. return BooleanKeyframeTrack;
  31715. case 'string':
  31716. return StringKeyframeTrack;
  31717. }
  31718. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31719. }
  31720. function parseKeyframeTrack( json ) {
  31721. if ( json.type === undefined ) {
  31722. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31723. }
  31724. const trackType = getTrackTypeForValueTypeName( json.type );
  31725. if ( json.times === undefined ) {
  31726. const times = [], values = [];
  31727. flattenJSON( json.keys, times, values, 'value' );
  31728. json.times = times;
  31729. json.values = values;
  31730. }
  31731. // derived classes can define a static parse method
  31732. if ( trackType.parse !== undefined ) {
  31733. return trackType.parse( json );
  31734. } else {
  31735. // by default, we assume a constructor compatible with the base
  31736. return new trackType( json.name, json.times, json.values, json.interpolation );
  31737. }
  31738. }
  31739. /**
  31740. * @class
  31741. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31742. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31743. * @hideconstructor
  31744. */
  31745. const Cache = {
  31746. /**
  31747. * Whether caching is enabled or not.
  31748. *
  31749. * @static
  31750. * @type {boolean}
  31751. * @default false
  31752. */
  31753. enabled: false,
  31754. /**
  31755. * A dictionary that holds cached files.
  31756. *
  31757. * @static
  31758. * @type {Object<string,Object>}
  31759. */
  31760. files: {},
  31761. /**
  31762. * Adds a cache entry with a key to reference the file. If this key already
  31763. * holds a file, it is overwritten.
  31764. *
  31765. * @static
  31766. * @param {string} key - The key to reference the cached file.
  31767. * @param {Object} file - The file to be cached.
  31768. */
  31769. add: function ( key, file ) {
  31770. if ( this.enabled === false ) return;
  31771. // log( 'Cache', 'Adding key:', key );
  31772. this.files[ key ] = file;
  31773. },
  31774. /**
  31775. * Gets the cached value for the given key.
  31776. *
  31777. * @static
  31778. * @param {string} key - The key to reference the cached file.
  31779. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31780. */
  31781. get: function ( key ) {
  31782. if ( this.enabled === false ) return;
  31783. // log( 'Cache', 'Checking key:', key );
  31784. return this.files[ key ];
  31785. },
  31786. /**
  31787. * Removes the cached file associated with the given key.
  31788. *
  31789. * @static
  31790. * @param {string} key - The key to reference the cached file.
  31791. */
  31792. remove: function ( key ) {
  31793. delete this.files[ key ];
  31794. },
  31795. /**
  31796. * Remove all values from the cache.
  31797. *
  31798. * @static
  31799. */
  31800. clear: function () {
  31801. this.files = {};
  31802. }
  31803. };
  31804. /**
  31805. * Handles and keeps track of loaded and pending data. A default global
  31806. * instance of this class is created and used by loaders if not supplied
  31807. * manually.
  31808. *
  31809. * In general that should be sufficient, however there are times when it can
  31810. * be useful to have separate loaders - for example if you want to show
  31811. * separate loading bars for objects and textures.
  31812. *
  31813. * ```js
  31814. * const manager = new THREE.LoadingManager();
  31815. * manager.onLoad = () => console.log( 'Loading complete!' );
  31816. *
  31817. * const loader1 = new OBJLoader( manager );
  31818. * const loader2 = new ColladaLoader( manager );
  31819. * ```
  31820. */
  31821. class LoadingManager {
  31822. /**
  31823. * Constructs a new loading manager.
  31824. *
  31825. * @param {Function} [onLoad] - Executes when all items have been loaded.
  31826. * @param {Function} [onProgress] - Executes when single items have been loaded.
  31827. * @param {Function} [onError] - Executes when an error occurs.
  31828. */
  31829. constructor( onLoad, onProgress, onError ) {
  31830. const scope = this;
  31831. let isLoading = false;
  31832. let itemsLoaded = 0;
  31833. let itemsTotal = 0;
  31834. let urlModifier = undefined;
  31835. const handlers = [];
  31836. // Refer to #5689 for the reason why we don't set .onStart
  31837. // in the constructor
  31838. /**
  31839. * Executes when an item starts loading.
  31840. *
  31841. * @type {Function|undefined}
  31842. * @default undefined
  31843. */
  31844. this.onStart = undefined;
  31845. /**
  31846. * Executes when all items have been loaded.
  31847. *
  31848. * @type {Function|undefined}
  31849. * @default undefined
  31850. */
  31851. this.onLoad = onLoad;
  31852. /**
  31853. * Executes when single items have been loaded.
  31854. *
  31855. * @type {Function|undefined}
  31856. * @default undefined
  31857. */
  31858. this.onProgress = onProgress;
  31859. /**
  31860. * Executes when an error occurs.
  31861. *
  31862. * @type {Function|undefined}
  31863. * @default undefined
  31864. */
  31865. this.onError = onError;
  31866. /**
  31867. * Used for aborting ongoing requests in loaders using this manager.
  31868. *
  31869. * @type {AbortController}
  31870. */
  31871. this.abortController = new AbortController();
  31872. /**
  31873. * This should be called by any loader using the manager when the loader
  31874. * starts loading an item.
  31875. *
  31876. * @param {string} url - The URL to load.
  31877. */
  31878. this.itemStart = function ( url ) {
  31879. itemsTotal ++;
  31880. if ( isLoading === false ) {
  31881. if ( scope.onStart !== undefined ) {
  31882. scope.onStart( url, itemsLoaded, itemsTotal );
  31883. }
  31884. }
  31885. isLoading = true;
  31886. };
  31887. /**
  31888. * This should be called by any loader using the manager when the loader
  31889. * ended loading an item.
  31890. *
  31891. * @param {string} url - The URL of the loaded item.
  31892. */
  31893. this.itemEnd = function ( url ) {
  31894. itemsLoaded ++;
  31895. if ( scope.onProgress !== undefined ) {
  31896. scope.onProgress( url, itemsLoaded, itemsTotal );
  31897. }
  31898. if ( itemsLoaded === itemsTotal ) {
  31899. isLoading = false;
  31900. if ( scope.onLoad !== undefined ) {
  31901. scope.onLoad();
  31902. }
  31903. }
  31904. };
  31905. /**
  31906. * This should be called by any loader using the manager when the loader
  31907. * encounters an error when loading an item.
  31908. *
  31909. * @param {string} url - The URL of the item that produces an error.
  31910. */
  31911. this.itemError = function ( url ) {
  31912. if ( scope.onError !== undefined ) {
  31913. scope.onError( url );
  31914. }
  31915. };
  31916. /**
  31917. * Given a URL, uses the URL modifier callback (if any) and returns a
  31918. * resolved URL. If no URL modifier is set, returns the original URL.
  31919. *
  31920. * @param {string} url - The URL to load.
  31921. * @return {string} The resolved URL.
  31922. */
  31923. this.resolveURL = function ( url ) {
  31924. if ( urlModifier ) {
  31925. return urlModifier( url );
  31926. }
  31927. return url;
  31928. };
  31929. /**
  31930. * If provided, the callback will be passed each resource URL before a
  31931. * request is sent. The callback may return the original URL, or a new URL to
  31932. * override loading behavior. This behavior can be used to load assets from
  31933. * .ZIP files, drag-and-drop APIs, and Data URIs.
  31934. *
  31935. * ```js
  31936. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  31937. *
  31938. * const manager = new THREE.LoadingManager();
  31939. *
  31940. * // Initialize loading manager with URL callback.
  31941. * const objectURLs = [];
  31942. * manager.setURLModifier( ( url ) => {
  31943. *
  31944. * url = URL.createObjectURL( blobs[ url ] );
  31945. * objectURLs.push( url );
  31946. * return url;
  31947. *
  31948. * } );
  31949. *
  31950. * // Load as usual, then revoke the blob URLs.
  31951. * const loader = new GLTFLoader( manager );
  31952. * loader.load( 'fish.gltf', (gltf) => {
  31953. *
  31954. * scene.add( gltf.scene );
  31955. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  31956. *
  31957. * } );
  31958. * ```
  31959. *
  31960. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  31961. * @return {LoadingManager} A reference to this loading manager.
  31962. */
  31963. this.setURLModifier = function ( transform ) {
  31964. urlModifier = transform;
  31965. return this;
  31966. };
  31967. /**
  31968. * Registers a loader with the given regular expression. Can be used to
  31969. * define what loader should be used in order to load specific files. A
  31970. * typical use case is to overwrite the default loader for textures.
  31971. *
  31972. * ```js
  31973. * // add handler for TGA textures
  31974. * manager.addHandler( /\.tga$/i, new TGALoader() );
  31975. * ```
  31976. *
  31977. * @param {string} regex - A regular expression.
  31978. * @param {Loader} loader - A loader that should handle matched cases.
  31979. * @return {LoadingManager} A reference to this loading manager.
  31980. */
  31981. this.addHandler = function ( regex, loader ) {
  31982. handlers.push( regex, loader );
  31983. return this;
  31984. };
  31985. /**
  31986. * Removes the loader for the given regular expression.
  31987. *
  31988. * @param {string} regex - A regular expression.
  31989. * @return {LoadingManager} A reference to this loading manager.
  31990. */
  31991. this.removeHandler = function ( regex ) {
  31992. const index = handlers.indexOf( regex );
  31993. if ( index !== -1 ) {
  31994. handlers.splice( index, 2 );
  31995. }
  31996. return this;
  31997. };
  31998. /**
  31999. * Can be used to retrieve the registered loader for the given file path.
  32000. *
  32001. * @param {string} file - The file path.
  32002. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32003. */
  32004. this.getHandler = function ( file ) {
  32005. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32006. const regex = handlers[ i ];
  32007. const loader = handlers[ i + 1 ];
  32008. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32009. if ( regex.test( file ) ) {
  32010. return loader;
  32011. }
  32012. }
  32013. return null;
  32014. };
  32015. /**
  32016. * Can be used to abort ongoing loading requests in loaders using this manager.
  32017. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32018. * is supported in the browser.
  32019. *
  32020. * @return {LoadingManager} A reference to this loading manager.
  32021. */
  32022. this.abort = function () {
  32023. this.abortController.abort();
  32024. this.abortController = new AbortController();
  32025. return this;
  32026. };
  32027. }
  32028. }
  32029. /**
  32030. * The global default loading manager.
  32031. *
  32032. * @constant
  32033. * @type {LoadingManager}
  32034. */
  32035. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32036. /**
  32037. * Abstract base class for loaders.
  32038. *
  32039. * @abstract
  32040. */
  32041. class Loader {
  32042. /**
  32043. * Constructs a new loader.
  32044. *
  32045. * @param {LoadingManager} [manager] - The loading manager.
  32046. */
  32047. constructor( manager ) {
  32048. /**
  32049. * The loading manager.
  32050. *
  32051. * @type {LoadingManager}
  32052. * @default DefaultLoadingManager
  32053. */
  32054. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32055. /**
  32056. * The crossOrigin string to implement CORS for loading the url from a
  32057. * different domain that allows CORS.
  32058. *
  32059. * @type {string}
  32060. * @default 'anonymous'
  32061. */
  32062. this.crossOrigin = 'anonymous';
  32063. /**
  32064. * Whether the XMLHttpRequest uses credentials.
  32065. *
  32066. * @type {boolean}
  32067. * @default false
  32068. */
  32069. this.withCredentials = false;
  32070. /**
  32071. * The base path from which the asset will be loaded.
  32072. *
  32073. * @type {string}
  32074. */
  32075. this.path = '';
  32076. /**
  32077. * The base path from which additional resources like textures will be loaded.
  32078. *
  32079. * @type {string}
  32080. */
  32081. this.resourcePath = '';
  32082. /**
  32083. * The [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32084. * used in HTTP request.
  32085. *
  32086. * @type {Object<string, any>}
  32087. */
  32088. this.requestHeader = {};
  32089. }
  32090. /**
  32091. * This method needs to be implemented by all concrete loaders. It holds the
  32092. * logic for loading assets from the backend.
  32093. *
  32094. * @abstract
  32095. * @param {string} url - The path/URL of the file to be loaded.
  32096. * @param {Function} onLoad - Executed when the loading process has been finished.
  32097. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32098. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32099. */
  32100. load( /* url, onLoad, onProgress, onError */ ) {}
  32101. /**
  32102. * A async version of {@link Loader#load}.
  32103. *
  32104. * @param {string} url - The path/URL of the file to be loaded.
  32105. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32106. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32107. */
  32108. loadAsync( url, onProgress ) {
  32109. const scope = this;
  32110. return new Promise( function ( resolve, reject ) {
  32111. scope.load( url, resolve, onProgress, reject );
  32112. } );
  32113. }
  32114. /**
  32115. * This method needs to be implemented by all concrete loaders. It holds the
  32116. * logic for parsing the asset into three.js entities.
  32117. *
  32118. * @abstract
  32119. * @param {any} data - The data to parse.
  32120. */
  32121. parse( /* data */ ) {}
  32122. /**
  32123. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32124. * from a different domain that allows CORS.
  32125. *
  32126. * @param {string} crossOrigin - The `crossOrigin` value.
  32127. * @return {Loader} A reference to this instance.
  32128. */
  32129. setCrossOrigin( crossOrigin ) {
  32130. this.crossOrigin = crossOrigin;
  32131. return this;
  32132. }
  32133. /**
  32134. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32135. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials]{@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials}.
  32136. *
  32137. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32138. *
  32139. * @param {boolean} value - The `withCredentials` value.
  32140. * @return {Loader} A reference to this instance.
  32141. */
  32142. setWithCredentials( value ) {
  32143. this.withCredentials = value;
  32144. return this;
  32145. }
  32146. /**
  32147. * Sets the base path for the asset.
  32148. *
  32149. * @param {string} path - The base path.
  32150. * @return {Loader} A reference to this instance.
  32151. */
  32152. setPath( path ) {
  32153. this.path = path;
  32154. return this;
  32155. }
  32156. /**
  32157. * Sets the base path for dependent resources like textures.
  32158. *
  32159. * @param {string} resourcePath - The resource path.
  32160. * @return {Loader} A reference to this instance.
  32161. */
  32162. setResourcePath( resourcePath ) {
  32163. this.resourcePath = resourcePath;
  32164. return this;
  32165. }
  32166. /**
  32167. * Sets the given request header.
  32168. *
  32169. * @param {Object} requestHeader - A [request header]{@link https://developer.mozilla.org/en-US/docs/Glossary/Request_header}
  32170. * for configuring the HTTP request.
  32171. * @return {Loader} A reference to this instance.
  32172. */
  32173. setRequestHeader( requestHeader ) {
  32174. this.requestHeader = requestHeader;
  32175. return this;
  32176. }
  32177. /**
  32178. * This method can be implemented in loaders for aborting ongoing requests.
  32179. *
  32180. * @abstract
  32181. * @return {Loader} A reference to this instance.
  32182. */
  32183. abort() {
  32184. return this;
  32185. }
  32186. }
  32187. /**
  32188. * Callback for onProgress in loaders.
  32189. *
  32190. * @callback onProgressCallback
  32191. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32192. */
  32193. /**
  32194. * Callback for onError in loaders.
  32195. *
  32196. * @callback onErrorCallback
  32197. * @param {Error} error - The error which occurred during the loading process.
  32198. */
  32199. /**
  32200. * The default material name that is used by loaders
  32201. * when creating materials for loaded 3D objects.
  32202. *
  32203. * Note: Not all loaders might honor this setting.
  32204. *
  32205. * @static
  32206. * @type {string}
  32207. * @default '__DEFAULT'
  32208. */
  32209. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32210. const loading = {};
  32211. class HttpError extends Error {
  32212. constructor( message, response ) {
  32213. super( message );
  32214. this.response = response;
  32215. }
  32216. }
  32217. /**
  32218. * A low level class for loading resources with the Fetch API, used internally by
  32219. * most loaders. It can also be used directly to load any file type that does
  32220. * not have a loader.
  32221. *
  32222. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32223. * once to your application.
  32224. *
  32225. * ```js
  32226. * const loader = new THREE.FileLoader();
  32227. * const data = await loader.loadAsync( 'example.txt' );
  32228. * ```
  32229. *
  32230. * @augments Loader
  32231. */
  32232. class FileLoader extends Loader {
  32233. /**
  32234. * Constructs a new file loader.
  32235. *
  32236. * @param {LoadingManager} [manager] - The loading manager.
  32237. */
  32238. constructor( manager ) {
  32239. super( manager );
  32240. /**
  32241. * The expected mime type. Valid values can be found
  32242. * [here]{@link hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype}
  32243. *
  32244. * @type {string}
  32245. */
  32246. this.mimeType = '';
  32247. /**
  32248. * The expected response type.
  32249. *
  32250. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32251. * @default ''
  32252. */
  32253. this.responseType = '';
  32254. /**
  32255. * Used for aborting requests.
  32256. *
  32257. * @private
  32258. * @type {AbortController}
  32259. */
  32260. this._abortController = new AbortController();
  32261. }
  32262. /**
  32263. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32264. *
  32265. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32266. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32267. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32268. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32269. * @return {any|undefined} The cached resource if available.
  32270. */
  32271. load( url, onLoad, onProgress, onError ) {
  32272. if ( url === undefined ) url = '';
  32273. if ( this.path !== undefined ) url = this.path + url;
  32274. url = this.manager.resolveURL( url );
  32275. const cached = Cache.get( `file:${url}` );
  32276. if ( cached !== undefined ) {
  32277. this.manager.itemStart( url );
  32278. setTimeout( () => {
  32279. if ( onLoad ) onLoad( cached );
  32280. this.manager.itemEnd( url );
  32281. }, 0 );
  32282. return cached;
  32283. }
  32284. // Check if request is duplicate
  32285. if ( loading[ url ] !== undefined ) {
  32286. loading[ url ].push( {
  32287. onLoad: onLoad,
  32288. onProgress: onProgress,
  32289. onError: onError
  32290. } );
  32291. return;
  32292. }
  32293. // Initialise array for duplicate requests
  32294. loading[ url ] = [];
  32295. loading[ url ].push( {
  32296. onLoad: onLoad,
  32297. onProgress: onProgress,
  32298. onError: onError,
  32299. } );
  32300. // create request
  32301. const req = new Request( url, {
  32302. headers: new Headers( this.requestHeader ),
  32303. credentials: this.withCredentials ? 'include' : 'same-origin',
  32304. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32305. } );
  32306. // record states ( avoid data race )
  32307. const mimeType = this.mimeType;
  32308. const responseType = this.responseType;
  32309. // start the fetch
  32310. fetch( req )
  32311. .then( response => {
  32312. if ( response.status === 200 || response.status === 0 ) {
  32313. // Some browsers return HTTP Status 0 when using non-http protocol
  32314. // e.g. 'file://' or 'data://'. Handle as success.
  32315. if ( response.status === 0 ) {
  32316. warn( 'FileLoader: HTTP Status 0 received.' );
  32317. }
  32318. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32319. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32320. return response;
  32321. }
  32322. const callbacks = loading[ url ];
  32323. const reader = response.body.getReader();
  32324. // Nginx needs X-File-Size check
  32325. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32326. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32327. const total = contentLength ? parseInt( contentLength ) : 0;
  32328. const lengthComputable = total !== 0;
  32329. let loaded = 0;
  32330. // periodically read data into the new stream tracking while download progress
  32331. const stream = new ReadableStream( {
  32332. start( controller ) {
  32333. readData();
  32334. function readData() {
  32335. reader.read().then( ( { done, value } ) => {
  32336. if ( done ) {
  32337. controller.close();
  32338. } else {
  32339. loaded += value.byteLength;
  32340. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32341. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32342. const callback = callbacks[ i ];
  32343. if ( callback.onProgress ) callback.onProgress( event );
  32344. }
  32345. controller.enqueue( value );
  32346. readData();
  32347. }
  32348. }, ( e ) => {
  32349. controller.error( e );
  32350. } );
  32351. }
  32352. }
  32353. } );
  32354. return new Response( stream );
  32355. } else {
  32356. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32357. }
  32358. } )
  32359. .then( response => {
  32360. switch ( responseType ) {
  32361. case 'arraybuffer':
  32362. return response.arrayBuffer();
  32363. case 'blob':
  32364. return response.blob();
  32365. case 'document':
  32366. return response.text()
  32367. .then( text => {
  32368. const parser = new DOMParser();
  32369. return parser.parseFromString( text, mimeType );
  32370. } );
  32371. case 'json':
  32372. return response.json();
  32373. default:
  32374. if ( mimeType === '' ) {
  32375. return response.text();
  32376. } else {
  32377. // sniff encoding
  32378. const re = /charset="?([^;"\s]*)"?/i;
  32379. const exec = re.exec( mimeType );
  32380. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32381. const decoder = new TextDecoder( label );
  32382. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32383. }
  32384. }
  32385. } )
  32386. .then( data => {
  32387. // Add to cache only on HTTP success, so that we do not cache
  32388. // error response bodies as proper responses to requests.
  32389. Cache.add( `file:${url}`, data );
  32390. const callbacks = loading[ url ];
  32391. delete loading[ url ];
  32392. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32393. const callback = callbacks[ i ];
  32394. if ( callback.onLoad ) callback.onLoad( data );
  32395. }
  32396. } )
  32397. .catch( err => {
  32398. // Abort errors and other errors are handled the same
  32399. const callbacks = loading[ url ];
  32400. if ( callbacks === undefined ) {
  32401. // When onLoad was called and url was deleted in `loading`
  32402. this.manager.itemError( url );
  32403. throw err;
  32404. }
  32405. delete loading[ url ];
  32406. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32407. const callback = callbacks[ i ];
  32408. if ( callback.onError ) callback.onError( err );
  32409. }
  32410. this.manager.itemError( url );
  32411. } )
  32412. .finally( () => {
  32413. this.manager.itemEnd( url );
  32414. } );
  32415. this.manager.itemStart( url );
  32416. }
  32417. /**
  32418. * Sets the expected response type.
  32419. *
  32420. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32421. * @return {FileLoader} A reference to this file loader.
  32422. */
  32423. setResponseType( value ) {
  32424. this.responseType = value;
  32425. return this;
  32426. }
  32427. /**
  32428. * Sets the expected mime type of the loaded file.
  32429. *
  32430. * @param {string} value - The mime type.
  32431. * @return {FileLoader} A reference to this file loader.
  32432. */
  32433. setMimeType( value ) {
  32434. this.mimeType = value;
  32435. return this;
  32436. }
  32437. /**
  32438. * Aborts ongoing fetch requests.
  32439. *
  32440. * @return {FileLoader} A reference to this instance.
  32441. */
  32442. abort() {
  32443. this._abortController.abort();
  32444. this._abortController = new AbortController();
  32445. return this;
  32446. }
  32447. }
  32448. /**
  32449. * Class for loading animation clips in the JSON format. The files are internally
  32450. * loaded via {@link FileLoader}.
  32451. *
  32452. * ```js
  32453. * const loader = new THREE.AnimationLoader();
  32454. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32455. * ```
  32456. *
  32457. * @augments Loader
  32458. */
  32459. class AnimationLoader extends Loader {
  32460. /**
  32461. * Constructs a new animation loader.
  32462. *
  32463. * @param {LoadingManager} [manager] - The loading manager.
  32464. */
  32465. constructor( manager ) {
  32466. super( manager );
  32467. }
  32468. /**
  32469. * Starts loading from the given URL and pass the loaded animations as an array
  32470. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32471. *
  32472. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32473. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32474. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32475. * @param {onErrorCallback} onError - Executed when errors occur.
  32476. */
  32477. load( url, onLoad, onProgress, onError ) {
  32478. const scope = this;
  32479. const loader = new FileLoader( this.manager );
  32480. loader.setPath( this.path );
  32481. loader.setRequestHeader( this.requestHeader );
  32482. loader.setWithCredentials( this.withCredentials );
  32483. loader.load( url, function ( text ) {
  32484. try {
  32485. onLoad( scope.parse( JSON.parse( text ) ) );
  32486. } catch ( e ) {
  32487. if ( onError ) {
  32488. onError( e );
  32489. } else {
  32490. error( e );
  32491. }
  32492. scope.manager.itemError( url );
  32493. }
  32494. }, onProgress, onError );
  32495. }
  32496. /**
  32497. * Parses the given JSON object and returns an array of animation clips.
  32498. *
  32499. * @param {Object} json - The serialized animation clips.
  32500. * @return {Array<AnimationClip>} The parsed animation clips.
  32501. */
  32502. parse( json ) {
  32503. const animations = [];
  32504. for ( let i = 0; i < json.length; i ++ ) {
  32505. const clip = AnimationClip.parse( json[ i ] );
  32506. animations.push( clip );
  32507. }
  32508. return animations;
  32509. }
  32510. }
  32511. /**
  32512. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32513. * Textures are internally loaded via {@link FileLoader}.
  32514. *
  32515. * Derived classes have to implement the `parse()` method which holds the parsing
  32516. * for the respective format.
  32517. *
  32518. * @abstract
  32519. * @augments Loader
  32520. */
  32521. class CompressedTextureLoader extends Loader {
  32522. /**
  32523. * Constructs a new compressed texture loader.
  32524. *
  32525. * @param {LoadingManager} [manager] - The loading manager.
  32526. */
  32527. constructor( manager ) {
  32528. super( manager );
  32529. }
  32530. /**
  32531. * Starts loading from the given URL and passes the loaded compressed texture
  32532. * to the `onLoad()` callback. The method also returns a new texture object which can
  32533. * directly be used for material creation. If you do it this way, the texture
  32534. * may pop up in your scene once the respective loading process is finished.
  32535. *
  32536. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32537. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32538. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32539. * @param {onErrorCallback} onError - Executed when errors occur.
  32540. * @return {CompressedTexture} The compressed texture.
  32541. */
  32542. load( url, onLoad, onProgress, onError ) {
  32543. const scope = this;
  32544. const images = [];
  32545. const texture = new CompressedTexture();
  32546. const loader = new FileLoader( this.manager );
  32547. loader.setPath( this.path );
  32548. loader.setResponseType( 'arraybuffer' );
  32549. loader.setRequestHeader( this.requestHeader );
  32550. loader.setWithCredentials( scope.withCredentials );
  32551. let loaded = 0;
  32552. function loadTexture( i ) {
  32553. loader.load( url[ i ], function ( buffer ) {
  32554. const texDatas = scope.parse( buffer, true );
  32555. images[ i ] = {
  32556. width: texDatas.width,
  32557. height: texDatas.height,
  32558. format: texDatas.format,
  32559. mipmaps: texDatas.mipmaps
  32560. };
  32561. loaded += 1;
  32562. if ( loaded === 6 ) {
  32563. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32564. texture.image = images;
  32565. texture.format = texDatas.format;
  32566. texture.needsUpdate = true;
  32567. if ( onLoad ) onLoad( texture );
  32568. }
  32569. }, onProgress, onError );
  32570. }
  32571. if ( Array.isArray( url ) ) {
  32572. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32573. loadTexture( i );
  32574. }
  32575. } else {
  32576. // compressed cubemap texture stored in a single DDS file
  32577. loader.load( url, function ( buffer ) {
  32578. const texDatas = scope.parse( buffer, true );
  32579. if ( texDatas.isCubemap ) {
  32580. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32581. for ( let f = 0; f < faces; f ++ ) {
  32582. images[ f ] = { mipmaps: [] };
  32583. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32584. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32585. images[ f ].format = texDatas.format;
  32586. images[ f ].width = texDatas.width;
  32587. images[ f ].height = texDatas.height;
  32588. }
  32589. }
  32590. texture.image = images;
  32591. } else {
  32592. texture.image.width = texDatas.width;
  32593. texture.image.height = texDatas.height;
  32594. texture.mipmaps = texDatas.mipmaps;
  32595. }
  32596. if ( texDatas.mipmapCount === 1 ) {
  32597. texture.minFilter = LinearFilter;
  32598. }
  32599. texture.format = texDatas.format;
  32600. texture.needsUpdate = true;
  32601. if ( onLoad ) onLoad( texture );
  32602. }, onProgress, onError );
  32603. }
  32604. return texture;
  32605. }
  32606. }
  32607. const _loading = new WeakMap();
  32608. /**
  32609. * A loader for loading images. The class loads images with the HTML `Image` API.
  32610. *
  32611. * ```js
  32612. * const loader = new THREE.ImageLoader();
  32613. * const image = await loader.loadAsync( 'image.png' );
  32614. * ```
  32615. * Please note that `ImageLoader` has dropped support for progress
  32616. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32617. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639}.
  32618. *
  32619. * @augments Loader
  32620. */
  32621. class ImageLoader extends Loader {
  32622. /**
  32623. * Constructs a new image loader.
  32624. *
  32625. * @param {LoadingManager} [manager] - The loading manager.
  32626. */
  32627. constructor( manager ) {
  32628. super( manager );
  32629. }
  32630. /**
  32631. * Starts loading from the given URL and passes the loaded image
  32632. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32633. * directly be used for texture creation. If you do it this way, the texture
  32634. * may pop up in your scene once the respective loading process is finished.
  32635. *
  32636. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32637. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32638. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32639. * @param {onErrorCallback} onError - Executed when errors occur.
  32640. * @return {Image} The image.
  32641. */
  32642. load( url, onLoad, onProgress, onError ) {
  32643. if ( this.path !== undefined ) url = this.path + url;
  32644. url = this.manager.resolveURL( url );
  32645. const scope = this;
  32646. const cached = Cache.get( `image:${url}` );
  32647. if ( cached !== undefined ) {
  32648. if ( cached.complete === true ) {
  32649. scope.manager.itemStart( url );
  32650. setTimeout( function () {
  32651. if ( onLoad ) onLoad( cached );
  32652. scope.manager.itemEnd( url );
  32653. }, 0 );
  32654. } else {
  32655. let arr = _loading.get( cached );
  32656. if ( arr === undefined ) {
  32657. arr = [];
  32658. _loading.set( cached, arr );
  32659. }
  32660. arr.push( { onLoad, onError } );
  32661. }
  32662. return cached;
  32663. }
  32664. const image = createElementNS( 'img' );
  32665. function onImageLoad() {
  32666. removeEventListeners();
  32667. if ( onLoad ) onLoad( this );
  32668. //
  32669. const callbacks = _loading.get( this ) || [];
  32670. for ( let i = 0; i < callbacks.length; i ++ ) {
  32671. const callback = callbacks[ i ];
  32672. if ( callback.onLoad ) callback.onLoad( this );
  32673. }
  32674. _loading.delete( this );
  32675. scope.manager.itemEnd( url );
  32676. }
  32677. function onImageError( event ) {
  32678. removeEventListeners();
  32679. if ( onError ) onError( event );
  32680. Cache.remove( `image:${url}` );
  32681. //
  32682. const callbacks = _loading.get( this ) || [];
  32683. for ( let i = 0; i < callbacks.length; i ++ ) {
  32684. const callback = callbacks[ i ];
  32685. if ( callback.onError ) callback.onError( event );
  32686. }
  32687. _loading.delete( this );
  32688. scope.manager.itemError( url );
  32689. scope.manager.itemEnd( url );
  32690. }
  32691. function removeEventListeners() {
  32692. image.removeEventListener( 'load', onImageLoad, false );
  32693. image.removeEventListener( 'error', onImageError, false );
  32694. }
  32695. image.addEventListener( 'load', onImageLoad, false );
  32696. image.addEventListener( 'error', onImageError, false );
  32697. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32698. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32699. }
  32700. Cache.add( `image:${url}`, image );
  32701. scope.manager.itemStart( url );
  32702. image.src = url;
  32703. return image;
  32704. }
  32705. }
  32706. /**
  32707. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32708. *
  32709. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32710. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32711. * like vertical and horizontal cross, column and row layouts are not supported.
  32712. *
  32713. * Note that, by convention, cube maps are specified in a coordinate system
  32714. * in which positive-x is to the right when looking up the positive-z axis --
  32715. * in other words, using a left-handed coordinate system. Since three.js uses
  32716. * a right-handed coordinate system, environment maps used in three.js will
  32717. * have pos-x and neg-x swapped.
  32718. *
  32719. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32720. * is set to `SRGBColorSpace` by default.
  32721. *
  32722. * ```js
  32723. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32724. * const cubeTexture = await loader.loadAsync( [
  32725. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32726. * ] );
  32727. * scene.background = cubeTexture;
  32728. * ```
  32729. *
  32730. * @augments Loader
  32731. */
  32732. class CubeTextureLoader extends Loader {
  32733. /**
  32734. * Constructs a new cube texture loader.
  32735. *
  32736. * @param {LoadingManager} [manager] - The loading manager.
  32737. */
  32738. constructor( manager ) {
  32739. super( manager );
  32740. }
  32741. /**
  32742. * Starts loading from the given URL and pass the fully loaded cube texture
  32743. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32744. * directly be used for material creation. If you do it this way, the cube texture
  32745. * may pop up in your scene once the respective loading process is finished.
  32746. *
  32747. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32748. * cube texture. The urls should be specified in the following order: pos-x,
  32749. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32750. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32751. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32752. * @param {onErrorCallback} onError - Executed when errors occur.
  32753. * @return {CubeTexture} The cube texture.
  32754. */
  32755. load( urls, onLoad, onProgress, onError ) {
  32756. const texture = new CubeTexture();
  32757. texture.colorSpace = SRGBColorSpace;
  32758. const loader = new ImageLoader( this.manager );
  32759. loader.setCrossOrigin( this.crossOrigin );
  32760. loader.setPath( this.path );
  32761. let loaded = 0;
  32762. function loadTexture( i ) {
  32763. loader.load( urls[ i ], function ( image ) {
  32764. texture.images[ i ] = image;
  32765. loaded ++;
  32766. if ( loaded === 6 ) {
  32767. texture.needsUpdate = true;
  32768. if ( onLoad ) onLoad( texture );
  32769. }
  32770. }, undefined, onError );
  32771. }
  32772. for ( let i = 0; i < urls.length; ++ i ) {
  32773. loadTexture( i );
  32774. }
  32775. return texture;
  32776. }
  32777. }
  32778. /**
  32779. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32780. * Textures are internally loaded via {@link FileLoader}.
  32781. *
  32782. * Derived classes have to implement the `parse()` method which holds the parsing
  32783. * for the respective format.
  32784. *
  32785. * @abstract
  32786. * @augments Loader
  32787. */
  32788. class DataTextureLoader extends Loader {
  32789. /**
  32790. * Constructs a new data texture loader.
  32791. *
  32792. * @param {LoadingManager} [manager] - The loading manager.
  32793. */
  32794. constructor( manager ) {
  32795. super( manager );
  32796. }
  32797. /**
  32798. * Starts loading from the given URL and passes the loaded data texture
  32799. * to the `onLoad()` callback. The method also returns a new texture object which can
  32800. * directly be used for material creation. If you do it this way, the texture
  32801. * may pop up in your scene once the respective loading process is finished.
  32802. *
  32803. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32804. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  32805. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32806. * @param {onErrorCallback} onError - Executed when errors occur.
  32807. * @return {DataTexture} The data texture.
  32808. */
  32809. load( url, onLoad, onProgress, onError ) {
  32810. const scope = this;
  32811. const texture = new DataTexture();
  32812. const loader = new FileLoader( this.manager );
  32813. loader.setResponseType( 'arraybuffer' );
  32814. loader.setRequestHeader( this.requestHeader );
  32815. loader.setPath( this.path );
  32816. loader.setWithCredentials( scope.withCredentials );
  32817. loader.load( url, function ( buffer ) {
  32818. let texData;
  32819. try {
  32820. texData = scope.parse( buffer );
  32821. } catch ( error ) {
  32822. if ( onError !== undefined ) {
  32823. onError( error );
  32824. } else {
  32825. error( error );
  32826. return;
  32827. }
  32828. }
  32829. if ( texData.image !== undefined ) {
  32830. texture.image = texData.image;
  32831. } else if ( texData.data !== undefined ) {
  32832. texture.image.width = texData.width;
  32833. texture.image.height = texData.height;
  32834. texture.image.data = texData.data;
  32835. }
  32836. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  32837. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  32838. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  32839. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  32840. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  32841. if ( texData.colorSpace !== undefined ) {
  32842. texture.colorSpace = texData.colorSpace;
  32843. }
  32844. if ( texData.flipY !== undefined ) {
  32845. texture.flipY = texData.flipY;
  32846. }
  32847. if ( texData.format !== undefined ) {
  32848. texture.format = texData.format;
  32849. }
  32850. if ( texData.type !== undefined ) {
  32851. texture.type = texData.type;
  32852. }
  32853. if ( texData.mipmaps !== undefined ) {
  32854. texture.mipmaps = texData.mipmaps;
  32855. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  32856. }
  32857. if ( texData.mipmapCount === 1 ) {
  32858. texture.minFilter = LinearFilter;
  32859. }
  32860. if ( texData.generateMipmaps !== undefined ) {
  32861. texture.generateMipmaps = texData.generateMipmaps;
  32862. }
  32863. texture.needsUpdate = true;
  32864. if ( onLoad ) onLoad( texture, texData );
  32865. }, onProgress, onError );
  32866. return texture;
  32867. }
  32868. }
  32869. /**
  32870. * Class for loading textures. Images are internally
  32871. * loaded via {@link ImageLoader}.
  32872. *
  32873. * ```js
  32874. * const loader = new THREE.TextureLoader();
  32875. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  32876. *
  32877. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  32878. * ```
  32879. * Please note that `TextureLoader` has dropped support for progress
  32880. * events in `r84`. For a `TextureLoader` that supports progress events, see
  32881. * [this thread]{@link https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145}.
  32882. *
  32883. * @augments Loader
  32884. */
  32885. class TextureLoader extends Loader {
  32886. /**
  32887. * Constructs a new texture loader.
  32888. *
  32889. * @param {LoadingManager} [manager] - The loading manager.
  32890. */
  32891. constructor( manager ) {
  32892. super( manager );
  32893. }
  32894. /**
  32895. * Starts loading from the given URL and pass the fully loaded texture
  32896. * to the `onLoad()` callback. The method also returns a new texture object which can
  32897. * directly be used for material creation. If you do it this way, the texture
  32898. * may pop up in your scene once the respective loading process is finished.
  32899. *
  32900. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32901. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  32902. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32903. * @param {onErrorCallback} onError - Executed when errors occur.
  32904. * @return {Texture} The texture.
  32905. */
  32906. load( url, onLoad, onProgress, onError ) {
  32907. const texture = new Texture();
  32908. const loader = new ImageLoader( this.manager );
  32909. loader.setCrossOrigin( this.crossOrigin );
  32910. loader.setPath( this.path );
  32911. loader.load( url, function ( image ) {
  32912. texture.image = image;
  32913. texture.needsUpdate = true;
  32914. if ( onLoad !== undefined ) {
  32915. onLoad( texture );
  32916. }
  32917. }, onProgress, onError );
  32918. return texture;
  32919. }
  32920. }
  32921. /**
  32922. * Abstract base class for lights - all other light types inherit the
  32923. * properties and methods described here.
  32924. *
  32925. * @abstract
  32926. * @augments Object3D
  32927. */
  32928. class Light extends Object3D {
  32929. /**
  32930. * Constructs a new light.
  32931. *
  32932. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  32933. * @param {number} [intensity=1] - The light's strength/intensity.
  32934. */
  32935. constructor( color, intensity = 1 ) {
  32936. super();
  32937. /**
  32938. * This flag can be used for type testing.
  32939. *
  32940. * @type {boolean}
  32941. * @readonly
  32942. * @default true
  32943. */
  32944. this.isLight = true;
  32945. this.type = 'Light';
  32946. /**
  32947. * The light's color.
  32948. *
  32949. * @type {Color}
  32950. */
  32951. this.color = new Color( color );
  32952. /**
  32953. * The light's intensity.
  32954. *
  32955. * @type {number}
  32956. * @default 1
  32957. */
  32958. this.intensity = intensity;
  32959. }
  32960. /**
  32961. * Frees the GPU-related resources allocated by this instance. Call this
  32962. * method whenever this instance is no longer used in your app.
  32963. */
  32964. dispose() {
  32965. // Empty here in base class; some subclasses override.
  32966. }
  32967. copy( source, recursive ) {
  32968. super.copy( source, recursive );
  32969. this.color.copy( source.color );
  32970. this.intensity = source.intensity;
  32971. return this;
  32972. }
  32973. toJSON( meta ) {
  32974. const data = super.toJSON( meta );
  32975. data.object.color = this.color.getHex();
  32976. data.object.intensity = this.intensity;
  32977. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  32978. if ( this.distance !== undefined ) data.object.distance = this.distance;
  32979. if ( this.angle !== undefined ) data.object.angle = this.angle;
  32980. if ( this.decay !== undefined ) data.object.decay = this.decay;
  32981. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  32982. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  32983. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  32984. return data;
  32985. }
  32986. }
  32987. /**
  32988. * A light source positioned directly above the scene, with color fading from
  32989. * the sky color to the ground color.
  32990. *
  32991. * This light cannot be used to cast shadows.
  32992. *
  32993. * ```js
  32994. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  32995. * scene.add( light );
  32996. * ```
  32997. *
  32998. * @augments Light
  32999. */
  33000. class HemisphereLight extends Light {
  33001. /**
  33002. * Constructs a new hemisphere light.
  33003. *
  33004. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33005. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33006. * @param {number} [intensity=1] - The light's strength/intensity.
  33007. */
  33008. constructor( skyColor, groundColor, intensity ) {
  33009. super( skyColor, intensity );
  33010. /**
  33011. * This flag can be used for type testing.
  33012. *
  33013. * @type {boolean}
  33014. * @readonly
  33015. * @default true
  33016. */
  33017. this.isHemisphereLight = true;
  33018. this.type = 'HemisphereLight';
  33019. this.position.copy( Object3D.DEFAULT_UP );
  33020. this.updateMatrix();
  33021. /**
  33022. * The light's ground color.
  33023. *
  33024. * @type {Color}
  33025. */
  33026. this.groundColor = new Color( groundColor );
  33027. }
  33028. copy( source, recursive ) {
  33029. super.copy( source, recursive );
  33030. this.groundColor.copy( source.groundColor );
  33031. return this;
  33032. }
  33033. }
  33034. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33035. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33036. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33037. /**
  33038. * Abstract base class for light shadow classes. These classes
  33039. * represent the shadow configuration for different light types.
  33040. *
  33041. * @abstract
  33042. */
  33043. class LightShadow {
  33044. /**
  33045. * Constructs a new light shadow.
  33046. *
  33047. * @param {Camera} camera - The light's view of the world.
  33048. */
  33049. constructor( camera ) {
  33050. /**
  33051. * The light's view of the world.
  33052. *
  33053. * @type {Camera}
  33054. */
  33055. this.camera = camera;
  33056. /**
  33057. * The intensity of the shadow. The default is `1`.
  33058. * Valid values are in the range `[0, 1]`.
  33059. *
  33060. * @type {number}
  33061. * @default 1
  33062. */
  33063. this.intensity = 1;
  33064. /**
  33065. * Shadow map bias, how much to add or subtract from the normalized depth
  33066. * when deciding whether a surface is in shadow.
  33067. *
  33068. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33069. * may help reduce artifacts in shadows.
  33070. *
  33071. * @type {number}
  33072. * @default 0
  33073. */
  33074. this.bias = 0;
  33075. /**
  33076. * Defines how much the position used to query the shadow map is offset along
  33077. * the object normal. The default is `0`. Increasing this value can be used to
  33078. * reduce shadow acne especially in large scenes where light shines onto
  33079. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33080. *
  33081. * @type {number}
  33082. * @default 0
  33083. */
  33084. this.normalBias = 0;
  33085. /**
  33086. * Setting this to values greater than 1 will blur the edges of the shadow.
  33087. * High values will cause unwanted banding effects in the shadows - a greater
  33088. * map size will allow for a higher value to be used here before these effects
  33089. * become visible.
  33090. *
  33091. * The property has no effect when the shadow map type is `PCFSoftShadowMap` and
  33092. * and it is recommended to increase softness by decreasing the shadow map size instead.
  33093. *
  33094. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33095. *
  33096. * @type {number}
  33097. * @default 1
  33098. */
  33099. this.radius = 1;
  33100. /**
  33101. * The amount of samples to use when blurring a VSM shadow map.
  33102. *
  33103. * @type {number}
  33104. * @default 8
  33105. */
  33106. this.blurSamples = 8;
  33107. /**
  33108. * Defines the width and height of the shadow map. Higher values give better quality
  33109. * shadows at the cost of computation time. Values must be powers of two.
  33110. *
  33111. * @type {Vector2}
  33112. * @default (512,512)
  33113. */
  33114. this.mapSize = new Vector2( 512, 512 );
  33115. /**
  33116. * The type of shadow texture. The default is `UnsignedByteType`.
  33117. *
  33118. * @type {number}
  33119. * @default UnsignedByteType
  33120. */
  33121. this.mapType = UnsignedByteType;
  33122. /**
  33123. * The depth map generated using the internal camera; a location beyond a
  33124. * pixel's depth is in shadow. Computed internally during rendering.
  33125. *
  33126. * @type {?RenderTarget}
  33127. * @default null
  33128. */
  33129. this.map = null;
  33130. /**
  33131. * The distribution map generated using the internal camera; an occlusion is
  33132. * calculated based on the distribution of depths. Computed internally during
  33133. * rendering.
  33134. *
  33135. * @type {?RenderTarget}
  33136. * @default null
  33137. */
  33138. this.mapPass = null;
  33139. /**
  33140. * Model to shadow camera space, to compute location and depth in shadow map.
  33141. * This is computed internally during rendering.
  33142. *
  33143. * @type {Matrix4}
  33144. */
  33145. this.matrix = new Matrix4();
  33146. /**
  33147. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33148. * lighting / shadows, you may set this to `false`.
  33149. *
  33150. * @type {boolean}
  33151. * @default true
  33152. */
  33153. this.autoUpdate = true;
  33154. /**
  33155. * When set to `true`, shadow maps will be updated in the next `render` call.
  33156. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33157. * set this property to `true` and then make a render call to update the light's shadow.
  33158. *
  33159. * @type {boolean}
  33160. * @default false
  33161. */
  33162. this.needsUpdate = false;
  33163. this._frustum = new Frustum();
  33164. this._frameExtents = new Vector2( 1, 1 );
  33165. this._viewportCount = 1;
  33166. this._viewports = [
  33167. new Vector4( 0, 0, 1, 1 )
  33168. ];
  33169. }
  33170. /**
  33171. * Used internally by the renderer to get the number of viewports that need
  33172. * to be rendered for this shadow.
  33173. *
  33174. * @return {number} The viewport count.
  33175. */
  33176. getViewportCount() {
  33177. return this._viewportCount;
  33178. }
  33179. /**
  33180. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33181. *
  33182. * @return {Frustum} The shadow camera frustum.
  33183. */
  33184. getFrustum() {
  33185. return this._frustum;
  33186. }
  33187. /**
  33188. * Update the matrices for the camera and shadow, used internally by the renderer.
  33189. *
  33190. * @param {Light} light - The light for which the shadow is being rendered.
  33191. */
  33192. updateMatrices( light ) {
  33193. const shadowCamera = this.camera;
  33194. const shadowMatrix = this.matrix;
  33195. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33196. shadowCamera.position.copy( _lightPositionWorld$1 );
  33197. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33198. shadowCamera.lookAt( _lookTarget$1 );
  33199. shadowCamera.updateMatrixWorld();
  33200. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33201. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33202. if ( shadowCamera.reversedDepth ) {
  33203. shadowMatrix.set(
  33204. 0.5, 0.0, 0.0, 0.5,
  33205. 0.0, 0.5, 0.0, 0.5,
  33206. 0.0, 0.0, 1.0, 0.0,
  33207. 0.0, 0.0, 0.0, 1.0
  33208. );
  33209. } else {
  33210. shadowMatrix.set(
  33211. 0.5, 0.0, 0.0, 0.5,
  33212. 0.0, 0.5, 0.0, 0.5,
  33213. 0.0, 0.0, 0.5, 0.5,
  33214. 0.0, 0.0, 0.0, 1.0
  33215. );
  33216. }
  33217. shadowMatrix.multiply( _projScreenMatrix$1 );
  33218. }
  33219. /**
  33220. * Returns a viewport definition for the given viewport index.
  33221. *
  33222. * @param {number} viewportIndex - The viewport index.
  33223. * @return {Vector4} The viewport.
  33224. */
  33225. getViewport( viewportIndex ) {
  33226. return this._viewports[ viewportIndex ];
  33227. }
  33228. /**
  33229. * Returns the frame extends.
  33230. *
  33231. * @return {Vector2} The frame extends.
  33232. */
  33233. getFrameExtents() {
  33234. return this._frameExtents;
  33235. }
  33236. /**
  33237. * Frees the GPU-related resources allocated by this instance. Call this
  33238. * method whenever this instance is no longer used in your app.
  33239. */
  33240. dispose() {
  33241. if ( this.map ) {
  33242. this.map.dispose();
  33243. }
  33244. if ( this.mapPass ) {
  33245. this.mapPass.dispose();
  33246. }
  33247. }
  33248. /**
  33249. * Copies the values of the given light shadow instance to this instance.
  33250. *
  33251. * @param {LightShadow} source - The light shadow to copy.
  33252. * @return {LightShadow} A reference to this light shadow instance.
  33253. */
  33254. copy( source ) {
  33255. this.camera = source.camera.clone();
  33256. this.intensity = source.intensity;
  33257. this.bias = source.bias;
  33258. this.radius = source.radius;
  33259. this.autoUpdate = source.autoUpdate;
  33260. this.needsUpdate = source.needsUpdate;
  33261. this.normalBias = source.normalBias;
  33262. this.blurSamples = source.blurSamples;
  33263. this.mapSize.copy( source.mapSize );
  33264. return this;
  33265. }
  33266. /**
  33267. * Returns a new light shadow instance with copied values from this instance.
  33268. *
  33269. * @return {LightShadow} A clone of this instance.
  33270. */
  33271. clone() {
  33272. return new this.constructor().copy( this );
  33273. }
  33274. /**
  33275. * Serializes the light shadow into JSON.
  33276. *
  33277. * @return {Object} A JSON object representing the serialized light shadow.
  33278. * @see {@link ObjectLoader#parse}
  33279. */
  33280. toJSON() {
  33281. const object = {};
  33282. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33283. if ( this.bias !== 0 ) object.bias = this.bias;
  33284. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33285. if ( this.radius !== 1 ) object.radius = this.radius;
  33286. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33287. object.camera = this.camera.toJSON( false ).object;
  33288. delete object.camera.matrix;
  33289. return object;
  33290. }
  33291. }
  33292. /**
  33293. * Represents the shadow configuration of directional lights.
  33294. *
  33295. * @augments LightShadow
  33296. */
  33297. class SpotLightShadow extends LightShadow {
  33298. /**
  33299. * Constructs a new spot light shadow.
  33300. */
  33301. constructor() {
  33302. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33303. /**
  33304. * This flag can be used for type testing.
  33305. *
  33306. * @type {boolean}
  33307. * @readonly
  33308. * @default true
  33309. */
  33310. this.isSpotLightShadow = true;
  33311. /**
  33312. * Used to focus the shadow camera. The camera's field of view is set as a
  33313. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33314. *
  33315. * @type {number}
  33316. * @default 1
  33317. */
  33318. this.focus = 1;
  33319. /**
  33320. * Texture aspect ratio.
  33321. *
  33322. * @type {number}
  33323. * @default 1
  33324. */
  33325. this.aspect = 1;
  33326. }
  33327. updateMatrices( light ) {
  33328. const camera = this.camera;
  33329. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33330. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33331. const far = light.distance || camera.far;
  33332. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33333. camera.fov = fov;
  33334. camera.aspect = aspect;
  33335. camera.far = far;
  33336. camera.updateProjectionMatrix();
  33337. }
  33338. super.updateMatrices( light );
  33339. }
  33340. copy( source ) {
  33341. super.copy( source );
  33342. this.focus = source.focus;
  33343. return this;
  33344. }
  33345. }
  33346. /**
  33347. * This light gets emitted from a single point in one direction, along a cone
  33348. * that increases in size the further from the light it gets.
  33349. *
  33350. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33351. *
  33352. * ```js
  33353. * // white spotlight shining from the side, modulated by a texture
  33354. * const spotLight = new THREE.SpotLight( 0xffffff );
  33355. * spotLight.position.set( 100, 1000, 100 );
  33356. * spotLight.map = new THREE.TextureLoader().load( url );
  33357. *
  33358. * spotLight.castShadow = true;
  33359. * spotLight.shadow.mapSize.width = 1024;
  33360. * spotLight.shadow.mapSize.height = 1024;
  33361. * spotLight.shadow.camera.near = 500;
  33362. * spotLight.shadow.camera.far = 4000;
  33363. * spotLight.shadow.camera.fov = 30;s
  33364. * ```
  33365. *
  33366. * @augments Light
  33367. */
  33368. class SpotLight extends Light {
  33369. /**
  33370. * Constructs a new spot light.
  33371. *
  33372. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33373. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33374. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33375. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33376. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33377. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33378. */
  33379. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33380. super( color, intensity );
  33381. /**
  33382. * This flag can be used for type testing.
  33383. *
  33384. * @type {boolean}
  33385. * @readonly
  33386. * @default true
  33387. */
  33388. this.isSpotLight = true;
  33389. this.type = 'SpotLight';
  33390. this.position.copy( Object3D.DEFAULT_UP );
  33391. this.updateMatrix();
  33392. /**
  33393. * The spot light points from its position to the
  33394. * target's position.
  33395. *
  33396. * For the target's position to be changed to anything other
  33397. * than the default, it must be added to the scene.
  33398. *
  33399. * It is also possible to set the target to be another 3D object
  33400. * in the scene. The light will now track the target object.
  33401. *
  33402. * @type {Object3D}
  33403. */
  33404. this.target = new Object3D();
  33405. /**
  33406. * Maximum range of the light. `0` means no limit.
  33407. *
  33408. * @type {number}
  33409. * @default 0
  33410. */
  33411. this.distance = distance;
  33412. /**
  33413. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33414. *
  33415. * @type {number}
  33416. * @default Math.PI/3
  33417. */
  33418. this.angle = angle;
  33419. /**
  33420. * Percent of the spotlight cone that is attenuated due to penumbra.
  33421. * Value range is `[0,1]`.
  33422. *
  33423. * @type {number}
  33424. * @default 0
  33425. */
  33426. this.penumbra = penumbra;
  33427. /**
  33428. * The amount the light dims along the distance of the light. In context of
  33429. * physically-correct rendering the default value should not be changed.
  33430. *
  33431. * @type {number}
  33432. * @default 2
  33433. */
  33434. this.decay = decay;
  33435. /**
  33436. * A texture used to modulate the color of the light. The spot light
  33437. * color is mixed with the RGB value of this texture, with a ratio
  33438. * corresponding to its alpha value. The cookie-like masking effect is
  33439. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33440. *
  33441. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33442. *
  33443. * @type {?Texture}
  33444. * @default null
  33445. */
  33446. this.map = null;
  33447. /**
  33448. * This property holds the light's shadow configuration.
  33449. *
  33450. * @type {SpotLightShadow}
  33451. */
  33452. this.shadow = new SpotLightShadow();
  33453. }
  33454. /**
  33455. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33456. * Changing the power will also change the light's intensity.
  33457. *
  33458. * @type {number}
  33459. */
  33460. get power() {
  33461. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33462. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33463. return this.intensity * Math.PI;
  33464. }
  33465. set power( power ) {
  33466. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33467. this.intensity = power / Math.PI;
  33468. }
  33469. dispose() {
  33470. this.shadow.dispose();
  33471. }
  33472. copy( source, recursive ) {
  33473. super.copy( source, recursive );
  33474. this.distance = source.distance;
  33475. this.angle = source.angle;
  33476. this.penumbra = source.penumbra;
  33477. this.decay = source.decay;
  33478. this.target = source.target.clone();
  33479. this.shadow = source.shadow.clone();
  33480. return this;
  33481. }
  33482. }
  33483. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33484. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33485. const _lookTarget = /*@__PURE__*/ new Vector3();
  33486. /**
  33487. * Represents the shadow configuration of point lights.
  33488. *
  33489. * @augments LightShadow
  33490. */
  33491. class PointLightShadow extends LightShadow {
  33492. /**
  33493. * Constructs a new point light shadow.
  33494. */
  33495. constructor() {
  33496. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33497. /**
  33498. * This flag can be used for type testing.
  33499. *
  33500. * @type {boolean}
  33501. * @readonly
  33502. * @default true
  33503. */
  33504. this.isPointLightShadow = true;
  33505. this._frameExtents = new Vector2( 4, 2 );
  33506. this._viewportCount = 6;
  33507. this._viewports = [
  33508. // These viewports map a cube-map onto a 2D texture with the
  33509. // following orientation:
  33510. //
  33511. // xzXZ
  33512. // y Y
  33513. //
  33514. // X - Positive x direction
  33515. // x - Negative x direction
  33516. // Y - Positive y direction
  33517. // y - Negative y direction
  33518. // Z - Positive z direction
  33519. // z - Negative z direction
  33520. // positive X
  33521. new Vector4( 2, 1, 1, 1 ),
  33522. // negative X
  33523. new Vector4( 0, 1, 1, 1 ),
  33524. // positive Z
  33525. new Vector4( 3, 1, 1, 1 ),
  33526. // negative Z
  33527. new Vector4( 1, 1, 1, 1 ),
  33528. // positive Y
  33529. new Vector4( 3, 0, 1, 1 ),
  33530. // negative Y
  33531. new Vector4( 1, 0, 1, 1 )
  33532. ];
  33533. this._cubeDirections = [
  33534. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 0, 1 ),
  33535. new Vector3( 0, 0, -1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, -1, 0 )
  33536. ];
  33537. this._cubeUps = [
  33538. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  33539. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33540. ];
  33541. }
  33542. /**
  33543. * Update the matrices for the camera and shadow, used internally by the renderer.
  33544. *
  33545. * @param {Light} light - The light for which the shadow is being rendered.
  33546. * @param {number} [viewportIndex=0] - The viewport index.
  33547. */
  33548. updateMatrices( light, viewportIndex = 0 ) {
  33549. const camera = this.camera;
  33550. const shadowMatrix = this.matrix;
  33551. const far = light.distance || camera.far;
  33552. if ( far !== camera.far ) {
  33553. camera.far = far;
  33554. camera.updateProjectionMatrix();
  33555. }
  33556. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33557. camera.position.copy( _lightPositionWorld );
  33558. _lookTarget.copy( camera.position );
  33559. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  33560. camera.up.copy( this._cubeUps[ viewportIndex ] );
  33561. camera.lookAt( _lookTarget );
  33562. camera.updateMatrixWorld();
  33563. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33564. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33565. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33566. }
  33567. }
  33568. /**
  33569. * A light that gets emitted from a single point in all directions. A common
  33570. * use case for this is to replicate the light emitted from a bare
  33571. * lightbulb.
  33572. *
  33573. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33574. *
  33575. * ```js
  33576. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33577. * light.position.set( 50, 50, 50 );
  33578. * scene.add( light );
  33579. * ```
  33580. *
  33581. * @augments Light
  33582. */
  33583. class PointLight extends Light {
  33584. /**
  33585. * Constructs a new point light.
  33586. *
  33587. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33588. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33589. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33590. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33591. */
  33592. constructor( color, intensity, distance = 0, decay = 2 ) {
  33593. super( color, intensity );
  33594. /**
  33595. * This flag can be used for type testing.
  33596. *
  33597. * @type {boolean}
  33598. * @readonly
  33599. * @default true
  33600. */
  33601. this.isPointLight = true;
  33602. this.type = 'PointLight';
  33603. /**
  33604. * When distance is zero, light will attenuate according to inverse-square
  33605. * law to infinite distance. When distance is non-zero, light will attenuate
  33606. * according to inverse-square law until near the distance cutoff, where it
  33607. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33608. * physically correct.
  33609. *
  33610. * @type {number}
  33611. * @default 0
  33612. */
  33613. this.distance = distance;
  33614. /**
  33615. * The amount the light dims along the distance of the light. In context of
  33616. * physically-correct rendering the default value should not be changed.
  33617. *
  33618. * @type {number}
  33619. * @default 2
  33620. */
  33621. this.decay = decay;
  33622. /**
  33623. * This property holds the light's shadow configuration.
  33624. *
  33625. * @type {PointLightShadow}
  33626. */
  33627. this.shadow = new PointLightShadow();
  33628. }
  33629. /**
  33630. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33631. * Changing the power will also change the light's intensity.
  33632. *
  33633. * @type {number}
  33634. */
  33635. get power() {
  33636. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33637. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33638. return this.intensity * 4 * Math.PI;
  33639. }
  33640. set power( power ) {
  33641. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33642. this.intensity = power / ( 4 * Math.PI );
  33643. }
  33644. dispose() {
  33645. this.shadow.dispose();
  33646. }
  33647. copy( source, recursive ) {
  33648. super.copy( source, recursive );
  33649. this.distance = source.distance;
  33650. this.decay = source.decay;
  33651. this.shadow = source.shadow.clone();
  33652. return this;
  33653. }
  33654. }
  33655. /**
  33656. * Camera that uses [orthographic projection]{@link https://en.wikipedia.org/wiki/Orthographic_projection}.
  33657. *
  33658. * In this projection mode, an object's size in the rendered image stays
  33659. * constant regardless of its distance from the camera. This can be useful
  33660. * for rendering 2D scenes and UI elements, amongst other things.
  33661. *
  33662. * ```js
  33663. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33664. * scene.add( camera );
  33665. * ```
  33666. *
  33667. * @augments Camera
  33668. */
  33669. class OrthographicCamera extends Camera {
  33670. /**
  33671. * Constructs a new orthographic camera.
  33672. *
  33673. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33674. * @param {number} [right=1] - The right plane of the camera's frustum.
  33675. * @param {number} [top=1] - The top plane of the camera's frustum.
  33676. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33677. * @param {number} [near=0.1] - The camera's near plane.
  33678. * @param {number} [far=2000] - The camera's far plane.
  33679. */
  33680. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33681. super();
  33682. /**
  33683. * This flag can be used for type testing.
  33684. *
  33685. * @type {boolean}
  33686. * @readonly
  33687. * @default true
  33688. */
  33689. this.isOrthographicCamera = true;
  33690. this.type = 'OrthographicCamera';
  33691. /**
  33692. * The zoom factor of the camera.
  33693. *
  33694. * @type {number}
  33695. * @default 1
  33696. */
  33697. this.zoom = 1;
  33698. /**
  33699. * Represents the frustum window specification. This property should not be edited
  33700. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33701. *
  33702. * @type {?Object}
  33703. * @default null
  33704. */
  33705. this.view = null;
  33706. /**
  33707. * The left plane of the camera's frustum.
  33708. *
  33709. * @type {number}
  33710. * @default -1
  33711. */
  33712. this.left = left;
  33713. /**
  33714. * The right plane of the camera's frustum.
  33715. *
  33716. * @type {number}
  33717. * @default 1
  33718. */
  33719. this.right = right;
  33720. /**
  33721. * The top plane of the camera's frustum.
  33722. *
  33723. * @type {number}
  33724. * @default 1
  33725. */
  33726. this.top = top;
  33727. /**
  33728. * The bottom plane of the camera's frustum.
  33729. *
  33730. * @type {number}
  33731. * @default -1
  33732. */
  33733. this.bottom = bottom;
  33734. /**
  33735. * The camera's near plane. The valid range is greater than `0`
  33736. * and less than the current value of {@link OrthographicCamera#far}.
  33737. *
  33738. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33739. * valid value for an orthographic camera's near plane.
  33740. *
  33741. * @type {number}
  33742. * @default 0.1
  33743. */
  33744. this.near = near;
  33745. /**
  33746. * The camera's far plane. Must be greater than the
  33747. * current value of {@link OrthographicCamera#near}.
  33748. *
  33749. * @type {number}
  33750. * @default 2000
  33751. */
  33752. this.far = far;
  33753. this.updateProjectionMatrix();
  33754. }
  33755. copy( source, recursive ) {
  33756. super.copy( source, recursive );
  33757. this.left = source.left;
  33758. this.right = source.right;
  33759. this.top = source.top;
  33760. this.bottom = source.bottom;
  33761. this.near = source.near;
  33762. this.far = source.far;
  33763. this.zoom = source.zoom;
  33764. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33765. return this;
  33766. }
  33767. /**
  33768. * Sets an offset in a larger frustum. This is useful for multi-window or
  33769. * multi-monitor/multi-machine setups.
  33770. *
  33771. * @param {number} fullWidth - The full width of multiview setup.
  33772. * @param {number} fullHeight - The full height of multiview setup.
  33773. * @param {number} x - The horizontal offset of the subcamera.
  33774. * @param {number} y - The vertical offset of the subcamera.
  33775. * @param {number} width - The width of subcamera.
  33776. * @param {number} height - The height of subcamera.
  33777. * @see {@link PerspectiveCamera#setViewOffset}
  33778. */
  33779. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33780. if ( this.view === null ) {
  33781. this.view = {
  33782. enabled: true,
  33783. fullWidth: 1,
  33784. fullHeight: 1,
  33785. offsetX: 0,
  33786. offsetY: 0,
  33787. width: 1,
  33788. height: 1
  33789. };
  33790. }
  33791. this.view.enabled = true;
  33792. this.view.fullWidth = fullWidth;
  33793. this.view.fullHeight = fullHeight;
  33794. this.view.offsetX = x;
  33795. this.view.offsetY = y;
  33796. this.view.width = width;
  33797. this.view.height = height;
  33798. this.updateProjectionMatrix();
  33799. }
  33800. /**
  33801. * Removes the view offset from the projection matrix.
  33802. */
  33803. clearViewOffset() {
  33804. if ( this.view !== null ) {
  33805. this.view.enabled = false;
  33806. }
  33807. this.updateProjectionMatrix();
  33808. }
  33809. /**
  33810. * Updates the camera's projection matrix. Must be called after any change of
  33811. * camera properties.
  33812. */
  33813. updateProjectionMatrix() {
  33814. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33815. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33816. const cx = ( this.right + this.left ) / 2;
  33817. const cy = ( this.top + this.bottom ) / 2;
  33818. let left = cx - dx;
  33819. let right = cx + dx;
  33820. let top = cy + dy;
  33821. let bottom = cy - dy;
  33822. if ( this.view !== null && this.view.enabled ) {
  33823. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33824. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33825. left += scaleW * this.view.offsetX;
  33826. right = left + scaleW * this.view.width;
  33827. top -= scaleH * this.view.offsetY;
  33828. bottom = top - scaleH * this.view.height;
  33829. }
  33830. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33831. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33832. }
  33833. toJSON( meta ) {
  33834. const data = super.toJSON( meta );
  33835. data.object.zoom = this.zoom;
  33836. data.object.left = this.left;
  33837. data.object.right = this.right;
  33838. data.object.top = this.top;
  33839. data.object.bottom = this.bottom;
  33840. data.object.near = this.near;
  33841. data.object.far = this.far;
  33842. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  33843. return data;
  33844. }
  33845. }
  33846. /**
  33847. * Represents the shadow configuration of directional lights.
  33848. *
  33849. * @augments LightShadow
  33850. */
  33851. class DirectionalLightShadow extends LightShadow {
  33852. /**
  33853. * Constructs a new directional light shadow.
  33854. */
  33855. constructor() {
  33856. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  33857. /**
  33858. * This flag can be used for type testing.
  33859. *
  33860. * @type {boolean}
  33861. * @readonly
  33862. * @default true
  33863. */
  33864. this.isDirectionalLightShadow = true;
  33865. }
  33866. }
  33867. /**
  33868. * A light that gets emitted in a specific direction. This light will behave
  33869. * as though it is infinitely far away and the rays produced from it are all
  33870. * parallel. The common use case for this is to simulate daylight; the sun is
  33871. * far enough away that its position can be considered to be infinite, and
  33872. * all light rays coming from it are parallel.
  33873. *
  33874. * A common point of confusion for directional lights is that setting the
  33875. * rotation has no effect. This is because three.js's DirectionalLight is the
  33876. * equivalent to what is often called a 'Target Direct Light' in other
  33877. * applications.
  33878. *
  33879. * This means that its direction is calculated as pointing from the light's
  33880. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  33881. * (as opposed to a 'Free Direct Light' that just has a rotation
  33882. * component).
  33883. *
  33884. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  33885. *
  33886. * ```js
  33887. * // White directional light at half intensity shining from the top.
  33888. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  33889. * scene.add( directionalLight );
  33890. * ```
  33891. *
  33892. * @augments Light
  33893. */
  33894. class DirectionalLight extends Light {
  33895. /**
  33896. * Constructs a new directional light.
  33897. *
  33898. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33899. * @param {number} [intensity=1] - The light's strength/intensity.
  33900. */
  33901. constructor( color, intensity ) {
  33902. super( color, intensity );
  33903. /**
  33904. * This flag can be used for type testing.
  33905. *
  33906. * @type {boolean}
  33907. * @readonly
  33908. * @default true
  33909. */
  33910. this.isDirectionalLight = true;
  33911. this.type = 'DirectionalLight';
  33912. this.position.copy( Object3D.DEFAULT_UP );
  33913. this.updateMatrix();
  33914. /**
  33915. * The directional light points from its position to the
  33916. * target's position.
  33917. *
  33918. * For the target's position to be changed to anything other
  33919. * than the default, it must be added to the scene.
  33920. *
  33921. * It is also possible to set the target to be another 3D object
  33922. * in the scene. The light will now track the target object.
  33923. *
  33924. * @type {Object3D}
  33925. */
  33926. this.target = new Object3D();
  33927. /**
  33928. * This property holds the light's shadow configuration.
  33929. *
  33930. * @type {DirectionalLightShadow}
  33931. */
  33932. this.shadow = new DirectionalLightShadow();
  33933. }
  33934. dispose() {
  33935. this.shadow.dispose();
  33936. }
  33937. copy( source ) {
  33938. super.copy( source );
  33939. this.target = source.target.clone();
  33940. this.shadow = source.shadow.clone();
  33941. return this;
  33942. }
  33943. }
  33944. /**
  33945. * This light globally illuminates all objects in the scene equally.
  33946. *
  33947. * It cannot be used to cast shadows as it does not have a direction.
  33948. *
  33949. * ```js
  33950. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  33951. * scene.add( light );
  33952. * ```
  33953. *
  33954. * @augments Light
  33955. */
  33956. class AmbientLight extends Light {
  33957. /**
  33958. * Constructs a new ambient light.
  33959. *
  33960. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33961. * @param {number} [intensity=1] - The light's strength/intensity.
  33962. */
  33963. constructor( color, intensity ) {
  33964. super( color, intensity );
  33965. /**
  33966. * This flag can be used for type testing.
  33967. *
  33968. * @type {boolean}
  33969. * @readonly
  33970. * @default true
  33971. */
  33972. this.isAmbientLight = true;
  33973. this.type = 'AmbientLight';
  33974. }
  33975. }
  33976. /**
  33977. * This class emits light uniformly across the face a rectangular plane.
  33978. * This light type can be used to simulate light sources such as bright
  33979. * windows or strip lighting.
  33980. *
  33981. * Important Notes:
  33982. *
  33983. * - There is no shadow support.
  33984. * - Only PBR materials are supported.
  33985. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  33986. * into your app and init the uniforms/textures.
  33987. *
  33988. * ```js
  33989. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  33990. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  33991. *
  33992. * const intensity = 1; const width = 10; const height = 10;
  33993. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  33994. * rectLight.position.set( 5, 5, 0 );
  33995. * rectLight.lookAt( 0, 0, 0 );
  33996. * scene.add( rectLight )
  33997. * ```
  33998. *
  33999. * @augments Light
  34000. */
  34001. class RectAreaLight extends Light {
  34002. /**
  34003. * Constructs a new area light.
  34004. *
  34005. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34006. * @param {number} [intensity=1] - The light's strength/intensity.
  34007. * @param {number} [width=10] - The width of the light.
  34008. * @param {number} [height=10] - The height of the light.
  34009. */
  34010. constructor( color, intensity, width = 10, height = 10 ) {
  34011. super( color, intensity );
  34012. /**
  34013. * This flag can be used for type testing.
  34014. *
  34015. * @type {boolean}
  34016. * @readonly
  34017. * @default true
  34018. */
  34019. this.isRectAreaLight = true;
  34020. this.type = 'RectAreaLight';
  34021. /**
  34022. * The width of the light.
  34023. *
  34024. * @type {number}
  34025. * @default 10
  34026. */
  34027. this.width = width;
  34028. /**
  34029. * The height of the light.
  34030. *
  34031. * @type {number}
  34032. * @default 10
  34033. */
  34034. this.height = height;
  34035. }
  34036. /**
  34037. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34038. * Changing the power will also change the light's intensity.
  34039. *
  34040. * @type {number}
  34041. */
  34042. get power() {
  34043. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34044. return this.intensity * this.width * this.height * Math.PI;
  34045. }
  34046. set power( power ) {
  34047. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34048. this.intensity = power / ( this.width * this.height * Math.PI );
  34049. }
  34050. copy( source ) {
  34051. super.copy( source );
  34052. this.width = source.width;
  34053. this.height = source.height;
  34054. return this;
  34055. }
  34056. toJSON( meta ) {
  34057. const data = super.toJSON( meta );
  34058. data.object.width = this.width;
  34059. data.object.height = this.height;
  34060. return data;
  34061. }
  34062. }
  34063. /**
  34064. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34065. * to encode lighting information.
  34066. *
  34067. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34068. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34069. */
  34070. class SphericalHarmonics3 {
  34071. /**
  34072. * Constructs a new spherical harmonics.
  34073. */
  34074. constructor() {
  34075. /**
  34076. * This flag can be used for type testing.
  34077. *
  34078. * @type {boolean}
  34079. * @readonly
  34080. * @default true
  34081. */
  34082. this.isSphericalHarmonics3 = true;
  34083. /**
  34084. * An array holding the (9) SH coefficients.
  34085. *
  34086. * @type {Array<Vector3>}
  34087. */
  34088. this.coefficients = [];
  34089. for ( let i = 0; i < 9; i ++ ) {
  34090. this.coefficients.push( new Vector3() );
  34091. }
  34092. }
  34093. /**
  34094. * Sets the given SH coefficients to this instance by copying
  34095. * the values.
  34096. *
  34097. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34098. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34099. */
  34100. set( coefficients ) {
  34101. for ( let i = 0; i < 9; i ++ ) {
  34102. this.coefficients[ i ].copy( coefficients[ i ] );
  34103. }
  34104. return this;
  34105. }
  34106. /**
  34107. * Sets all SH coefficients to `0`.
  34108. *
  34109. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34110. */
  34111. zero() {
  34112. for ( let i = 0; i < 9; i ++ ) {
  34113. this.coefficients[ i ].set( 0, 0, 0 );
  34114. }
  34115. return this;
  34116. }
  34117. /**
  34118. * Returns the radiance in the direction of the given normal.
  34119. *
  34120. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34121. * @param {Vector3} target - The target vector that is used to store the method's result.
  34122. * @return {Vector3} The radiance.
  34123. */
  34124. getAt( normal, target ) {
  34125. // normal is assumed to be unit length
  34126. const x = normal.x, y = normal.y, z = normal.z;
  34127. const coeff = this.coefficients;
  34128. // band 0
  34129. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34130. // band 1
  34131. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34132. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34133. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34134. // band 2
  34135. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34136. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34137. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34138. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34139. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34140. return target;
  34141. }
  34142. /**
  34143. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34144. * direction of the given normal.
  34145. *
  34146. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34147. * @param {Vector3} target - The target vector that is used to store the method's result.
  34148. * @return {Vector3} The irradiance.
  34149. */
  34150. getIrradianceAt( normal, target ) {
  34151. // normal is assumed to be unit length
  34152. const x = normal.x, y = normal.y, z = normal.z;
  34153. const coeff = this.coefficients;
  34154. // band 0
  34155. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34156. // band 1
  34157. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34158. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34159. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34160. // band 2
  34161. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34162. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34163. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34164. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34165. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34166. return target;
  34167. }
  34168. /**
  34169. * Adds the given SH to this instance.
  34170. *
  34171. * @param {SphericalHarmonics3} sh - The SH to add.
  34172. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34173. */
  34174. add( sh ) {
  34175. for ( let i = 0; i < 9; i ++ ) {
  34176. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34177. }
  34178. return this;
  34179. }
  34180. /**
  34181. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34182. * {@link SphericalHarmonics3#scale} at once.
  34183. *
  34184. * @param {SphericalHarmonics3} sh - The SH to add.
  34185. * @param {number} s - The scale factor.
  34186. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34187. */
  34188. addScaledSH( sh, s ) {
  34189. for ( let i = 0; i < 9; i ++ ) {
  34190. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34191. }
  34192. return this;
  34193. }
  34194. /**
  34195. * Scales this SH by the given scale factor.
  34196. *
  34197. * @param {number} s - The scale factor.
  34198. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34199. */
  34200. scale( s ) {
  34201. for ( let i = 0; i < 9; i ++ ) {
  34202. this.coefficients[ i ].multiplyScalar( s );
  34203. }
  34204. return this;
  34205. }
  34206. /**
  34207. * Linear interpolates between the given SH and this instance by the given
  34208. * alpha factor.
  34209. *
  34210. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34211. * @param {number} alpha - The alpha factor.
  34212. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34213. */
  34214. lerp( sh, alpha ) {
  34215. for ( let i = 0; i < 9; i ++ ) {
  34216. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34217. }
  34218. return this;
  34219. }
  34220. /**
  34221. * Returns `true` if this spherical harmonics is equal with the given one.
  34222. *
  34223. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34224. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34225. */
  34226. equals( sh ) {
  34227. for ( let i = 0; i < 9; i ++ ) {
  34228. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34229. return false;
  34230. }
  34231. }
  34232. return true;
  34233. }
  34234. /**
  34235. * Copies the values of the given spherical harmonics to this instance.
  34236. *
  34237. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34238. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34239. */
  34240. copy( sh ) {
  34241. return this.set( sh.coefficients );
  34242. }
  34243. /**
  34244. * Returns a new spherical harmonics with copied values from this instance.
  34245. *
  34246. * @return {SphericalHarmonics3} A clone of this instance.
  34247. */
  34248. clone() {
  34249. return new this.constructor().copy( this );
  34250. }
  34251. /**
  34252. * Sets the SH coefficients of this instance from the given array.
  34253. *
  34254. * @param {Array<number>} array - An array holding the SH coefficients.
  34255. * @param {number} [offset=0] - The array offset where to start copying.
  34256. * @return {SphericalHarmonics3} A clone of this instance.
  34257. */
  34258. fromArray( array, offset = 0 ) {
  34259. const coefficients = this.coefficients;
  34260. for ( let i = 0; i < 9; i ++ ) {
  34261. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34262. }
  34263. return this;
  34264. }
  34265. /**
  34266. * Returns an array with the SH coefficients, or copies them into the provided
  34267. * array. The coefficients are represented as numbers.
  34268. *
  34269. * @param {Array<number>} [array=[]] - The target array.
  34270. * @param {number} [offset=0] - The array offset where to start copying.
  34271. * @return {Array<number>} An array with flat SH coefficients.
  34272. */
  34273. toArray( array = [], offset = 0 ) {
  34274. const coefficients = this.coefficients;
  34275. for ( let i = 0; i < 9; i ++ ) {
  34276. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34277. }
  34278. return array;
  34279. }
  34280. /**
  34281. * Computes the SH basis for the given normal vector.
  34282. *
  34283. * @param {Vector3} normal - The normal.
  34284. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34285. */
  34286. static getBasisAt( normal, shBasis ) {
  34287. // normal is assumed to be unit length
  34288. const x = normal.x, y = normal.y, z = normal.z;
  34289. // band 0
  34290. shBasis[ 0 ] = 0.282095;
  34291. // band 1
  34292. shBasis[ 1 ] = 0.488603 * y;
  34293. shBasis[ 2 ] = 0.488603 * z;
  34294. shBasis[ 3 ] = 0.488603 * x;
  34295. // band 2
  34296. shBasis[ 4 ] = 1.092548 * x * y;
  34297. shBasis[ 5 ] = 1.092548 * y * z;
  34298. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34299. shBasis[ 7 ] = 1.092548 * x * z;
  34300. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34301. }
  34302. }
  34303. /**
  34304. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34305. * classical light sources (e.g. directional, point or spot lights), light
  34306. * probes do not emit light. Instead they store information about light
  34307. * passing through 3D space. During rendering, the light that hits a 3D
  34308. * object is approximated by using the data from the light probe.
  34309. *
  34310. * Light probes are usually created from (radiance) environment maps. The
  34311. * class {@link LightProbeGenerator} can be used to create light probes from
  34312. * cube textures or render targets. However, light estimation data could also
  34313. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34314. * augmented reality content that reacts to real world lighting.
  34315. *
  34316. * The current probe implementation in three.js supports so-called diffuse
  34317. * light probes. This type of light probe is functionally equivalent to an
  34318. * irradiance environment map.
  34319. *
  34320. * @augments Light
  34321. */
  34322. class LightProbe extends Light {
  34323. /**
  34324. * Constructs a new light probe.
  34325. *
  34326. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34327. * @param {number} [intensity=1] - The light's strength/intensity.
  34328. */
  34329. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34330. super( undefined, intensity );
  34331. /**
  34332. * This flag can be used for type testing.
  34333. *
  34334. * @type {boolean}
  34335. * @readonly
  34336. * @default true
  34337. */
  34338. this.isLightProbe = true;
  34339. /**
  34340. * A light probe uses spherical harmonics to encode lighting information.
  34341. *
  34342. * @type {SphericalHarmonics3}
  34343. */
  34344. this.sh = sh;
  34345. }
  34346. copy( source ) {
  34347. super.copy( source );
  34348. this.sh.copy( source.sh );
  34349. return this;
  34350. }
  34351. /**
  34352. * Deserializes the light prove from the given JSON.
  34353. *
  34354. * @param {Object} json - The JSON holding the serialized light probe.
  34355. * @return {LightProbe} A reference to this light probe.
  34356. */
  34357. fromJSON( json ) {
  34358. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34359. this.sh.fromArray( json.sh );
  34360. return this;
  34361. }
  34362. toJSON( meta ) {
  34363. const data = super.toJSON( meta );
  34364. data.object.sh = this.sh.toArray();
  34365. return data;
  34366. }
  34367. }
  34368. /**
  34369. * Class for loading geometries. The files are internally
  34370. * loaded via {@link FileLoader}.
  34371. *
  34372. * ```js
  34373. * const loader = new THREE.MaterialLoader();
  34374. * const material = await loader.loadAsync( 'material.json' );
  34375. * ```
  34376. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34377. *
  34378. * @augments Loader
  34379. */
  34380. class MaterialLoader extends Loader {
  34381. /**
  34382. * Constructs a new material loader.
  34383. *
  34384. * @param {LoadingManager} [manager] - The loading manager.
  34385. */
  34386. constructor( manager ) {
  34387. super( manager );
  34388. /**
  34389. * A dictionary holding textures used by the material.
  34390. *
  34391. * @type {Object<string,Texture>}
  34392. */
  34393. this.textures = {};
  34394. }
  34395. /**
  34396. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34397. *
  34398. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34399. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34400. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34401. * @param {onErrorCallback} onError - Executed when errors occur.
  34402. */
  34403. load( url, onLoad, onProgress, onError ) {
  34404. const scope = this;
  34405. const loader = new FileLoader( scope.manager );
  34406. loader.setPath( scope.path );
  34407. loader.setRequestHeader( scope.requestHeader );
  34408. loader.setWithCredentials( scope.withCredentials );
  34409. loader.load( url, function ( text ) {
  34410. try {
  34411. onLoad( scope.parse( JSON.parse( text ) ) );
  34412. } catch ( e ) {
  34413. if ( onError ) {
  34414. onError( e );
  34415. } else {
  34416. error( e );
  34417. }
  34418. scope.manager.itemError( url );
  34419. }
  34420. }, onProgress, onError );
  34421. }
  34422. /**
  34423. * Parses the given JSON object and returns a material.
  34424. *
  34425. * @param {Object} json - The serialized material.
  34426. * @return {Material} The parsed material.
  34427. */
  34428. parse( json ) {
  34429. const textures = this.textures;
  34430. function getTexture( name ) {
  34431. if ( textures[ name ] === undefined ) {
  34432. warn( 'MaterialLoader: Undefined texture', name );
  34433. }
  34434. return textures[ name ];
  34435. }
  34436. const material = this.createMaterialFromType( json.type );
  34437. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34438. if ( json.name !== undefined ) material.name = json.name;
  34439. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34440. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34441. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34442. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34443. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34444. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34445. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34446. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34447. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34448. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34449. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34450. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34451. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34452. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34453. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34454. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34455. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34456. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34457. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34458. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34459. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34460. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34461. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34462. if ( json.fog !== undefined ) material.fog = json.fog;
  34463. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34464. if ( json.blending !== undefined ) material.blending = json.blending;
  34465. if ( json.combine !== undefined ) material.combine = json.combine;
  34466. if ( json.side !== undefined ) material.side = json.side;
  34467. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34468. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34469. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34470. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34471. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34472. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34473. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34474. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34475. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34476. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34477. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34478. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34479. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34480. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34481. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34482. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34483. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34484. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34485. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34486. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34487. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34488. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34489. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34490. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34491. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34492. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34493. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34494. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34495. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34496. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34497. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34498. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34499. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34500. if ( json.scale !== undefined ) material.scale = json.scale;
  34501. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34502. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34503. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34504. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34505. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34506. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34507. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34508. if ( json.visible !== undefined ) material.visible = json.visible;
  34509. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34510. if ( json.userData !== undefined ) material.userData = json.userData;
  34511. if ( json.vertexColors !== undefined ) {
  34512. if ( typeof json.vertexColors === 'number' ) {
  34513. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34514. } else {
  34515. material.vertexColors = json.vertexColors;
  34516. }
  34517. }
  34518. // Shader Material
  34519. if ( json.uniforms !== undefined ) {
  34520. for ( const name in json.uniforms ) {
  34521. const uniform = json.uniforms[ name ];
  34522. material.uniforms[ name ] = {};
  34523. switch ( uniform.type ) {
  34524. case 't':
  34525. material.uniforms[ name ].value = getTexture( uniform.value );
  34526. break;
  34527. case 'c':
  34528. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34529. break;
  34530. case 'v2':
  34531. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34532. break;
  34533. case 'v3':
  34534. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34535. break;
  34536. case 'v4':
  34537. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34538. break;
  34539. case 'm3':
  34540. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34541. break;
  34542. case 'm4':
  34543. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34544. break;
  34545. default:
  34546. material.uniforms[ name ].value = uniform.value;
  34547. }
  34548. }
  34549. }
  34550. if ( json.defines !== undefined ) material.defines = json.defines;
  34551. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34552. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34553. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34554. if ( json.extensions !== undefined ) {
  34555. for ( const key in json.extensions ) {
  34556. material.extensions[ key ] = json.extensions[ key ];
  34557. }
  34558. }
  34559. if ( json.lights !== undefined ) material.lights = json.lights;
  34560. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34561. // for PointsMaterial
  34562. if ( json.size !== undefined ) material.size = json.size;
  34563. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34564. // maps
  34565. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34566. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34567. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34568. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34569. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34570. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34571. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34572. if ( json.normalScale !== undefined ) {
  34573. let normalScale = json.normalScale;
  34574. if ( Array.isArray( normalScale ) === false ) {
  34575. // Blender exporter used to export a scalar. See #7459
  34576. normalScale = [ normalScale, normalScale ];
  34577. }
  34578. material.normalScale = new Vector2().fromArray( normalScale );
  34579. }
  34580. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34581. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34582. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34583. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34584. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34585. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34586. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34587. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34588. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34589. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34590. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34591. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34592. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34593. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34594. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34595. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34596. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34597. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34598. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34599. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34600. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34601. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34602. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34603. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34604. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34605. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34606. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34607. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34608. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34609. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34610. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34611. return material;
  34612. }
  34613. /**
  34614. * Textures are not embedded in the material JSON so they have
  34615. * to be injected before the loading process starts.
  34616. *
  34617. * @param {Object} value - A dictionary holding textures for material properties.
  34618. * @return {MaterialLoader} A reference to this material loader.
  34619. */
  34620. setTextures( value ) {
  34621. this.textures = value;
  34622. return this;
  34623. }
  34624. /**
  34625. * Creates a material for the given type.
  34626. *
  34627. * @param {string} type - The material type.
  34628. * @return {Material} The new material.
  34629. */
  34630. createMaterialFromType( type ) {
  34631. return MaterialLoader.createMaterialFromType( type );
  34632. }
  34633. /**
  34634. * Creates a material for the given type.
  34635. *
  34636. * @static
  34637. * @param {string} type - The material type.
  34638. * @return {Material} The new material.
  34639. */
  34640. static createMaterialFromType( type ) {
  34641. const materialLib = {
  34642. ShadowMaterial,
  34643. SpriteMaterial,
  34644. RawShaderMaterial,
  34645. ShaderMaterial,
  34646. PointsMaterial,
  34647. MeshPhysicalMaterial,
  34648. MeshStandardMaterial,
  34649. MeshPhongMaterial,
  34650. MeshToonMaterial,
  34651. MeshNormalMaterial,
  34652. MeshLambertMaterial,
  34653. MeshDepthMaterial,
  34654. MeshDistanceMaterial,
  34655. MeshBasicMaterial,
  34656. MeshMatcapMaterial,
  34657. LineDashedMaterial,
  34658. LineBasicMaterial,
  34659. Material
  34660. };
  34661. return new materialLib[ type ]();
  34662. }
  34663. }
  34664. /**
  34665. * A class with loader utility functions.
  34666. */
  34667. class LoaderUtils {
  34668. /**
  34669. * Extracts the base URL from the given URL.
  34670. *
  34671. * @param {string} url -The URL to extract the base URL from.
  34672. * @return {string} The extracted base URL.
  34673. */
  34674. static extractUrlBase( url ) {
  34675. const index = url.lastIndexOf( '/' );
  34676. if ( index === -1 ) return './';
  34677. return url.slice( 0, index + 1 );
  34678. }
  34679. /**
  34680. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34681. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34682. * string.
  34683. *
  34684. * @param {string} url -The URL to resolve.
  34685. * @param {string} path - The base path for relative URLs to be resolved against.
  34686. * @return {string} The resolved URL.
  34687. */
  34688. static resolveURL( url, path ) {
  34689. // Invalid URL
  34690. if ( typeof url !== 'string' || url === '' ) return '';
  34691. // Host Relative URL
  34692. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34693. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34694. }
  34695. // Absolute URL http://,https://,//
  34696. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34697. // Data URI
  34698. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34699. // Blob URL
  34700. if ( /^blob:.*$/i.test( url ) ) return url;
  34701. // Relative URL
  34702. return path + url;
  34703. }
  34704. }
  34705. /**
  34706. * An instanced version of a geometry.
  34707. */
  34708. class InstancedBufferGeometry extends BufferGeometry {
  34709. /**
  34710. * Constructs a new instanced buffer geometry.
  34711. */
  34712. constructor() {
  34713. super();
  34714. /**
  34715. * This flag can be used for type testing.
  34716. *
  34717. * @type {boolean}
  34718. * @readonly
  34719. * @default true
  34720. */
  34721. this.isInstancedBufferGeometry = true;
  34722. this.type = 'InstancedBufferGeometry';
  34723. /**
  34724. * The instance count.
  34725. *
  34726. * @type {number}
  34727. * @default Infinity
  34728. */
  34729. this.instanceCount = Infinity;
  34730. }
  34731. copy( source ) {
  34732. super.copy( source );
  34733. this.instanceCount = source.instanceCount;
  34734. return this;
  34735. }
  34736. toJSON() {
  34737. const data = super.toJSON();
  34738. data.instanceCount = this.instanceCount;
  34739. data.isInstancedBufferGeometry = true;
  34740. return data;
  34741. }
  34742. }
  34743. /**
  34744. * Class for loading geometries. The files are internally
  34745. * loaded via {@link FileLoader}.
  34746. *
  34747. * ```js
  34748. * const loader = new THREE.BufferGeometryLoader();
  34749. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34750. *
  34751. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34752. * const object = new THREE.Mesh( geometry, material );
  34753. * scene.add( object );
  34754. * ```
  34755. *
  34756. * @augments Loader
  34757. */
  34758. class BufferGeometryLoader extends Loader {
  34759. /**
  34760. * Constructs a new geometry loader.
  34761. *
  34762. * @param {LoadingManager} [manager] - The loading manager.
  34763. */
  34764. constructor( manager ) {
  34765. super( manager );
  34766. }
  34767. /**
  34768. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34769. *
  34770. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34771. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34772. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34773. * @param {onErrorCallback} onError - Executed when errors occur.
  34774. */
  34775. load( url, onLoad, onProgress, onError ) {
  34776. const scope = this;
  34777. const loader = new FileLoader( scope.manager );
  34778. loader.setPath( scope.path );
  34779. loader.setRequestHeader( scope.requestHeader );
  34780. loader.setWithCredentials( scope.withCredentials );
  34781. loader.load( url, function ( text ) {
  34782. try {
  34783. onLoad( scope.parse( JSON.parse( text ) ) );
  34784. } catch ( e ) {
  34785. if ( onError ) {
  34786. onError( e );
  34787. } else {
  34788. error( e );
  34789. }
  34790. scope.manager.itemError( url );
  34791. }
  34792. }, onProgress, onError );
  34793. }
  34794. /**
  34795. * Parses the given JSON object and returns a geometry.
  34796. *
  34797. * @param {Object} json - The serialized geometry.
  34798. * @return {BufferGeometry} The parsed geometry.
  34799. */
  34800. parse( json ) {
  34801. const interleavedBufferMap = {};
  34802. const arrayBufferMap = {};
  34803. function getInterleavedBuffer( json, uuid ) {
  34804. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34805. const interleavedBuffers = json.interleavedBuffers;
  34806. const interleavedBuffer = interleavedBuffers[ uuid ];
  34807. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34808. const array = getTypedArray( interleavedBuffer.type, buffer );
  34809. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34810. ib.uuid = interleavedBuffer.uuid;
  34811. interleavedBufferMap[ uuid ] = ib;
  34812. return ib;
  34813. }
  34814. function getArrayBuffer( json, uuid ) {
  34815. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34816. const arrayBuffers = json.arrayBuffers;
  34817. const arrayBuffer = arrayBuffers[ uuid ];
  34818. const ab = new Uint32Array( arrayBuffer ).buffer;
  34819. arrayBufferMap[ uuid ] = ab;
  34820. return ab;
  34821. }
  34822. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34823. const index = json.data.index;
  34824. if ( index !== undefined ) {
  34825. const typedArray = getTypedArray( index.type, index.array );
  34826. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34827. }
  34828. const attributes = json.data.attributes;
  34829. for ( const key in attributes ) {
  34830. const attribute = attributes[ key ];
  34831. let bufferAttribute;
  34832. if ( attribute.isInterleavedBufferAttribute ) {
  34833. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34834. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34835. } else {
  34836. const typedArray = getTypedArray( attribute.type, attribute.array );
  34837. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34838. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  34839. }
  34840. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34841. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  34842. geometry.setAttribute( key, bufferAttribute );
  34843. }
  34844. const morphAttributes = json.data.morphAttributes;
  34845. if ( morphAttributes ) {
  34846. for ( const key in morphAttributes ) {
  34847. const attributeArray = morphAttributes[ key ];
  34848. const array = [];
  34849. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  34850. const attribute = attributeArray[ i ];
  34851. let bufferAttribute;
  34852. if ( attribute.isInterleavedBufferAttribute ) {
  34853. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34854. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34855. } else {
  34856. const typedArray = getTypedArray( attribute.type, attribute.array );
  34857. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  34858. }
  34859. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  34860. array.push( bufferAttribute );
  34861. }
  34862. geometry.morphAttributes[ key ] = array;
  34863. }
  34864. }
  34865. const morphTargetsRelative = json.data.morphTargetsRelative;
  34866. if ( morphTargetsRelative ) {
  34867. geometry.morphTargetsRelative = true;
  34868. }
  34869. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  34870. if ( groups !== undefined ) {
  34871. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  34872. const group = groups[ i ];
  34873. geometry.addGroup( group.start, group.count, group.materialIndex );
  34874. }
  34875. }
  34876. const boundingSphere = json.data.boundingSphere;
  34877. if ( boundingSphere !== undefined ) {
  34878. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  34879. }
  34880. if ( json.name ) geometry.name = json.name;
  34881. if ( json.userData ) geometry.userData = json.userData;
  34882. return geometry;
  34883. }
  34884. }
  34885. /**
  34886. * A loader for loading a JSON resource in the [JSON Object/Scene format]{@link https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4}.
  34887. * The files are internally loaded via {@link FileLoader}.
  34888. *
  34889. * ```js
  34890. * const loader = new THREE.ObjectLoader();
  34891. * const obj = await loader.loadAsync( 'models/json/example.json' );
  34892. * scene.add( obj );
  34893. *
  34894. * // Alternatively, to parse a previously loaded JSON structure
  34895. * const object = await loader.parseAsync( a_json_object );
  34896. * scene.add( object );
  34897. * ```
  34898. *
  34899. * @augments Loader
  34900. */
  34901. class ObjectLoader extends Loader {
  34902. /**
  34903. * Constructs a new object loader.
  34904. *
  34905. * @param {LoadingManager} [manager] - The loading manager.
  34906. */
  34907. constructor( manager ) {
  34908. super( manager );
  34909. }
  34910. /**
  34911. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  34912. *
  34913. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34914. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  34915. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34916. * @param {onErrorCallback} onError - Executed when errors occur.
  34917. */
  34918. load( url, onLoad, onProgress, onError ) {
  34919. const scope = this;
  34920. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34921. this.resourcePath = this.resourcePath || path;
  34922. const loader = new FileLoader( this.manager );
  34923. loader.setPath( this.path );
  34924. loader.setRequestHeader( this.requestHeader );
  34925. loader.setWithCredentials( this.withCredentials );
  34926. loader.load( url, function ( text ) {
  34927. let json = null;
  34928. try {
  34929. json = JSON.parse( text );
  34930. } catch ( error ) {
  34931. if ( onError !== undefined ) onError( error );
  34932. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  34933. return;
  34934. }
  34935. const metadata = json.metadata;
  34936. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34937. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  34938. error( 'ObjectLoader: Can\'t load ' + url );
  34939. return;
  34940. }
  34941. scope.parse( json, onLoad );
  34942. }, onProgress, onError );
  34943. }
  34944. /**
  34945. * Async version of {@link ObjectLoader#load}.
  34946. *
  34947. * @async
  34948. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34949. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34950. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  34951. */
  34952. async loadAsync( url, onProgress ) {
  34953. const scope = this;
  34954. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  34955. this.resourcePath = this.resourcePath || path;
  34956. const loader = new FileLoader( this.manager );
  34957. loader.setPath( this.path );
  34958. loader.setRequestHeader( this.requestHeader );
  34959. loader.setWithCredentials( this.withCredentials );
  34960. const text = await loader.loadAsync( url, onProgress );
  34961. const json = JSON.parse( text );
  34962. const metadata = json.metadata;
  34963. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  34964. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  34965. }
  34966. return await scope.parseAsync( json );
  34967. }
  34968. /**
  34969. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  34970. * but can also be used directly to parse a previously loaded JSON structure.
  34971. *
  34972. * @param {Object} json - The serialized 3D object.
  34973. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  34974. * @return {Object3D} The parsed 3D object.
  34975. */
  34976. parse( json, onLoad ) {
  34977. const animations = this.parseAnimations( json.animations );
  34978. const shapes = this.parseShapes( json.shapes );
  34979. const geometries = this.parseGeometries( json.geometries, shapes );
  34980. const images = this.parseImages( json.images, function () {
  34981. if ( onLoad !== undefined ) onLoad( object );
  34982. } );
  34983. const textures = this.parseTextures( json.textures, images );
  34984. const materials = this.parseMaterials( json.materials, textures );
  34985. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  34986. const skeletons = this.parseSkeletons( json.skeletons, object );
  34987. this.bindSkeletons( object, skeletons );
  34988. this.bindLightTargets( object );
  34989. //
  34990. if ( onLoad !== undefined ) {
  34991. let hasImages = false;
  34992. for ( const uuid in images ) {
  34993. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  34994. hasImages = true;
  34995. break;
  34996. }
  34997. }
  34998. if ( hasImages === false ) onLoad( object );
  34999. }
  35000. return object;
  35001. }
  35002. /**
  35003. * Async version of {@link ObjectLoader#parse}.
  35004. *
  35005. * @param {Object} json - The serialized 3D object.
  35006. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35007. */
  35008. async parseAsync( json ) {
  35009. const animations = this.parseAnimations( json.animations );
  35010. const shapes = this.parseShapes( json.shapes );
  35011. const geometries = this.parseGeometries( json.geometries, shapes );
  35012. const images = await this.parseImagesAsync( json.images );
  35013. const textures = this.parseTextures( json.textures, images );
  35014. const materials = this.parseMaterials( json.materials, textures );
  35015. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35016. const skeletons = this.parseSkeletons( json.skeletons, object );
  35017. this.bindSkeletons( object, skeletons );
  35018. this.bindLightTargets( object );
  35019. return object;
  35020. }
  35021. // internals
  35022. parseShapes( json ) {
  35023. const shapes = {};
  35024. if ( json !== undefined ) {
  35025. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35026. const shape = new Shape().fromJSON( json[ i ] );
  35027. shapes[ shape.uuid ] = shape;
  35028. }
  35029. }
  35030. return shapes;
  35031. }
  35032. parseSkeletons( json, object ) {
  35033. const skeletons = {};
  35034. const bones = {};
  35035. // generate bone lookup table
  35036. object.traverse( function ( child ) {
  35037. if ( child.isBone ) bones[ child.uuid ] = child;
  35038. } );
  35039. // create skeletons
  35040. if ( json !== undefined ) {
  35041. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35042. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35043. skeletons[ skeleton.uuid ] = skeleton;
  35044. }
  35045. }
  35046. return skeletons;
  35047. }
  35048. parseGeometries( json, shapes ) {
  35049. const geometries = {};
  35050. if ( json !== undefined ) {
  35051. const bufferGeometryLoader = new BufferGeometryLoader();
  35052. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35053. let geometry;
  35054. const data = json[ i ];
  35055. switch ( data.type ) {
  35056. case 'BufferGeometry':
  35057. case 'InstancedBufferGeometry':
  35058. geometry = bufferGeometryLoader.parse( data );
  35059. break;
  35060. default:
  35061. if ( data.type in Geometries ) {
  35062. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35063. } else {
  35064. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35065. }
  35066. }
  35067. geometry.uuid = data.uuid;
  35068. if ( data.name !== undefined ) geometry.name = data.name;
  35069. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35070. geometries[ data.uuid ] = geometry;
  35071. }
  35072. }
  35073. return geometries;
  35074. }
  35075. parseMaterials( json, textures ) {
  35076. const cache = {}; // MultiMaterial
  35077. const materials = {};
  35078. if ( json !== undefined ) {
  35079. const loader = new MaterialLoader();
  35080. loader.setTextures( textures );
  35081. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35082. const data = json[ i ];
  35083. if ( cache[ data.uuid ] === undefined ) {
  35084. cache[ data.uuid ] = loader.parse( data );
  35085. }
  35086. materials[ data.uuid ] = cache[ data.uuid ];
  35087. }
  35088. }
  35089. return materials;
  35090. }
  35091. parseAnimations( json ) {
  35092. const animations = {};
  35093. if ( json !== undefined ) {
  35094. for ( let i = 0; i < json.length; i ++ ) {
  35095. const data = json[ i ];
  35096. const clip = AnimationClip.parse( data );
  35097. animations[ clip.uuid ] = clip;
  35098. }
  35099. }
  35100. return animations;
  35101. }
  35102. parseImages( json, onLoad ) {
  35103. const scope = this;
  35104. const images = {};
  35105. let loader;
  35106. function loadImage( url ) {
  35107. scope.manager.itemStart( url );
  35108. return loader.load( url, function () {
  35109. scope.manager.itemEnd( url );
  35110. }, undefined, function () {
  35111. scope.manager.itemError( url );
  35112. scope.manager.itemEnd( url );
  35113. } );
  35114. }
  35115. function deserializeImage( image ) {
  35116. if ( typeof image === 'string' ) {
  35117. const url = image;
  35118. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35119. return loadImage( path );
  35120. } else {
  35121. if ( image.data ) {
  35122. return {
  35123. data: getTypedArray( image.type, image.data ),
  35124. width: image.width,
  35125. height: image.height
  35126. };
  35127. } else {
  35128. return null;
  35129. }
  35130. }
  35131. }
  35132. if ( json !== undefined && json.length > 0 ) {
  35133. const manager = new LoadingManager( onLoad );
  35134. loader = new ImageLoader( manager );
  35135. loader.setCrossOrigin( this.crossOrigin );
  35136. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35137. const image = json[ i ];
  35138. const url = image.url;
  35139. if ( Array.isArray( url ) ) {
  35140. // load array of images e.g CubeTexture
  35141. const imageArray = [];
  35142. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35143. const currentUrl = url[ j ];
  35144. const deserializedImage = deserializeImage( currentUrl );
  35145. if ( deserializedImage !== null ) {
  35146. if ( deserializedImage instanceof HTMLImageElement ) {
  35147. imageArray.push( deserializedImage );
  35148. } else {
  35149. // special case: handle array of data textures for cube textures
  35150. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35151. }
  35152. }
  35153. }
  35154. images[ image.uuid ] = new Source( imageArray );
  35155. } else {
  35156. // load single image
  35157. const deserializedImage = deserializeImage( image.url );
  35158. images[ image.uuid ] = new Source( deserializedImage );
  35159. }
  35160. }
  35161. }
  35162. return images;
  35163. }
  35164. async parseImagesAsync( json ) {
  35165. const scope = this;
  35166. const images = {};
  35167. let loader;
  35168. async function deserializeImage( image ) {
  35169. if ( typeof image === 'string' ) {
  35170. const url = image;
  35171. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35172. return await loader.loadAsync( path );
  35173. } else {
  35174. if ( image.data ) {
  35175. return {
  35176. data: getTypedArray( image.type, image.data ),
  35177. width: image.width,
  35178. height: image.height
  35179. };
  35180. } else {
  35181. return null;
  35182. }
  35183. }
  35184. }
  35185. if ( json !== undefined && json.length > 0 ) {
  35186. loader = new ImageLoader( this.manager );
  35187. loader.setCrossOrigin( this.crossOrigin );
  35188. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35189. const image = json[ i ];
  35190. const url = image.url;
  35191. if ( Array.isArray( url ) ) {
  35192. // load array of images e.g CubeTexture
  35193. const imageArray = [];
  35194. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35195. const currentUrl = url[ j ];
  35196. const deserializedImage = await deserializeImage( currentUrl );
  35197. if ( deserializedImage !== null ) {
  35198. if ( deserializedImage instanceof HTMLImageElement ) {
  35199. imageArray.push( deserializedImage );
  35200. } else {
  35201. // special case: handle array of data textures for cube textures
  35202. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35203. }
  35204. }
  35205. }
  35206. images[ image.uuid ] = new Source( imageArray );
  35207. } else {
  35208. // load single image
  35209. const deserializedImage = await deserializeImage( image.url );
  35210. images[ image.uuid ] = new Source( deserializedImage );
  35211. }
  35212. }
  35213. }
  35214. return images;
  35215. }
  35216. parseTextures( json, images ) {
  35217. function parseConstant( value, type ) {
  35218. if ( typeof value === 'number' ) return value;
  35219. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35220. return type[ value ];
  35221. }
  35222. const textures = {};
  35223. if ( json !== undefined ) {
  35224. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35225. const data = json[ i ];
  35226. if ( data.image === undefined ) {
  35227. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35228. }
  35229. if ( images[ data.image ] === undefined ) {
  35230. warn( 'ObjectLoader: Undefined image', data.image );
  35231. }
  35232. const source = images[ data.image ];
  35233. const image = source.data;
  35234. let texture;
  35235. if ( Array.isArray( image ) ) {
  35236. texture = new CubeTexture();
  35237. if ( image.length === 6 ) texture.needsUpdate = true;
  35238. } else {
  35239. if ( image && image.data ) {
  35240. texture = new DataTexture();
  35241. } else {
  35242. texture = new Texture();
  35243. }
  35244. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35245. }
  35246. texture.source = source;
  35247. texture.uuid = data.uuid;
  35248. if ( data.name !== undefined ) texture.name = data.name;
  35249. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35250. if ( data.channel !== undefined ) texture.channel = data.channel;
  35251. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35252. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35253. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35254. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35255. if ( data.wrap !== undefined ) {
  35256. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35257. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35258. }
  35259. if ( data.format !== undefined ) texture.format = data.format;
  35260. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35261. if ( data.type !== undefined ) texture.type = data.type;
  35262. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35263. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35264. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35265. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35266. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35267. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35268. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35269. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35270. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35271. if ( data.userData !== undefined ) texture.userData = data.userData;
  35272. textures[ data.uuid ] = texture;
  35273. }
  35274. }
  35275. return textures;
  35276. }
  35277. parseObject( data, geometries, materials, textures, animations ) {
  35278. let object;
  35279. function getGeometry( name ) {
  35280. if ( geometries[ name ] === undefined ) {
  35281. warn( 'ObjectLoader: Undefined geometry', name );
  35282. }
  35283. return geometries[ name ];
  35284. }
  35285. function getMaterial( name ) {
  35286. if ( name === undefined ) return undefined;
  35287. if ( Array.isArray( name ) ) {
  35288. const array = [];
  35289. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35290. const uuid = name[ i ];
  35291. if ( materials[ uuid ] === undefined ) {
  35292. warn( 'ObjectLoader: Undefined material', uuid );
  35293. }
  35294. array.push( materials[ uuid ] );
  35295. }
  35296. return array;
  35297. }
  35298. if ( materials[ name ] === undefined ) {
  35299. warn( 'ObjectLoader: Undefined material', name );
  35300. }
  35301. return materials[ name ];
  35302. }
  35303. function getTexture( uuid ) {
  35304. if ( textures[ uuid ] === undefined ) {
  35305. warn( 'ObjectLoader: Undefined texture', uuid );
  35306. }
  35307. return textures[ uuid ];
  35308. }
  35309. let geometry, material;
  35310. switch ( data.type ) {
  35311. case 'Scene':
  35312. object = new Scene();
  35313. if ( data.background !== undefined ) {
  35314. if ( Number.isInteger( data.background ) ) {
  35315. object.background = new Color( data.background );
  35316. } else {
  35317. object.background = getTexture( data.background );
  35318. }
  35319. }
  35320. if ( data.environment !== undefined ) {
  35321. object.environment = getTexture( data.environment );
  35322. }
  35323. if ( data.fog !== undefined ) {
  35324. if ( data.fog.type === 'Fog' ) {
  35325. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35326. } else if ( data.fog.type === 'FogExp2' ) {
  35327. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35328. }
  35329. if ( data.fog.name !== '' ) {
  35330. object.fog.name = data.fog.name;
  35331. }
  35332. }
  35333. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35334. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35335. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35336. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35337. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35338. break;
  35339. case 'PerspectiveCamera':
  35340. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35341. if ( data.focus !== undefined ) object.focus = data.focus;
  35342. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35343. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35344. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35345. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35346. break;
  35347. case 'OrthographicCamera':
  35348. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35349. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35350. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35351. break;
  35352. case 'AmbientLight':
  35353. object = new AmbientLight( data.color, data.intensity );
  35354. break;
  35355. case 'DirectionalLight':
  35356. object = new DirectionalLight( data.color, data.intensity );
  35357. object.target = data.target || '';
  35358. break;
  35359. case 'PointLight':
  35360. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35361. break;
  35362. case 'RectAreaLight':
  35363. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35364. break;
  35365. case 'SpotLight':
  35366. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35367. object.target = data.target || '';
  35368. break;
  35369. case 'HemisphereLight':
  35370. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35371. break;
  35372. case 'LightProbe':
  35373. object = new LightProbe().fromJSON( data );
  35374. break;
  35375. case 'SkinnedMesh':
  35376. geometry = getGeometry( data.geometry );
  35377. material = getMaterial( data.material );
  35378. object = new SkinnedMesh( geometry, material );
  35379. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35380. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35381. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35382. break;
  35383. case 'Mesh':
  35384. geometry = getGeometry( data.geometry );
  35385. material = getMaterial( data.material );
  35386. object = new Mesh( geometry, material );
  35387. break;
  35388. case 'InstancedMesh':
  35389. geometry = getGeometry( data.geometry );
  35390. material = getMaterial( data.material );
  35391. const count = data.count;
  35392. const instanceMatrix = data.instanceMatrix;
  35393. const instanceColor = data.instanceColor;
  35394. object = new InstancedMesh( geometry, material, count );
  35395. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35396. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35397. break;
  35398. case 'BatchedMesh':
  35399. geometry = getGeometry( data.geometry );
  35400. material = getMaterial( data.material );
  35401. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35402. object.geometry = geometry;
  35403. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35404. object.sortObjects = data.sortObjects;
  35405. object._drawRanges = data.drawRanges;
  35406. object._reservedRanges = data.reservedRanges;
  35407. object._geometryInfo = data.geometryInfo.map( info => {
  35408. let box = null;
  35409. let sphere = null;
  35410. if ( info.boundingBox !== undefined ) {
  35411. box = new Box3().fromJSON( info.boundingBox );
  35412. }
  35413. if ( info.boundingSphere !== undefined ) {
  35414. sphere = new Sphere().fromJSON( info.boundingSphere );
  35415. }
  35416. return {
  35417. ...info,
  35418. boundingBox: box,
  35419. boundingSphere: sphere
  35420. };
  35421. } );
  35422. object._instanceInfo = data.instanceInfo;
  35423. object._availableInstanceIds = data._availableInstanceIds;
  35424. object._availableGeometryIds = data._availableGeometryIds;
  35425. object._nextIndexStart = data.nextIndexStart;
  35426. object._nextVertexStart = data.nextVertexStart;
  35427. object._geometryCount = data.geometryCount;
  35428. object._maxInstanceCount = data.maxInstanceCount;
  35429. object._maxVertexCount = data.maxVertexCount;
  35430. object._maxIndexCount = data.maxIndexCount;
  35431. object._geometryInitialized = data.geometryInitialized;
  35432. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35433. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35434. if ( data.colorsTexture !== undefined ) {
  35435. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35436. }
  35437. if ( data.boundingSphere !== undefined ) {
  35438. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35439. }
  35440. if ( data.boundingBox !== undefined ) {
  35441. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35442. }
  35443. break;
  35444. case 'LOD':
  35445. object = new LOD();
  35446. break;
  35447. case 'Line':
  35448. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35449. break;
  35450. case 'LineLoop':
  35451. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35452. break;
  35453. case 'LineSegments':
  35454. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35455. break;
  35456. case 'PointCloud':
  35457. case 'Points':
  35458. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35459. break;
  35460. case 'Sprite':
  35461. object = new Sprite( getMaterial( data.material ) );
  35462. break;
  35463. case 'Group':
  35464. object = new Group();
  35465. break;
  35466. case 'Bone':
  35467. object = new Bone();
  35468. break;
  35469. default:
  35470. object = new Object3D();
  35471. }
  35472. object.uuid = data.uuid;
  35473. if ( data.name !== undefined ) object.name = data.name;
  35474. if ( data.matrix !== undefined ) {
  35475. object.matrix.fromArray( data.matrix );
  35476. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35477. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35478. } else {
  35479. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35480. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35481. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35482. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35483. }
  35484. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35485. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35486. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35487. if ( data.shadow ) {
  35488. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35489. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35490. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35491. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35492. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35493. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35494. }
  35495. if ( data.visible !== undefined ) object.visible = data.visible;
  35496. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35497. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35498. if ( data.userData !== undefined ) object.userData = data.userData;
  35499. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35500. if ( data.children !== undefined ) {
  35501. const children = data.children;
  35502. for ( let i = 0; i < children.length; i ++ ) {
  35503. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35504. }
  35505. }
  35506. if ( data.animations !== undefined ) {
  35507. const objectAnimations = data.animations;
  35508. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35509. const uuid = objectAnimations[ i ];
  35510. object.animations.push( animations[ uuid ] );
  35511. }
  35512. }
  35513. if ( data.type === 'LOD' ) {
  35514. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35515. const levels = data.levels;
  35516. for ( let l = 0; l < levels.length; l ++ ) {
  35517. const level = levels[ l ];
  35518. const child = object.getObjectByProperty( 'uuid', level.object );
  35519. if ( child !== undefined ) {
  35520. object.addLevel( child, level.distance, level.hysteresis );
  35521. }
  35522. }
  35523. }
  35524. return object;
  35525. }
  35526. bindSkeletons( object, skeletons ) {
  35527. if ( Object.keys( skeletons ).length === 0 ) return;
  35528. object.traverse( function ( child ) {
  35529. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35530. const skeleton = skeletons[ child.skeleton ];
  35531. if ( skeleton === undefined ) {
  35532. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35533. } else {
  35534. child.bind( skeleton, child.bindMatrix );
  35535. }
  35536. }
  35537. } );
  35538. }
  35539. bindLightTargets( object ) {
  35540. object.traverse( function ( child ) {
  35541. if ( child.isDirectionalLight || child.isSpotLight ) {
  35542. const uuid = child.target;
  35543. const target = object.getObjectByProperty( 'uuid', uuid );
  35544. if ( target !== undefined ) {
  35545. child.target = target;
  35546. } else {
  35547. child.target = new Object3D();
  35548. }
  35549. }
  35550. } );
  35551. }
  35552. }
  35553. const TEXTURE_MAPPING = {
  35554. UVMapping: UVMapping,
  35555. CubeReflectionMapping: CubeReflectionMapping,
  35556. CubeRefractionMapping: CubeRefractionMapping,
  35557. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35558. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35559. CubeUVReflectionMapping: CubeUVReflectionMapping
  35560. };
  35561. const TEXTURE_WRAPPING = {
  35562. RepeatWrapping: RepeatWrapping,
  35563. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35564. MirroredRepeatWrapping: MirroredRepeatWrapping
  35565. };
  35566. const TEXTURE_FILTER = {
  35567. NearestFilter: NearestFilter,
  35568. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35569. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35570. LinearFilter: LinearFilter,
  35571. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35572. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35573. };
  35574. const _errorMap = new WeakMap();
  35575. /**
  35576. * A loader for loading images as an [ImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap}.
  35577. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35578. * textures for rendering.
  35579. *
  35580. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35581. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35582. *
  35583. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35584. *
  35585. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35586. *
  35587. * ```js
  35588. * const loader = new THREE.ImageBitmapLoader();
  35589. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35590. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35591. *
  35592. * const texture = new THREE.Texture( imageBitmap );
  35593. * texture.needsUpdate = true;
  35594. * ```
  35595. *
  35596. * @augments Loader
  35597. */
  35598. class ImageBitmapLoader extends Loader {
  35599. /**
  35600. * Constructs a new image bitmap loader.
  35601. *
  35602. * @param {LoadingManager} [manager] - The loading manager.
  35603. */
  35604. constructor( manager ) {
  35605. super( manager );
  35606. /**
  35607. * This flag can be used for type testing.
  35608. *
  35609. * @type {boolean}
  35610. * @readonly
  35611. * @default true
  35612. */
  35613. this.isImageBitmapLoader = true;
  35614. if ( typeof createImageBitmap === 'undefined' ) {
  35615. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35616. }
  35617. if ( typeof fetch === 'undefined' ) {
  35618. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35619. }
  35620. /**
  35621. * Represents the loader options.
  35622. *
  35623. * @type {Object}
  35624. * @default {premultiplyAlpha:'none'}
  35625. */
  35626. this.options = { premultiplyAlpha: 'none' };
  35627. /**
  35628. * Used for aborting requests.
  35629. *
  35630. * @private
  35631. * @type {AbortController}
  35632. */
  35633. this._abortController = new AbortController();
  35634. }
  35635. /**
  35636. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35637. * [createImageBitmap]{@link https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap}.
  35638. *
  35639. * @param {Object} options - The loader options to set.
  35640. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35641. */
  35642. setOptions( options ) {
  35643. this.options = options;
  35644. return this;
  35645. }
  35646. /**
  35647. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35648. *
  35649. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35650. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35651. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35652. * @param {onErrorCallback} onError - Executed when errors occur.
  35653. * @return {ImageBitmap|undefined} The image bitmap.
  35654. */
  35655. load( url, onLoad, onProgress, onError ) {
  35656. if ( url === undefined ) url = '';
  35657. if ( this.path !== undefined ) url = this.path + url;
  35658. url = this.manager.resolveURL( url );
  35659. const scope = this;
  35660. const cached = Cache.get( `image-bitmap:${url}` );
  35661. if ( cached !== undefined ) {
  35662. scope.manager.itemStart( url );
  35663. // If cached is a promise, wait for it to resolve
  35664. if ( cached.then ) {
  35665. cached.then( imageBitmap => {
  35666. // check if there is an error for the cached promise
  35667. if ( _errorMap.has( cached ) === true ) {
  35668. if ( onError ) onError( _errorMap.get( cached ) );
  35669. scope.manager.itemError( url );
  35670. scope.manager.itemEnd( url );
  35671. } else {
  35672. if ( onLoad ) onLoad( imageBitmap );
  35673. scope.manager.itemEnd( url );
  35674. return imageBitmap;
  35675. }
  35676. } );
  35677. return;
  35678. }
  35679. // If cached is not a promise (i.e., it's already an imageBitmap)
  35680. setTimeout( function () {
  35681. if ( onLoad ) onLoad( cached );
  35682. scope.manager.itemEnd( url );
  35683. }, 0 );
  35684. return cached;
  35685. }
  35686. const fetchOptions = {};
  35687. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35688. fetchOptions.headers = this.requestHeader;
  35689. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35690. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35691. return res.blob();
  35692. } ).then( function ( blob ) {
  35693. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35694. } ).then( function ( imageBitmap ) {
  35695. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35696. if ( onLoad ) onLoad( imageBitmap );
  35697. scope.manager.itemEnd( url );
  35698. return imageBitmap;
  35699. } ).catch( function ( e ) {
  35700. if ( onError ) onError( e );
  35701. _errorMap.set( promise, e );
  35702. Cache.remove( `image-bitmap:${url}` );
  35703. scope.manager.itemError( url );
  35704. scope.manager.itemEnd( url );
  35705. } );
  35706. Cache.add( `image-bitmap:${url}`, promise );
  35707. scope.manager.itemStart( url );
  35708. }
  35709. /**
  35710. * Aborts ongoing fetch requests.
  35711. *
  35712. * @return {ImageBitmapLoader} A reference to this instance.
  35713. */
  35714. abort() {
  35715. this._abortController.abort();
  35716. this._abortController = new AbortController();
  35717. return this;
  35718. }
  35719. }
  35720. let _context;
  35721. /**
  35722. * Manages the global audio context in the engine.
  35723. *
  35724. * @hideconstructor
  35725. */
  35726. class AudioContext {
  35727. /**
  35728. * Returns the global native audio context.
  35729. *
  35730. * @return {AudioContext} The native audio context.
  35731. */
  35732. static getContext() {
  35733. if ( _context === undefined ) {
  35734. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35735. }
  35736. return _context;
  35737. }
  35738. /**
  35739. * Allows to set the global native audio context from outside.
  35740. *
  35741. * @param {AudioContext} value - The native context to set.
  35742. */
  35743. static setContext( value ) {
  35744. _context = value;
  35745. }
  35746. }
  35747. /**
  35748. * Class for loading audio buffers. Audios are internally
  35749. * loaded via {@link FileLoader}.
  35750. *
  35751. * ```js
  35752. * const audioListener = new THREE.AudioListener();
  35753. * const ambientSound = new THREE.Audio( audioListener );
  35754. *
  35755. * const loader = new THREE.AudioLoader();
  35756. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35757. *
  35758. * ambientSound.setBuffer( audioBuffer );
  35759. * ambientSound.play();
  35760. * ```
  35761. *
  35762. * @augments Loader
  35763. */
  35764. class AudioLoader extends Loader {
  35765. /**
  35766. * Constructs a new audio loader.
  35767. *
  35768. * @param {LoadingManager} [manager] - The loading manager.
  35769. */
  35770. constructor( manager ) {
  35771. super( manager );
  35772. }
  35773. /**
  35774. * Starts loading from the given URL and passes the loaded audio buffer
  35775. * to the `onLoad()` callback.
  35776. *
  35777. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35778. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35779. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35780. * @param {onErrorCallback} onError - Executed when errors occur.
  35781. */
  35782. load( url, onLoad, onProgress, onError ) {
  35783. const scope = this;
  35784. const loader = new FileLoader( this.manager );
  35785. loader.setResponseType( 'arraybuffer' );
  35786. loader.setPath( this.path );
  35787. loader.setRequestHeader( this.requestHeader );
  35788. loader.setWithCredentials( this.withCredentials );
  35789. loader.load( url, function ( buffer ) {
  35790. try {
  35791. // Create a copy of the buffer. The `decodeAudioData` method
  35792. // detaches the buffer when complete, preventing reuse.
  35793. const bufferCopy = buffer.slice( 0 );
  35794. const context = AudioContext.getContext();
  35795. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35796. onLoad( audioBuffer );
  35797. } ).catch( handleError );
  35798. } catch ( e ) {
  35799. handleError( e );
  35800. }
  35801. }, onProgress, onError );
  35802. function handleError( e ) {
  35803. if ( onError ) {
  35804. onError( e );
  35805. } else {
  35806. error( e );
  35807. }
  35808. scope.manager.itemError( url );
  35809. }
  35810. }
  35811. }
  35812. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35813. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35814. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35815. /**
  35816. * A special type of camera that uses two perspective cameras with
  35817. * stereoscopic projection. Can be used for rendering stereo effects
  35818. * like [3D Anaglyph]{@link https://en.wikipedia.org/wiki/Anaglyph_3D} or
  35819. * [Parallax Barrier]{@link https://en.wikipedia.org/wiki/parallax_barrier}.
  35820. */
  35821. class StereoCamera {
  35822. /**
  35823. * Constructs a new stereo camera.
  35824. */
  35825. constructor() {
  35826. /**
  35827. * The type property is used for detecting the object type
  35828. * in context of serialization/deserialization.
  35829. *
  35830. * @type {string}
  35831. * @readonly
  35832. */
  35833. this.type = 'StereoCamera';
  35834. /**
  35835. * The aspect.
  35836. *
  35837. * @type {number}
  35838. * @default 1
  35839. */
  35840. this.aspect = 1;
  35841. /**
  35842. * The eye separation which represents the distance
  35843. * between the left and right camera.
  35844. *
  35845. * @type {number}
  35846. * @default 0.064
  35847. */
  35848. this.eyeSep = 0.064;
  35849. /**
  35850. * The camera representing the left eye. This is added to layer `1` so objects to be
  35851. * rendered by the left camera must also be added to this layer.
  35852. *
  35853. * @type {PerspectiveCamera}
  35854. */
  35855. this.cameraL = new PerspectiveCamera();
  35856. this.cameraL.layers.enable( 1 );
  35857. this.cameraL.matrixAutoUpdate = false;
  35858. /**
  35859. * The camera representing the right eye. This is added to layer `2` so objects to be
  35860. * rendered by the right camera must also be added to this layer.
  35861. *
  35862. * @type {PerspectiveCamera}
  35863. */
  35864. this.cameraR = new PerspectiveCamera();
  35865. this.cameraR.layers.enable( 2 );
  35866. this.cameraR.matrixAutoUpdate = false;
  35867. this._cache = {
  35868. focus: null,
  35869. fov: null,
  35870. aspect: null,
  35871. near: null,
  35872. far: null,
  35873. zoom: null,
  35874. eyeSep: null
  35875. };
  35876. }
  35877. /**
  35878. * Updates the stereo camera based on the given perspective camera.
  35879. *
  35880. * @param {PerspectiveCamera} camera - The perspective camera.
  35881. */
  35882. update( camera ) {
  35883. const cache = this._cache;
  35884. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  35885. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  35886. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  35887. if ( needsUpdate ) {
  35888. cache.focus = camera.focus;
  35889. cache.fov = camera.fov;
  35890. cache.aspect = camera.aspect * this.aspect;
  35891. cache.near = camera.near;
  35892. cache.far = camera.far;
  35893. cache.zoom = camera.zoom;
  35894. cache.eyeSep = this.eyeSep;
  35895. // Off-axis stereoscopic effect based on
  35896. // http://paulbourke.net/stereographics/stereorender/
  35897. _projectionMatrix.copy( camera.projectionMatrix );
  35898. const eyeSepHalf = cache.eyeSep / 2;
  35899. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  35900. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  35901. let xmin, xmax;
  35902. // translate xOffset
  35903. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  35904. _eyeRight.elements[ 12 ] = eyeSepHalf;
  35905. // for left eye
  35906. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  35907. xmax = ymax * cache.aspect + eyeSepOnProjection;
  35908. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35909. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35910. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  35911. // for right eye
  35912. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  35913. xmax = ymax * cache.aspect - eyeSepOnProjection;
  35914. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  35915. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  35916. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  35917. }
  35918. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  35919. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  35920. }
  35921. }
  35922. /**
  35923. * This type of camera can be used in order to efficiently render a scene with a
  35924. * predefined set of cameras. This is an important performance aspect for
  35925. * rendering VR scenes.
  35926. *
  35927. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  35928. * to define for each sub camera the `viewport` property which determines the
  35929. * part of the viewport that is rendered with this camera.
  35930. *
  35931. * @augments PerspectiveCamera
  35932. */
  35933. class ArrayCamera extends PerspectiveCamera {
  35934. /**
  35935. * Constructs a new array camera.
  35936. *
  35937. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  35938. */
  35939. constructor( array = [] ) {
  35940. super();
  35941. /**
  35942. * This flag can be used for type testing.
  35943. *
  35944. * @type {boolean}
  35945. * @readonly
  35946. * @default true
  35947. */
  35948. this.isArrayCamera = true;
  35949. /**
  35950. * Whether this camera is used with multiview rendering or not.
  35951. *
  35952. * @type {boolean}
  35953. * @readonly
  35954. * @default false
  35955. */
  35956. this.isMultiViewCamera = false;
  35957. /**
  35958. * An array of perspective sub cameras.
  35959. *
  35960. * @type {Array<PerspectiveCamera>}
  35961. */
  35962. this.cameras = array;
  35963. }
  35964. }
  35965. /**
  35966. * Class for keeping track of time.
  35967. */
  35968. class Clock {
  35969. /**
  35970. * Constructs a new clock.
  35971. *
  35972. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  35973. * `getDelta()` is called for the first time.
  35974. */
  35975. constructor( autoStart = true ) {
  35976. /**
  35977. * If set to `true`, the clock starts automatically when `getDelta()` is called
  35978. * for the first time.
  35979. *
  35980. * @type {boolean}
  35981. * @default true
  35982. */
  35983. this.autoStart = autoStart;
  35984. /**
  35985. * Holds the time at which the clock's `start()` method was last called.
  35986. *
  35987. * @type {number}
  35988. * @default 0
  35989. */
  35990. this.startTime = 0;
  35991. /**
  35992. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  35993. * `getDelta()` methods were last called.
  35994. *
  35995. * @type {number}
  35996. * @default 0
  35997. */
  35998. this.oldTime = 0;
  35999. /**
  36000. * Keeps track of the total time that the clock has been running.
  36001. *
  36002. * @type {number}
  36003. * @default 0
  36004. */
  36005. this.elapsedTime = 0;
  36006. /**
  36007. * Whether the clock is running or not.
  36008. *
  36009. * @type {boolean}
  36010. * @default true
  36011. */
  36012. this.running = false;
  36013. }
  36014. /**
  36015. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36016. * called by the class.
  36017. */
  36018. start() {
  36019. this.startTime = performance.now();
  36020. this.oldTime = this.startTime;
  36021. this.elapsedTime = 0;
  36022. this.running = true;
  36023. }
  36024. /**
  36025. * Stops the clock.
  36026. */
  36027. stop() {
  36028. this.getElapsedTime();
  36029. this.running = false;
  36030. this.autoStart = false;
  36031. }
  36032. /**
  36033. * Returns the elapsed time in seconds.
  36034. *
  36035. * @return {number} The elapsed time.
  36036. */
  36037. getElapsedTime() {
  36038. this.getDelta();
  36039. return this.elapsedTime;
  36040. }
  36041. /**
  36042. * Returns the delta time in seconds.
  36043. *
  36044. * @return {number} The delta time.
  36045. */
  36046. getDelta() {
  36047. let diff = 0;
  36048. if ( this.autoStart && ! this.running ) {
  36049. this.start();
  36050. return 0;
  36051. }
  36052. if ( this.running ) {
  36053. const newTime = performance.now();
  36054. diff = ( newTime - this.oldTime ) / 1000;
  36055. this.oldTime = newTime;
  36056. this.elapsedTime += diff;
  36057. }
  36058. return diff;
  36059. }
  36060. }
  36061. const _position$1 = /*@__PURE__*/ new Vector3();
  36062. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36063. const _scale$1 = /*@__PURE__*/ new Vector3();
  36064. const _forward = /*@__PURE__*/ new Vector3();
  36065. const _up = /*@__PURE__*/ new Vector3();
  36066. /**
  36067. * The class represents a virtual listener of the all positional and non-positional audio effects
  36068. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36069. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36070. *
  36071. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36072. * camera represents the 3D transformation of the listener.
  36073. *
  36074. * @augments Object3D
  36075. */
  36076. class AudioListener extends Object3D {
  36077. /**
  36078. * Constructs a new audio listener.
  36079. */
  36080. constructor() {
  36081. super();
  36082. this.type = 'AudioListener';
  36083. /**
  36084. * The native audio context.
  36085. *
  36086. * @type {AudioContext}
  36087. * @readonly
  36088. */
  36089. this.context = AudioContext.getContext();
  36090. /**
  36091. * The gain node used for volume control.
  36092. *
  36093. * @type {GainNode}
  36094. * @readonly
  36095. */
  36096. this.gain = this.context.createGain();
  36097. this.gain.connect( this.context.destination );
  36098. /**
  36099. * An optional filter.
  36100. *
  36101. * Defined via {@link AudioListener#setFilter}.
  36102. *
  36103. * @type {?AudioNode}
  36104. * @default null
  36105. * @readonly
  36106. */
  36107. this.filter = null;
  36108. /**
  36109. * Time delta values required for `linearRampToValueAtTime()` usage.
  36110. *
  36111. * @type {number}
  36112. * @default 0
  36113. * @readonly
  36114. */
  36115. this.timeDelta = 0;
  36116. // private
  36117. this._clock = new Clock();
  36118. }
  36119. /**
  36120. * Returns the listener's input node.
  36121. *
  36122. * This method is used by other audio nodes to connect to this listener.
  36123. *
  36124. * @return {GainNode} The input node.
  36125. */
  36126. getInput() {
  36127. return this.gain;
  36128. }
  36129. /**
  36130. * Removes the current filter from this listener.
  36131. *
  36132. * @return {AudioListener} A reference to this listener.
  36133. */
  36134. removeFilter() {
  36135. if ( this.filter !== null ) {
  36136. this.gain.disconnect( this.filter );
  36137. this.filter.disconnect( this.context.destination );
  36138. this.gain.connect( this.context.destination );
  36139. this.filter = null;
  36140. }
  36141. return this;
  36142. }
  36143. /**
  36144. * Returns the current set filter.
  36145. *
  36146. * @return {?AudioNode} The filter.
  36147. */
  36148. getFilter() {
  36149. return this.filter;
  36150. }
  36151. /**
  36152. * Sets the given filter to this listener.
  36153. *
  36154. * @param {AudioNode} value - The filter to set.
  36155. * @return {AudioListener} A reference to this listener.
  36156. */
  36157. setFilter( value ) {
  36158. if ( this.filter !== null ) {
  36159. this.gain.disconnect( this.filter );
  36160. this.filter.disconnect( this.context.destination );
  36161. } else {
  36162. this.gain.disconnect( this.context.destination );
  36163. }
  36164. this.filter = value;
  36165. this.gain.connect( this.filter );
  36166. this.filter.connect( this.context.destination );
  36167. return this;
  36168. }
  36169. /**
  36170. * Returns the applications master volume.
  36171. *
  36172. * @return {number} The master volume.
  36173. */
  36174. getMasterVolume() {
  36175. return this.gain.gain.value;
  36176. }
  36177. /**
  36178. * Sets the applications master volume. This volume setting affects
  36179. * all audio nodes in the scene.
  36180. *
  36181. * @param {number} value - The master volume to set.
  36182. * @return {AudioListener} A reference to this listener.
  36183. */
  36184. setMasterVolume( value ) {
  36185. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36186. return this;
  36187. }
  36188. updateMatrixWorld( force ) {
  36189. super.updateMatrixWorld( force );
  36190. const listener = this.context.listener;
  36191. this.timeDelta = this._clock.getDelta();
  36192. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36193. // the initial forward and up directions must be orthogonal
  36194. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36195. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36196. if ( listener.positionX ) {
  36197. // code path for Chrome (see #14393)
  36198. const endTime = this.context.currentTime + this.timeDelta;
  36199. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36200. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36201. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36202. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36203. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36204. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36205. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36206. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36207. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36208. } else {
  36209. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36210. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36211. }
  36212. }
  36213. }
  36214. /**
  36215. * Represents a non-positional ( global ) audio object.
  36216. *
  36217. * This and related audio modules make use of the [Web Audio API]{@link https://www.w3.org/TR/webaudio-1.1/}.
  36218. *
  36219. * ```js
  36220. * // create an AudioListener and add it to the camera
  36221. * const listener = new THREE.AudioListener();
  36222. * camera.add( listener );
  36223. *
  36224. * // create a global audio source
  36225. * const sound = new THREE.Audio( listener );
  36226. *
  36227. * // load a sound and set it as the Audio object's buffer
  36228. * const audioLoader = new THREE.AudioLoader();
  36229. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36230. * sound.setBuffer( buffer );
  36231. * sound.setLoop( true );
  36232. * sound.setVolume( 0.5 );
  36233. * sound.play();
  36234. * });
  36235. * ```
  36236. *
  36237. * @augments Object3D
  36238. */
  36239. class Audio extends Object3D {
  36240. /**
  36241. * Constructs a new audio.
  36242. *
  36243. * @param {AudioListener} listener - The global audio listener.
  36244. */
  36245. constructor( listener ) {
  36246. super();
  36247. this.type = 'Audio';
  36248. /**
  36249. * The global audio listener.
  36250. *
  36251. * @type {AudioListener}
  36252. * @readonly
  36253. */
  36254. this.listener = listener;
  36255. /**
  36256. * The audio context.
  36257. *
  36258. * @type {AudioContext}
  36259. * @readonly
  36260. */
  36261. this.context = listener.context;
  36262. /**
  36263. * The gain node used for volume control.
  36264. *
  36265. * @type {GainNode}
  36266. * @readonly
  36267. */
  36268. this.gain = this.context.createGain();
  36269. this.gain.connect( listener.getInput() );
  36270. /**
  36271. * Whether to start playback automatically or not.
  36272. *
  36273. * @type {boolean}
  36274. * @default false
  36275. */
  36276. this.autoplay = false;
  36277. /**
  36278. * A reference to an audio buffer.
  36279. *
  36280. * Defined via {@link Audio#setBuffer}.
  36281. *
  36282. * @type {?AudioBuffer}
  36283. * @default null
  36284. * @readonly
  36285. */
  36286. this.buffer = null;
  36287. /**
  36288. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36289. * +/- 1200 is an octave.
  36290. *
  36291. * Defined via {@link Audio#setDetune}.
  36292. *
  36293. * @type {number}
  36294. * @default 0
  36295. * @readonly
  36296. */
  36297. this.detune = 0;
  36298. /**
  36299. * Whether the audio should loop or not.
  36300. *
  36301. * Defined via {@link Audio#setLoop}.
  36302. *
  36303. * @type {boolean}
  36304. * @default false
  36305. * @readonly
  36306. */
  36307. this.loop = false;
  36308. /**
  36309. * Defines where in the audio buffer the replay should
  36310. * start, in seconds.
  36311. *
  36312. * @type {number}
  36313. * @default 0
  36314. */
  36315. this.loopStart = 0;
  36316. /**
  36317. * Defines where in the audio buffer the replay should
  36318. * stop, in seconds.
  36319. *
  36320. * @type {number}
  36321. * @default 0
  36322. */
  36323. this.loopEnd = 0;
  36324. /**
  36325. * An offset to the time within the audio buffer the playback
  36326. * should begin, in seconds.
  36327. *
  36328. * @type {number}
  36329. * @default 0
  36330. */
  36331. this.offset = 0;
  36332. /**
  36333. * Overrides the default duration of the audio.
  36334. *
  36335. * @type {undefined|number}
  36336. * @default undefined
  36337. */
  36338. this.duration = undefined;
  36339. /**
  36340. * The playback speed.
  36341. *
  36342. * Defined via {@link Audio#setPlaybackRate}.
  36343. *
  36344. * @type {number}
  36345. * @readonly
  36346. * @default 1
  36347. */
  36348. this.playbackRate = 1;
  36349. /**
  36350. * Indicates whether the audio is playing or not.
  36351. *
  36352. * This flag will be automatically set when using {@link Audio#play},
  36353. * {@link Audio#pause}, {@link Audio#stop}.
  36354. *
  36355. * @type {boolean}
  36356. * @readonly
  36357. * @default false
  36358. */
  36359. this.isPlaying = false;
  36360. /**
  36361. * Indicates whether the audio playback can be controlled
  36362. * with method like {@link Audio#play} or {@link Audio#pause}.
  36363. *
  36364. * This flag will be automatically set when audio sources are
  36365. * defined.
  36366. *
  36367. * @type {boolean}
  36368. * @readonly
  36369. * @default true
  36370. */
  36371. this.hasPlaybackControl = true;
  36372. /**
  36373. * Holds a reference to the current audio source.
  36374. *
  36375. * The property is automatically by one of the `set*()` methods.
  36376. *
  36377. * @type {?AudioNode}
  36378. * @readonly
  36379. * @default null
  36380. */
  36381. this.source = null;
  36382. /**
  36383. * Defines the source type.
  36384. *
  36385. * The property is automatically by one of the `set*()` methods.
  36386. *
  36387. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36388. * @readonly
  36389. * @default 'empty'
  36390. */
  36391. this.sourceType = 'empty';
  36392. this._startedAt = 0;
  36393. this._progress = 0;
  36394. this._connected = false;
  36395. /**
  36396. * Can be used to apply a variety of low-order filters to create
  36397. * more complex sound effects e.g. via `BiquadFilterNode`.
  36398. *
  36399. * The property is automatically set by {@link Audio#setFilters}.
  36400. *
  36401. * @type {Array<AudioNode>}
  36402. * @readonly
  36403. */
  36404. this.filters = [];
  36405. }
  36406. /**
  36407. * Returns the output audio node.
  36408. *
  36409. * @return {GainNode} The output node.
  36410. */
  36411. getOutput() {
  36412. return this.gain;
  36413. }
  36414. /**
  36415. * Sets the given audio node as the source of this instance.
  36416. *
  36417. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36418. *
  36419. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36420. * @return {Audio} A reference to this instance.
  36421. */
  36422. setNodeSource( audioNode ) {
  36423. this.hasPlaybackControl = false;
  36424. this.sourceType = 'audioNode';
  36425. this.source = audioNode;
  36426. this.connect();
  36427. return this;
  36428. }
  36429. /**
  36430. * Sets the given media element as the source of this instance.
  36431. *
  36432. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36433. *
  36434. * @param {HTMLMediaElement} mediaElement - The media element.
  36435. * @return {Audio} A reference to this instance.
  36436. */
  36437. setMediaElementSource( mediaElement ) {
  36438. this.hasPlaybackControl = false;
  36439. this.sourceType = 'mediaNode';
  36440. this.source = this.context.createMediaElementSource( mediaElement );
  36441. this.connect();
  36442. return this;
  36443. }
  36444. /**
  36445. * Sets the given media stream as the source of this instance.
  36446. *
  36447. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36448. *
  36449. * @param {MediaStream} mediaStream - The media stream.
  36450. * @return {Audio} A reference to this instance.
  36451. */
  36452. setMediaStreamSource( mediaStream ) {
  36453. this.hasPlaybackControl = false;
  36454. this.sourceType = 'mediaStreamNode';
  36455. this.source = this.context.createMediaStreamSource( mediaStream );
  36456. this.connect();
  36457. return this;
  36458. }
  36459. /**
  36460. * Sets the given audio buffer as the source of this instance.
  36461. *
  36462. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36463. *
  36464. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36465. * @return {Audio} A reference to this instance.
  36466. */
  36467. setBuffer( audioBuffer ) {
  36468. this.buffer = audioBuffer;
  36469. this.sourceType = 'buffer';
  36470. if ( this.autoplay ) this.play();
  36471. return this;
  36472. }
  36473. /**
  36474. * Starts the playback of the audio.
  36475. *
  36476. * Can only be used with compatible audio sources that allow playback control.
  36477. *
  36478. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36479. * @return {Audio|undefined} A reference to this instance.
  36480. */
  36481. play( delay = 0 ) {
  36482. if ( this.isPlaying === true ) {
  36483. warn( 'Audio: Audio is already playing.' );
  36484. return;
  36485. }
  36486. if ( this.hasPlaybackControl === false ) {
  36487. warn( 'Audio: this Audio has no playback control.' );
  36488. return;
  36489. }
  36490. this._startedAt = this.context.currentTime + delay;
  36491. const source = this.context.createBufferSource();
  36492. source.buffer = this.buffer;
  36493. source.loop = this.loop;
  36494. source.loopStart = this.loopStart;
  36495. source.loopEnd = this.loopEnd;
  36496. source.onended = this.onEnded.bind( this );
  36497. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36498. this.isPlaying = true;
  36499. this.source = source;
  36500. this.setDetune( this.detune );
  36501. this.setPlaybackRate( this.playbackRate );
  36502. return this.connect();
  36503. }
  36504. /**
  36505. * Pauses the playback of the audio.
  36506. *
  36507. * Can only be used with compatible audio sources that allow playback control.
  36508. *
  36509. * @return {Audio|undefined} A reference to this instance.
  36510. */
  36511. pause() {
  36512. if ( this.hasPlaybackControl === false ) {
  36513. warn( 'Audio: this Audio has no playback control.' );
  36514. return;
  36515. }
  36516. if ( this.isPlaying === true ) {
  36517. // update current progress
  36518. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36519. if ( this.loop === true ) {
  36520. // ensure _progress does not exceed duration with looped audios
  36521. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36522. }
  36523. this.source.stop();
  36524. this.source.onended = null;
  36525. this.isPlaying = false;
  36526. }
  36527. return this;
  36528. }
  36529. /**
  36530. * Stops the playback of the audio.
  36531. *
  36532. * Can only be used with compatible audio sources that allow playback control.
  36533. *
  36534. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36535. * @return {Audio|undefined} A reference to this instance.
  36536. */
  36537. stop( delay = 0 ) {
  36538. if ( this.hasPlaybackControl === false ) {
  36539. warn( 'Audio: this Audio has no playback control.' );
  36540. return;
  36541. }
  36542. this._progress = 0;
  36543. if ( this.source !== null ) {
  36544. this.source.stop( this.context.currentTime + delay );
  36545. this.source.onended = null;
  36546. }
  36547. this.isPlaying = false;
  36548. return this;
  36549. }
  36550. /**
  36551. * Connects to the audio source. This is used internally on
  36552. * initialisation and when setting / removing filters.
  36553. *
  36554. * @return {Audio} A reference to this instance.
  36555. */
  36556. connect() {
  36557. if ( this.filters.length > 0 ) {
  36558. this.source.connect( this.filters[ 0 ] );
  36559. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36560. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36561. }
  36562. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36563. } else {
  36564. this.source.connect( this.getOutput() );
  36565. }
  36566. this._connected = true;
  36567. return this;
  36568. }
  36569. /**
  36570. * Disconnects to the audio source. This is used internally on
  36571. * initialisation and when setting / removing filters.
  36572. *
  36573. * @return {Audio|undefined} A reference to this instance.
  36574. */
  36575. disconnect() {
  36576. if ( this._connected === false ) {
  36577. return;
  36578. }
  36579. if ( this.filters.length > 0 ) {
  36580. this.source.disconnect( this.filters[ 0 ] );
  36581. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36582. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36583. }
  36584. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36585. } else {
  36586. this.source.disconnect( this.getOutput() );
  36587. }
  36588. this._connected = false;
  36589. return this;
  36590. }
  36591. /**
  36592. * Returns the current set filters.
  36593. *
  36594. * @return {Array<AudioNode>} The list of filters.
  36595. */
  36596. getFilters() {
  36597. return this.filters;
  36598. }
  36599. /**
  36600. * Sets an array of filters and connects them with the audio source.
  36601. *
  36602. * @param {Array<AudioNode>} [value] - A list of filters.
  36603. * @return {Audio} A reference to this instance.
  36604. */
  36605. setFilters( value ) {
  36606. if ( ! value ) value = [];
  36607. if ( this._connected === true ) {
  36608. this.disconnect();
  36609. this.filters = value.slice();
  36610. this.connect();
  36611. } else {
  36612. this.filters = value.slice();
  36613. }
  36614. return this;
  36615. }
  36616. /**
  36617. * Defines the detuning of oscillation in cents.
  36618. *
  36619. * @param {number} value - The detuning of oscillation in cents.
  36620. * @return {Audio} A reference to this instance.
  36621. */
  36622. setDetune( value ) {
  36623. this.detune = value;
  36624. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36625. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36626. }
  36627. return this;
  36628. }
  36629. /**
  36630. * Returns the detuning of oscillation in cents.
  36631. *
  36632. * @return {number} The detuning of oscillation in cents.
  36633. */
  36634. getDetune() {
  36635. return this.detune;
  36636. }
  36637. /**
  36638. * Returns the first filter in the list of filters.
  36639. *
  36640. * @return {AudioNode|undefined} The first filter in the list of filters.
  36641. */
  36642. getFilter() {
  36643. return this.getFilters()[ 0 ];
  36644. }
  36645. /**
  36646. * Applies a single filter node to the audio.
  36647. *
  36648. * @param {AudioNode} [filter] - The filter to set.
  36649. * @return {Audio} A reference to this instance.
  36650. */
  36651. setFilter( filter ) {
  36652. return this.setFilters( filter ? [ filter ] : [] );
  36653. }
  36654. /**
  36655. * Sets the playback rate.
  36656. *
  36657. * Can only be used with compatible audio sources that allow playback control.
  36658. *
  36659. * @param {number} [value] - The playback rate to set.
  36660. * @return {Audio|undefined} A reference to this instance.
  36661. */
  36662. setPlaybackRate( value ) {
  36663. if ( this.hasPlaybackControl === false ) {
  36664. warn( 'Audio: this Audio has no playback control.' );
  36665. return;
  36666. }
  36667. this.playbackRate = value;
  36668. if ( this.isPlaying === true ) {
  36669. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36670. }
  36671. return this;
  36672. }
  36673. /**
  36674. * Returns the current playback rate.
  36675. * @return {number} The playback rate.
  36676. */
  36677. getPlaybackRate() {
  36678. return this.playbackRate;
  36679. }
  36680. /**
  36681. * Automatically called when playback finished.
  36682. */
  36683. onEnded() {
  36684. this.isPlaying = false;
  36685. this._progress = 0;
  36686. }
  36687. /**
  36688. * Returns the loop flag.
  36689. *
  36690. * Can only be used with compatible audio sources that allow playback control.
  36691. *
  36692. * @return {boolean} Whether the audio should loop or not.
  36693. */
  36694. getLoop() {
  36695. if ( this.hasPlaybackControl === false ) {
  36696. warn( 'Audio: this Audio has no playback control.' );
  36697. return false;
  36698. }
  36699. return this.loop;
  36700. }
  36701. /**
  36702. * Sets the loop flag.
  36703. *
  36704. * Can only be used with compatible audio sources that allow playback control.
  36705. *
  36706. * @param {boolean} value - Whether the audio should loop or not.
  36707. * @return {Audio|undefined} A reference to this instance.
  36708. */
  36709. setLoop( value ) {
  36710. if ( this.hasPlaybackControl === false ) {
  36711. warn( 'Audio: this Audio has no playback control.' );
  36712. return;
  36713. }
  36714. this.loop = value;
  36715. if ( this.isPlaying === true ) {
  36716. this.source.loop = this.loop;
  36717. }
  36718. return this;
  36719. }
  36720. /**
  36721. * Sets the loop start value which defines where in the audio buffer the replay should
  36722. * start, in seconds.
  36723. *
  36724. * @param {number} value - The loop start value.
  36725. * @return {Audio} A reference to this instance.
  36726. */
  36727. setLoopStart( value ) {
  36728. this.loopStart = value;
  36729. return this;
  36730. }
  36731. /**
  36732. * Sets the loop end value which defines where in the audio buffer the replay should
  36733. * stop, in seconds.
  36734. *
  36735. * @param {number} value - The loop end value.
  36736. * @return {Audio} A reference to this instance.
  36737. */
  36738. setLoopEnd( value ) {
  36739. this.loopEnd = value;
  36740. return this;
  36741. }
  36742. /**
  36743. * Returns the volume.
  36744. *
  36745. * @return {number} The volume.
  36746. */
  36747. getVolume() {
  36748. return this.gain.gain.value;
  36749. }
  36750. /**
  36751. * Sets the volume.
  36752. *
  36753. * @param {number} value - The volume to set.
  36754. * @return {Audio} A reference to this instance.
  36755. */
  36756. setVolume( value ) {
  36757. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36758. return this;
  36759. }
  36760. copy( source, recursive ) {
  36761. super.copy( source, recursive );
  36762. if ( source.sourceType !== 'buffer' ) {
  36763. warn( 'Audio: Audio source type cannot be copied.' );
  36764. return this;
  36765. }
  36766. this.autoplay = source.autoplay;
  36767. this.buffer = source.buffer;
  36768. this.detune = source.detune;
  36769. this.loop = source.loop;
  36770. this.loopStart = source.loopStart;
  36771. this.loopEnd = source.loopEnd;
  36772. this.offset = source.offset;
  36773. this.duration = source.duration;
  36774. this.playbackRate = source.playbackRate;
  36775. this.hasPlaybackControl = source.hasPlaybackControl;
  36776. this.sourceType = source.sourceType;
  36777. this.filters = source.filters.slice();
  36778. return this;
  36779. }
  36780. clone( recursive ) {
  36781. return new this.constructor( this.listener ).copy( this, recursive );
  36782. }
  36783. }
  36784. const _position = /*@__PURE__*/ new Vector3();
  36785. const _quaternion = /*@__PURE__*/ new Quaternion();
  36786. const _scale = /*@__PURE__*/ new Vector3();
  36787. const _orientation = /*@__PURE__*/ new Vector3();
  36788. /**
  36789. * Represents a positional audio object.
  36790. *
  36791. * ```js
  36792. * // create an AudioListener and add it to the camera
  36793. * const listener = new THREE.AudioListener();
  36794. * camera.add( listener );
  36795. *
  36796. * // create the PositionalAudio object (passing in the listener)
  36797. * const sound = new THREE.PositionalAudio( listener );
  36798. *
  36799. * // load a sound and set it as the PositionalAudio object's buffer
  36800. * const audioLoader = new THREE.AudioLoader();
  36801. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36802. * sound.setBuffer( buffer );
  36803. * sound.setRefDistance( 20 );
  36804. * sound.play();
  36805. * });
  36806. *
  36807. * // create an object for the sound to play from
  36808. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36809. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36810. * const mesh = new THREE.Mesh( sphere, material );
  36811. * scene.add( mesh );
  36812. *
  36813. * // finally add the sound to the mesh
  36814. * mesh.add( sound );
  36815. *
  36816. * @augments Audio
  36817. */
  36818. class PositionalAudio extends Audio {
  36819. /**
  36820. * Constructs a positional audio.
  36821. *
  36822. * @param {AudioListener} listener - The global audio listener.
  36823. */
  36824. constructor( listener ) {
  36825. super( listener );
  36826. /**
  36827. * The panner node represents the location, direction, and behavior of an audio
  36828. * source in 3D space.
  36829. *
  36830. * @type {PannerNode}
  36831. * @readonly
  36832. */
  36833. this.panner = this.context.createPanner();
  36834. this.panner.panningModel = 'HRTF';
  36835. this.panner.connect( this.gain );
  36836. }
  36837. connect() {
  36838. super.connect();
  36839. this.panner.connect( this.gain );
  36840. return this;
  36841. }
  36842. disconnect() {
  36843. super.disconnect();
  36844. this.panner.disconnect( this.gain );
  36845. return this;
  36846. }
  36847. getOutput() {
  36848. return this.panner;
  36849. }
  36850. /**
  36851. * Returns the current reference distance.
  36852. *
  36853. * @return {number} The reference distance.
  36854. */
  36855. getRefDistance() {
  36856. return this.panner.refDistance;
  36857. }
  36858. /**
  36859. * Defines the reference distance for reducing volume as the audio source moves
  36860. * further from the listener – i.e. the distance at which the volume reduction
  36861. * starts taking effect.
  36862. *
  36863. * @param {number} value - The reference distance to set.
  36864. * @return {PositionalAudio} A reference to this instance.
  36865. */
  36866. setRefDistance( value ) {
  36867. this.panner.refDistance = value;
  36868. return this;
  36869. }
  36870. /**
  36871. * Returns the current rolloff factor.
  36872. *
  36873. * @return {number} The rolloff factor.
  36874. */
  36875. getRolloffFactor() {
  36876. return this.panner.rolloffFactor;
  36877. }
  36878. /**
  36879. * Defines how quickly the volume is reduced as the source moves away from the listener.
  36880. *
  36881. * @param {number} value - The rolloff factor.
  36882. * @return {PositionalAudio} A reference to this instance.
  36883. */
  36884. setRolloffFactor( value ) {
  36885. this.panner.rolloffFactor = value;
  36886. return this;
  36887. }
  36888. /**
  36889. * Returns the current distance model.
  36890. *
  36891. * @return {('linear'|'inverse'|'exponential')} The distance model.
  36892. */
  36893. getDistanceModel() {
  36894. return this.panner.distanceModel;
  36895. }
  36896. /**
  36897. * Defines which algorithm to use to reduce the volume of the audio source
  36898. * as it moves away from the listener.
  36899. *
  36900. * Read [the spec]{@link https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype}
  36901. * for more details.
  36902. *
  36903. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  36904. * @return {PositionalAudio} A reference to this instance.
  36905. */
  36906. setDistanceModel( value ) {
  36907. this.panner.distanceModel = value;
  36908. return this;
  36909. }
  36910. /**
  36911. * Returns the current max distance.
  36912. *
  36913. * @return {number} The max distance.
  36914. */
  36915. getMaxDistance() {
  36916. return this.panner.maxDistance;
  36917. }
  36918. /**
  36919. * Defines the maximum distance between the audio source and the listener,
  36920. * after which the volume is not reduced any further.
  36921. *
  36922. * This value is used only by the `linear` distance model.
  36923. *
  36924. * @param {number} value - The max distance.
  36925. * @return {PositionalAudio} A reference to this instance.
  36926. */
  36927. setMaxDistance( value ) {
  36928. this.panner.maxDistance = value;
  36929. return this;
  36930. }
  36931. /**
  36932. * Sets the directional cone in which the audio can be listened.
  36933. *
  36934. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  36935. * @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.
  36936. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  36937. * @return {PositionalAudio} A reference to this instance.
  36938. */
  36939. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  36940. this.panner.coneInnerAngle = coneInnerAngle;
  36941. this.panner.coneOuterAngle = coneOuterAngle;
  36942. this.panner.coneOuterGain = coneOuterGain;
  36943. return this;
  36944. }
  36945. updateMatrixWorld( force ) {
  36946. super.updateMatrixWorld( force );
  36947. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  36948. this.matrixWorld.decompose( _position, _quaternion, _scale );
  36949. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  36950. const panner = this.panner;
  36951. if ( panner.positionX ) {
  36952. // code path for Chrome and Firefox (see #14393)
  36953. const endTime = this.context.currentTime + this.listener.timeDelta;
  36954. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  36955. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  36956. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  36957. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  36958. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  36959. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  36960. } else {
  36961. panner.setPosition( _position.x, _position.y, _position.z );
  36962. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  36963. }
  36964. }
  36965. }
  36966. /**
  36967. * This class can be used to analyse audio data.
  36968. *
  36969. * ```js
  36970. * // create an AudioListener and add it to the camera
  36971. * const listener = new THREE.AudioListener();
  36972. * camera.add( listener );
  36973. *
  36974. * // create an Audio source
  36975. * const sound = new THREE.Audio( listener );
  36976. *
  36977. * // load a sound and set it as the Audio object's buffer
  36978. * const audioLoader = new THREE.AudioLoader();
  36979. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36980. * sound.setBuffer( buffer );
  36981. * sound.setLoop(true);
  36982. * sound.setVolume(0.5);
  36983. * sound.play();
  36984. * });
  36985. *
  36986. * // create an AudioAnalyser, passing in the sound and desired fftSize
  36987. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  36988. *
  36989. * // get the average frequency of the sound
  36990. * const data = analyser.getAverageFrequency();
  36991. * ```
  36992. */
  36993. class AudioAnalyser {
  36994. /**
  36995. * Constructs a new audio analyzer.
  36996. *
  36997. * @param {Audio} audio - The audio to analyze.
  36998. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  36999. */
  37000. constructor( audio, fftSize = 2048 ) {
  37001. /**
  37002. * The global audio listener.
  37003. *
  37004. * @type {AnalyserNode}
  37005. */
  37006. this.analyser = audio.context.createAnalyser();
  37007. this.analyser.fftSize = fftSize;
  37008. /**
  37009. * Holds the analyzed data.
  37010. *
  37011. * @type {Uint8Array}
  37012. */
  37013. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37014. audio.getOutput().connect( this.analyser );
  37015. }
  37016. /**
  37017. * Returns an array with frequency data of the audio.
  37018. *
  37019. * Each item in the array represents the decibel value for a specific frequency.
  37020. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37021. * For example, for 48000 sample rate, the last item of the array will represent
  37022. * the decibel value for 24000 Hz.
  37023. *
  37024. * @return {Uint8Array} The frequency data.
  37025. */
  37026. getFrequencyData() {
  37027. this.analyser.getByteFrequencyData( this.data );
  37028. return this.data;
  37029. }
  37030. /**
  37031. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37032. *
  37033. * @return {number} The average frequency.
  37034. */
  37035. getAverageFrequency() {
  37036. let value = 0;
  37037. const data = this.getFrequencyData();
  37038. for ( let i = 0; i < data.length; i ++ ) {
  37039. value += data[ i ];
  37040. }
  37041. return value / data.length;
  37042. }
  37043. }
  37044. /**
  37045. * Buffered scene graph property that allows weighted accumulation; used internally.
  37046. */
  37047. class PropertyMixer {
  37048. /**
  37049. * Constructs a new property mixer.
  37050. *
  37051. * @param {PropertyBinding} binding - The property binding.
  37052. * @param {string} typeName - The keyframe track type name.
  37053. * @param {number} valueSize - The keyframe track value size.
  37054. */
  37055. constructor( binding, typeName, valueSize ) {
  37056. /**
  37057. * The property binding.
  37058. *
  37059. * @type {PropertyBinding}
  37060. */
  37061. this.binding = binding;
  37062. /**
  37063. * The keyframe track value size.
  37064. *
  37065. * @type {number}
  37066. */
  37067. this.valueSize = valueSize;
  37068. let mixFunction,
  37069. mixFunctionAdditive,
  37070. setIdentity;
  37071. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37072. //
  37073. // interpolators can use .buffer as their .result
  37074. // the data then goes to 'incoming'
  37075. //
  37076. // 'accu0' and 'accu1' are used frame-interleaved for
  37077. // the cumulative result and are compared to detect
  37078. // changes
  37079. //
  37080. // 'orig' stores the original state of the property
  37081. //
  37082. // 'add' is used for additive cumulative results
  37083. //
  37084. // 'work' is optional and is only present for quaternion types. It is used
  37085. // to store intermediate quaternion multiplication results
  37086. switch ( typeName ) {
  37087. case 'quaternion':
  37088. mixFunction = this._slerp;
  37089. mixFunctionAdditive = this._slerpAdditive;
  37090. setIdentity = this._setAdditiveIdentityQuaternion;
  37091. this.buffer = new Float64Array( valueSize * 6 );
  37092. this._workIndex = 5;
  37093. break;
  37094. case 'string':
  37095. case 'bool':
  37096. mixFunction = this._select;
  37097. // Use the regular mix function and for additive on these types,
  37098. // additive is not relevant for non-numeric types
  37099. mixFunctionAdditive = this._select;
  37100. setIdentity = this._setAdditiveIdentityOther;
  37101. this.buffer = new Array( valueSize * 5 );
  37102. break;
  37103. default:
  37104. mixFunction = this._lerp;
  37105. mixFunctionAdditive = this._lerpAdditive;
  37106. setIdentity = this._setAdditiveIdentityNumeric;
  37107. this.buffer = new Float64Array( valueSize * 5 );
  37108. }
  37109. this._mixBufferRegion = mixFunction;
  37110. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37111. this._setIdentity = setIdentity;
  37112. this._origIndex = 3;
  37113. this._addIndex = 4;
  37114. /**
  37115. * TODO
  37116. *
  37117. * @type {number}
  37118. * @default 0
  37119. */
  37120. this.cumulativeWeight = 0;
  37121. /**
  37122. * TODO
  37123. *
  37124. * @type {number}
  37125. * @default 0
  37126. */
  37127. this.cumulativeWeightAdditive = 0;
  37128. /**
  37129. * TODO
  37130. *
  37131. * @type {number}
  37132. * @default 0
  37133. */
  37134. this.useCount = 0;
  37135. /**
  37136. * TODO
  37137. *
  37138. * @type {number}
  37139. * @default 0
  37140. */
  37141. this.referenceCount = 0;
  37142. }
  37143. /**
  37144. * Accumulates data in the `incoming` region into `accu<i>`.
  37145. *
  37146. * @param {number} accuIndex - The accumulation index.
  37147. * @param {number} weight - The weight.
  37148. */
  37149. accumulate( accuIndex, weight ) {
  37150. // note: happily accumulating nothing when weight = 0, the caller knows
  37151. // the weight and shouldn't have made the call in the first place
  37152. const buffer = this.buffer,
  37153. stride = this.valueSize,
  37154. offset = accuIndex * stride + stride;
  37155. let currentWeight = this.cumulativeWeight;
  37156. if ( currentWeight === 0 ) {
  37157. // accuN := incoming * weight
  37158. for ( let i = 0; i !== stride; ++ i ) {
  37159. buffer[ offset + i ] = buffer[ i ];
  37160. }
  37161. currentWeight = weight;
  37162. } else {
  37163. // accuN := accuN + incoming * weight
  37164. currentWeight += weight;
  37165. const mix = weight / currentWeight;
  37166. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37167. }
  37168. this.cumulativeWeight = currentWeight;
  37169. }
  37170. /**
  37171. * Accumulates data in the `incoming` region into `add`.
  37172. *
  37173. * @param {number} weight - The weight.
  37174. */
  37175. accumulateAdditive( weight ) {
  37176. const buffer = this.buffer,
  37177. stride = this.valueSize,
  37178. offset = stride * this._addIndex;
  37179. if ( this.cumulativeWeightAdditive === 0 ) {
  37180. // add = identity
  37181. this._setIdentity();
  37182. }
  37183. // add := add + incoming * weight
  37184. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37185. this.cumulativeWeightAdditive += weight;
  37186. }
  37187. /**
  37188. * Applies the state of `accu<i>` to the binding when accus differ.
  37189. *
  37190. * @param {number} accuIndex - The accumulation index.
  37191. */
  37192. apply( accuIndex ) {
  37193. const stride = this.valueSize,
  37194. buffer = this.buffer,
  37195. offset = accuIndex * stride + stride,
  37196. weight = this.cumulativeWeight,
  37197. weightAdditive = this.cumulativeWeightAdditive,
  37198. binding = this.binding;
  37199. this.cumulativeWeight = 0;
  37200. this.cumulativeWeightAdditive = 0;
  37201. if ( weight < 1 ) {
  37202. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37203. const originalValueOffset = stride * this._origIndex;
  37204. this._mixBufferRegion(
  37205. buffer, offset, originalValueOffset, 1 - weight, stride );
  37206. }
  37207. if ( weightAdditive > 0 ) {
  37208. // accuN := accuN + additive accuN
  37209. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37210. }
  37211. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37212. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37213. // value has changed -> update scene graph
  37214. binding.setValue( buffer, offset );
  37215. break;
  37216. }
  37217. }
  37218. }
  37219. /**
  37220. * Remembers the state of the bound property and copy it to both accus.
  37221. */
  37222. saveOriginalState() {
  37223. const binding = this.binding;
  37224. const buffer = this.buffer,
  37225. stride = this.valueSize,
  37226. originalValueOffset = stride * this._origIndex;
  37227. binding.getValue( buffer, originalValueOffset );
  37228. // accu[0..1] := orig -- initially detect changes against the original
  37229. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37230. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37231. }
  37232. // Add to identity for additive
  37233. this._setIdentity();
  37234. this.cumulativeWeight = 0;
  37235. this.cumulativeWeightAdditive = 0;
  37236. }
  37237. /**
  37238. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37239. */
  37240. restoreOriginalState() {
  37241. const originalValueOffset = this.valueSize * 3;
  37242. this.binding.setValue( this.buffer, originalValueOffset );
  37243. }
  37244. // internals
  37245. _setAdditiveIdentityNumeric() {
  37246. const startIndex = this._addIndex * this.valueSize;
  37247. const endIndex = startIndex + this.valueSize;
  37248. for ( let i = startIndex; i < endIndex; i ++ ) {
  37249. this.buffer[ i ] = 0;
  37250. }
  37251. }
  37252. _setAdditiveIdentityQuaternion() {
  37253. this._setAdditiveIdentityNumeric();
  37254. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37255. }
  37256. _setAdditiveIdentityOther() {
  37257. const startIndex = this._origIndex * this.valueSize;
  37258. const targetIndex = this._addIndex * this.valueSize;
  37259. for ( let i = 0; i < this.valueSize; i ++ ) {
  37260. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37261. }
  37262. }
  37263. // mix functions
  37264. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37265. if ( t >= 0.5 ) {
  37266. for ( let i = 0; i !== stride; ++ i ) {
  37267. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37268. }
  37269. }
  37270. }
  37271. _slerp( buffer, dstOffset, srcOffset, t ) {
  37272. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37273. }
  37274. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37275. const workOffset = this._workIndex * stride;
  37276. // Store result in intermediate buffer offset
  37277. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37278. // Slerp to the intermediate result
  37279. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37280. }
  37281. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37282. const s = 1 - t;
  37283. for ( let i = 0; i !== stride; ++ i ) {
  37284. const j = dstOffset + i;
  37285. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37286. }
  37287. }
  37288. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37289. for ( let i = 0; i !== stride; ++ i ) {
  37290. const j = dstOffset + i;
  37291. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37292. }
  37293. }
  37294. }
  37295. // Characters [].:/ are reserved for track binding syntax.
  37296. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37297. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37298. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37299. // only latin characters, and the unicode \p{L} is not yet supported. So
  37300. // instead, we exclude reserved characters and match everything else.
  37301. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37302. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37303. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37304. // be matched to parse the rest of the track name.
  37305. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37306. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37307. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37308. // Object on target node, and accessor. May not contain reserved
  37309. // characters. Accessor may contain any character except closing bracket.
  37310. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37311. // Property and accessor. May not contain reserved characters. Accessor may
  37312. // contain any non-bracket characters.
  37313. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37314. const _trackRe = new RegExp( ''
  37315. + '^'
  37316. + _directoryRe
  37317. + _nodeRe
  37318. + _objectRe
  37319. + _propertyRe
  37320. + '$'
  37321. );
  37322. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37323. class Composite {
  37324. constructor( targetGroup, path, optionalParsedPath ) {
  37325. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37326. this._targetGroup = targetGroup;
  37327. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37328. }
  37329. getValue( array, offset ) {
  37330. this.bind(); // bind all binding
  37331. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37332. binding = this._bindings[ firstValidIndex ];
  37333. // and only call .getValue on the first
  37334. if ( binding !== undefined ) binding.getValue( array, offset );
  37335. }
  37336. setValue( array, offset ) {
  37337. const bindings = this._bindings;
  37338. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37339. bindings[ i ].setValue( array, offset );
  37340. }
  37341. }
  37342. bind() {
  37343. const bindings = this._bindings;
  37344. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37345. bindings[ i ].bind();
  37346. }
  37347. }
  37348. unbind() {
  37349. const bindings = this._bindings;
  37350. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37351. bindings[ i ].unbind();
  37352. }
  37353. }
  37354. }
  37355. // Note: This class uses a State pattern on a per-method basis:
  37356. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37357. // prototype version of these methods with one that represents
  37358. // the bound state. When the property is not found, the methods
  37359. // become no-ops.
  37360. /**
  37361. * This holds a reference to a real property in the scene graph; used internally.
  37362. */
  37363. class PropertyBinding {
  37364. /**
  37365. * Constructs a new property binding.
  37366. *
  37367. * @param {Object} rootNode - The root node.
  37368. * @param {string} path - The path.
  37369. * @param {?Object} [parsedPath] - The parsed path.
  37370. */
  37371. constructor( rootNode, path, parsedPath ) {
  37372. /**
  37373. * The object path to the animated property.
  37374. *
  37375. * @type {string}
  37376. */
  37377. this.path = path;
  37378. /**
  37379. * An object holding information about the path.
  37380. *
  37381. * @type {Object}
  37382. */
  37383. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37384. /**
  37385. * The object owns the animated property.
  37386. *
  37387. * @type {?Object}
  37388. */
  37389. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37390. /**
  37391. * The root node.
  37392. *
  37393. * @type {Object3D|Skeleton}
  37394. */
  37395. this.rootNode = rootNode;
  37396. // initial state of these methods that calls 'bind'
  37397. this.getValue = this._getValue_unbound;
  37398. this.setValue = this._setValue_unbound;
  37399. }
  37400. /**
  37401. * Factory method for creating a property binding from the given parameters.
  37402. *
  37403. * @static
  37404. * @param {Object} root - The root node.
  37405. * @param {string} path - The path.
  37406. * @param {?Object} [parsedPath] - The parsed path.
  37407. * @return {PropertyBinding|Composite} The created property binding or composite.
  37408. */
  37409. static create( root, path, parsedPath ) {
  37410. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37411. return new PropertyBinding( root, path, parsedPath );
  37412. } else {
  37413. return new PropertyBinding.Composite( root, path, parsedPath );
  37414. }
  37415. }
  37416. /**
  37417. * Replaces spaces with underscores and removes unsupported characters from
  37418. * node names, to ensure compatibility with parseTrackName().
  37419. *
  37420. * @param {string} name - Node name to be sanitized.
  37421. * @return {string} The sanitized node name.
  37422. */
  37423. static sanitizeNodeName( name ) {
  37424. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37425. }
  37426. /**
  37427. * Parses the given track name (an object path to an animated property) and
  37428. * returns an object with information about the path. Matches strings in the following forms:
  37429. *
  37430. * - nodeName.property
  37431. * - nodeName.property[accessor]
  37432. * - nodeName.material.property[accessor]
  37433. * - uuid.property[accessor]
  37434. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37435. * - parentName/nodeName.property
  37436. * - parentName/parentName/nodeName.property[index]
  37437. * - .bone[Armature.DEF_cog].position
  37438. * - scene:helium_balloon_model:helium_balloon_model.position
  37439. *
  37440. * @static
  37441. * @param {string} trackName - The track name to parse.
  37442. * @return {Object} The parsed track name as an object.
  37443. */
  37444. static parseTrackName( trackName ) {
  37445. const matches = _trackRe.exec( trackName );
  37446. if ( matches === null ) {
  37447. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37448. }
  37449. const results = {
  37450. // directoryName: matches[ 1 ], // (tschw) currently unused
  37451. nodeName: matches[ 2 ],
  37452. objectName: matches[ 3 ],
  37453. objectIndex: matches[ 4 ],
  37454. propertyName: matches[ 5 ], // required
  37455. propertyIndex: matches[ 6 ]
  37456. };
  37457. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37458. if ( lastDot !== undefined && lastDot !== -1 ) {
  37459. const objectName = results.nodeName.substring( lastDot + 1 );
  37460. // Object names must be checked against an allowlist. Otherwise, there
  37461. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37462. // 'bar' could be the objectName, or part of a nodeName (which can
  37463. // include '.' characters).
  37464. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37465. results.nodeName = results.nodeName.substring( 0, lastDot );
  37466. results.objectName = objectName;
  37467. }
  37468. }
  37469. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37470. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37471. }
  37472. return results;
  37473. }
  37474. /**
  37475. * Searches for a node in the hierarchy of the given root object by the given
  37476. * node name.
  37477. *
  37478. * @static
  37479. * @param {Object} root - The root object.
  37480. * @param {string|number} nodeName - The name of the node.
  37481. * @return {?Object} The found node. Returns `null` if no object was found.
  37482. */
  37483. static findNode( root, nodeName ) {
  37484. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37485. return root;
  37486. }
  37487. // search into skeleton bones.
  37488. if ( root.skeleton ) {
  37489. const bone = root.skeleton.getBoneByName( nodeName );
  37490. if ( bone !== undefined ) {
  37491. return bone;
  37492. }
  37493. }
  37494. // search into node subtree.
  37495. if ( root.children ) {
  37496. const searchNodeSubtree = function ( children ) {
  37497. for ( let i = 0; i < children.length; i ++ ) {
  37498. const childNode = children[ i ];
  37499. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37500. return childNode;
  37501. }
  37502. const result = searchNodeSubtree( childNode.children );
  37503. if ( result ) return result;
  37504. }
  37505. return null;
  37506. };
  37507. const subTreeNode = searchNodeSubtree( root.children );
  37508. if ( subTreeNode ) {
  37509. return subTreeNode;
  37510. }
  37511. }
  37512. return null;
  37513. }
  37514. // these are used to "bind" a nonexistent property
  37515. _getValue_unavailable() {}
  37516. _setValue_unavailable() {}
  37517. // Getters
  37518. _getValue_direct( buffer, offset ) {
  37519. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37520. }
  37521. _getValue_array( buffer, offset ) {
  37522. const source = this.resolvedProperty;
  37523. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37524. buffer[ offset ++ ] = source[ i ];
  37525. }
  37526. }
  37527. _getValue_arrayElement( buffer, offset ) {
  37528. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37529. }
  37530. _getValue_toArray( buffer, offset ) {
  37531. this.resolvedProperty.toArray( buffer, offset );
  37532. }
  37533. // Direct
  37534. _setValue_direct( buffer, offset ) {
  37535. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37536. }
  37537. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37538. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37539. this.targetObject.needsUpdate = true;
  37540. }
  37541. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37542. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37543. this.targetObject.matrixWorldNeedsUpdate = true;
  37544. }
  37545. // EntireArray
  37546. _setValue_array( buffer, offset ) {
  37547. const dest = this.resolvedProperty;
  37548. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37549. dest[ i ] = buffer[ offset ++ ];
  37550. }
  37551. }
  37552. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37553. const dest = this.resolvedProperty;
  37554. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37555. dest[ i ] = buffer[ offset ++ ];
  37556. }
  37557. this.targetObject.needsUpdate = true;
  37558. }
  37559. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37560. const dest = this.resolvedProperty;
  37561. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37562. dest[ i ] = buffer[ offset ++ ];
  37563. }
  37564. this.targetObject.matrixWorldNeedsUpdate = true;
  37565. }
  37566. // ArrayElement
  37567. _setValue_arrayElement( buffer, offset ) {
  37568. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37569. }
  37570. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37571. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37572. this.targetObject.needsUpdate = true;
  37573. }
  37574. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37575. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37576. this.targetObject.matrixWorldNeedsUpdate = true;
  37577. }
  37578. // HasToFromArray
  37579. _setValue_fromArray( buffer, offset ) {
  37580. this.resolvedProperty.fromArray( buffer, offset );
  37581. }
  37582. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37583. this.resolvedProperty.fromArray( buffer, offset );
  37584. this.targetObject.needsUpdate = true;
  37585. }
  37586. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37587. this.resolvedProperty.fromArray( buffer, offset );
  37588. this.targetObject.matrixWorldNeedsUpdate = true;
  37589. }
  37590. _getValue_unbound( targetArray, offset ) {
  37591. this.bind();
  37592. this.getValue( targetArray, offset );
  37593. }
  37594. _setValue_unbound( sourceArray, offset ) {
  37595. this.bind();
  37596. this.setValue( sourceArray, offset );
  37597. }
  37598. /**
  37599. * Creates a getter / setter pair for the property tracked by this binding.
  37600. */
  37601. bind() {
  37602. let targetObject = this.node;
  37603. const parsedPath = this.parsedPath;
  37604. const objectName = parsedPath.objectName;
  37605. const propertyName = parsedPath.propertyName;
  37606. let propertyIndex = parsedPath.propertyIndex;
  37607. if ( ! targetObject ) {
  37608. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37609. this.node = targetObject;
  37610. }
  37611. // set fail state so we can just 'return' on error
  37612. this.getValue = this._getValue_unavailable;
  37613. this.setValue = this._setValue_unavailable;
  37614. // ensure there is a value node
  37615. if ( ! targetObject ) {
  37616. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37617. return;
  37618. }
  37619. if ( objectName ) {
  37620. let objectIndex = parsedPath.objectIndex;
  37621. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37622. switch ( objectName ) {
  37623. case 'materials':
  37624. if ( ! targetObject.material ) {
  37625. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37626. return;
  37627. }
  37628. if ( ! targetObject.material.materials ) {
  37629. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37630. return;
  37631. }
  37632. targetObject = targetObject.material.materials;
  37633. break;
  37634. case 'bones':
  37635. if ( ! targetObject.skeleton ) {
  37636. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37637. return;
  37638. }
  37639. // potential future optimization: skip this if propertyIndex is already an integer
  37640. // and convert the integer string to a true integer.
  37641. targetObject = targetObject.skeleton.bones;
  37642. // support resolving morphTarget names into indices.
  37643. for ( let i = 0; i < targetObject.length; i ++ ) {
  37644. if ( targetObject[ i ].name === objectIndex ) {
  37645. objectIndex = i;
  37646. break;
  37647. }
  37648. }
  37649. break;
  37650. case 'map':
  37651. if ( 'map' in targetObject ) {
  37652. targetObject = targetObject.map;
  37653. break;
  37654. }
  37655. if ( ! targetObject.material ) {
  37656. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37657. return;
  37658. }
  37659. if ( ! targetObject.material.map ) {
  37660. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37661. return;
  37662. }
  37663. targetObject = targetObject.material.map;
  37664. break;
  37665. default:
  37666. if ( targetObject[ objectName ] === undefined ) {
  37667. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37668. return;
  37669. }
  37670. targetObject = targetObject[ objectName ];
  37671. }
  37672. if ( objectIndex !== undefined ) {
  37673. if ( targetObject[ objectIndex ] === undefined ) {
  37674. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37675. return;
  37676. }
  37677. targetObject = targetObject[ objectIndex ];
  37678. }
  37679. }
  37680. // resolve property
  37681. const nodeProperty = targetObject[ propertyName ];
  37682. if ( nodeProperty === undefined ) {
  37683. const nodeName = parsedPath.nodeName;
  37684. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37685. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37686. return;
  37687. }
  37688. // determine versioning scheme
  37689. let versioning = this.Versioning.None;
  37690. this.targetObject = targetObject;
  37691. if ( targetObject.isMaterial === true ) {
  37692. versioning = this.Versioning.NeedsUpdate;
  37693. } else if ( targetObject.isObject3D === true ) {
  37694. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37695. }
  37696. // determine how the property gets bound
  37697. let bindingType = this.BindingType.Direct;
  37698. if ( propertyIndex !== undefined ) {
  37699. // access a sub element of the property array (only primitives are supported right now)
  37700. if ( propertyName === 'morphTargetInfluences' ) {
  37701. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37702. // support resolving morphTarget names into indices.
  37703. if ( ! targetObject.geometry ) {
  37704. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37705. return;
  37706. }
  37707. if ( ! targetObject.geometry.morphAttributes ) {
  37708. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37709. return;
  37710. }
  37711. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37712. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37713. }
  37714. }
  37715. bindingType = this.BindingType.ArrayElement;
  37716. this.resolvedProperty = nodeProperty;
  37717. this.propertyIndex = propertyIndex;
  37718. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37719. // must use copy for Object3D.Euler/Quaternion
  37720. bindingType = this.BindingType.HasFromToArray;
  37721. this.resolvedProperty = nodeProperty;
  37722. } else if ( Array.isArray( nodeProperty ) ) {
  37723. bindingType = this.BindingType.EntireArray;
  37724. this.resolvedProperty = nodeProperty;
  37725. } else {
  37726. this.propertyName = propertyName;
  37727. }
  37728. // select getter / setter
  37729. this.getValue = this.GetterByBindingType[ bindingType ];
  37730. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37731. }
  37732. /**
  37733. * Unbinds the property.
  37734. */
  37735. unbind() {
  37736. this.node = null;
  37737. // back to the prototype version of getValue / setValue
  37738. // note: avoiding to mutate the shape of 'this' via 'delete'
  37739. this.getValue = this._getValue_unbound;
  37740. this.setValue = this._setValue_unbound;
  37741. }
  37742. }
  37743. PropertyBinding.Composite = Composite;
  37744. PropertyBinding.prototype.BindingType = {
  37745. Direct: 0,
  37746. EntireArray: 1,
  37747. ArrayElement: 2,
  37748. HasFromToArray: 3
  37749. };
  37750. PropertyBinding.prototype.Versioning = {
  37751. None: 0,
  37752. NeedsUpdate: 1,
  37753. MatrixWorldNeedsUpdate: 2
  37754. };
  37755. PropertyBinding.prototype.GetterByBindingType = [
  37756. PropertyBinding.prototype._getValue_direct,
  37757. PropertyBinding.prototype._getValue_array,
  37758. PropertyBinding.prototype._getValue_arrayElement,
  37759. PropertyBinding.prototype._getValue_toArray,
  37760. ];
  37761. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37762. [
  37763. // Direct
  37764. PropertyBinding.prototype._setValue_direct,
  37765. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37766. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37767. ], [
  37768. // EntireArray
  37769. PropertyBinding.prototype._setValue_array,
  37770. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37771. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37772. ], [
  37773. // ArrayElement
  37774. PropertyBinding.prototype._setValue_arrayElement,
  37775. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37776. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37777. ], [
  37778. // HasToFromArray
  37779. PropertyBinding.prototype._setValue_fromArray,
  37780. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37781. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37782. ]
  37783. ];
  37784. /**
  37785. * A group of objects that receives a shared animation state.
  37786. *
  37787. * Usage:
  37788. *
  37789. * - Add objects you would otherwise pass as 'root' to the
  37790. * constructor or the .clipAction method of AnimationMixer.
  37791. * - Instead pass this object as 'root'.
  37792. * - You can also add and remove objects later when the mixer is running.
  37793. *
  37794. * Note:
  37795. *
  37796. * - Objects of this class appear as one object to the mixer,
  37797. * so cache control of the individual objects must be done on the group.
  37798. *
  37799. * Limitation:
  37800. *
  37801. * - The animated properties must be compatible among the all objects in the group.
  37802. * - A single property can either be controlled through a target group or directly, but not both.
  37803. */
  37804. class AnimationObjectGroup {
  37805. /**
  37806. * Constructs a new animation group.
  37807. *
  37808. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37809. */
  37810. constructor() {
  37811. /**
  37812. * This flag can be used for type testing.
  37813. *
  37814. * @type {boolean}
  37815. * @readonly
  37816. * @default true
  37817. */
  37818. this.isAnimationObjectGroup = true;
  37819. /**
  37820. * The UUID of the 3D object.
  37821. *
  37822. * @type {string}
  37823. * @readonly
  37824. */
  37825. this.uuid = generateUUID();
  37826. // cached objects followed by the active ones
  37827. this._objects = Array.prototype.slice.call( arguments );
  37828. this.nCachedObjects_ = 0; // threshold
  37829. // note: read by PropertyBinding.Composite
  37830. const indices = {};
  37831. this._indicesByUUID = indices; // for bookkeeping
  37832. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37833. indices[ arguments[ i ].uuid ] = i;
  37834. }
  37835. this._paths = []; // inside: string
  37836. this._parsedPaths = []; // inside: { we don't care, here }
  37837. this._bindings = []; // inside: Array< PropertyBinding >
  37838. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  37839. const scope = this;
  37840. this.stats = {
  37841. objects: {
  37842. get total() {
  37843. return scope._objects.length;
  37844. },
  37845. get inUse() {
  37846. return this.total - scope.nCachedObjects_;
  37847. }
  37848. },
  37849. get bindingsPerObject() {
  37850. return scope._bindings.length;
  37851. }
  37852. };
  37853. }
  37854. /**
  37855. * Adds an arbitrary number of objects to this animation group.
  37856. *
  37857. * @param {...Object3D} arguments - The 3D objects to add.
  37858. */
  37859. add() {
  37860. const objects = this._objects,
  37861. indicesByUUID = this._indicesByUUID,
  37862. paths = this._paths,
  37863. parsedPaths = this._parsedPaths,
  37864. bindings = this._bindings,
  37865. nBindings = bindings.length;
  37866. let knownObject = undefined,
  37867. nObjects = objects.length,
  37868. nCachedObjects = this.nCachedObjects_;
  37869. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37870. const object = arguments[ i ],
  37871. uuid = object.uuid;
  37872. let index = indicesByUUID[ uuid ];
  37873. if ( index === undefined ) {
  37874. // unknown object -> add it to the ACTIVE region
  37875. index = nObjects ++;
  37876. indicesByUUID[ uuid ] = index;
  37877. objects.push( object );
  37878. // accounting is done, now do the same for all bindings
  37879. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37880. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  37881. }
  37882. } else if ( index < nCachedObjects ) {
  37883. knownObject = objects[ index ];
  37884. // move existing object to the ACTIVE region
  37885. const firstActiveIndex = -- nCachedObjects,
  37886. lastCachedObject = objects[ firstActiveIndex ];
  37887. indicesByUUID[ lastCachedObject.uuid ] = index;
  37888. objects[ index ] = lastCachedObject;
  37889. indicesByUUID[ uuid ] = firstActiveIndex;
  37890. objects[ firstActiveIndex ] = object;
  37891. // accounting is done, now do the same for all bindings
  37892. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37893. const bindingsForPath = bindings[ j ],
  37894. lastCached = bindingsForPath[ firstActiveIndex ];
  37895. let binding = bindingsForPath[ index ];
  37896. bindingsForPath[ index ] = lastCached;
  37897. if ( binding === undefined ) {
  37898. // since we do not bother to create new bindings
  37899. // for objects that are cached, the binding may
  37900. // or may not exist
  37901. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  37902. }
  37903. bindingsForPath[ firstActiveIndex ] = binding;
  37904. }
  37905. } else if ( objects[ index ] !== knownObject ) {
  37906. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  37907. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  37908. } // else the object is already where we want it to be
  37909. } // for arguments
  37910. this.nCachedObjects_ = nCachedObjects;
  37911. }
  37912. /**
  37913. * Removes an arbitrary number of objects to this animation group
  37914. *
  37915. * @param {...Object3D} arguments - The 3D objects to remove.
  37916. */
  37917. remove() {
  37918. const objects = this._objects,
  37919. indicesByUUID = this._indicesByUUID,
  37920. bindings = this._bindings,
  37921. nBindings = bindings.length;
  37922. let nCachedObjects = this.nCachedObjects_;
  37923. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37924. const object = arguments[ i ],
  37925. uuid = object.uuid,
  37926. index = indicesByUUID[ uuid ];
  37927. if ( index !== undefined && index >= nCachedObjects ) {
  37928. // move existing object into the CACHED region
  37929. const lastCachedIndex = nCachedObjects ++,
  37930. firstActiveObject = objects[ lastCachedIndex ];
  37931. indicesByUUID[ firstActiveObject.uuid ] = index;
  37932. objects[ index ] = firstActiveObject;
  37933. indicesByUUID[ uuid ] = lastCachedIndex;
  37934. objects[ lastCachedIndex ] = object;
  37935. // accounting is done, now do the same for all bindings
  37936. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37937. const bindingsForPath = bindings[ j ],
  37938. firstActive = bindingsForPath[ lastCachedIndex ],
  37939. binding = bindingsForPath[ index ];
  37940. bindingsForPath[ index ] = firstActive;
  37941. bindingsForPath[ lastCachedIndex ] = binding;
  37942. }
  37943. }
  37944. } // for arguments
  37945. this.nCachedObjects_ = nCachedObjects;
  37946. }
  37947. /**
  37948. * Deallocates all memory resources for the passed 3D objects of this animation group.
  37949. *
  37950. * @param {...Object3D} arguments - The 3D objects to uncache.
  37951. */
  37952. uncache() {
  37953. const objects = this._objects,
  37954. indicesByUUID = this._indicesByUUID,
  37955. bindings = this._bindings,
  37956. nBindings = bindings.length;
  37957. let nCachedObjects = this.nCachedObjects_,
  37958. nObjects = objects.length;
  37959. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37960. const object = arguments[ i ],
  37961. uuid = object.uuid,
  37962. index = indicesByUUID[ uuid ];
  37963. if ( index !== undefined ) {
  37964. delete indicesByUUID[ uuid ];
  37965. if ( index < nCachedObjects ) {
  37966. // object is cached, shrink the CACHED region
  37967. const firstActiveIndex = -- nCachedObjects,
  37968. lastCachedObject = objects[ firstActiveIndex ],
  37969. lastIndex = -- nObjects,
  37970. lastObject = objects[ lastIndex ];
  37971. // last cached object takes this object's place
  37972. indicesByUUID[ lastCachedObject.uuid ] = index;
  37973. objects[ index ] = lastCachedObject;
  37974. // last object goes to the activated slot and pop
  37975. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  37976. objects[ firstActiveIndex ] = lastObject;
  37977. objects.pop();
  37978. // accounting is done, now do the same for all bindings
  37979. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37980. const bindingsForPath = bindings[ j ],
  37981. lastCached = bindingsForPath[ firstActiveIndex ],
  37982. last = bindingsForPath[ lastIndex ];
  37983. bindingsForPath[ index ] = lastCached;
  37984. bindingsForPath[ firstActiveIndex ] = last;
  37985. bindingsForPath.pop();
  37986. }
  37987. } else {
  37988. // object is active, just swap with the last and pop
  37989. const lastIndex = -- nObjects,
  37990. lastObject = objects[ lastIndex ];
  37991. if ( lastIndex > 0 ) {
  37992. indicesByUUID[ lastObject.uuid ] = index;
  37993. }
  37994. objects[ index ] = lastObject;
  37995. objects.pop();
  37996. // accounting is done, now do the same for all bindings
  37997. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  37998. const bindingsForPath = bindings[ j ];
  37999. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38000. bindingsForPath.pop();
  38001. }
  38002. } // cached or active
  38003. } // if object is known
  38004. } // for arguments
  38005. this.nCachedObjects_ = nCachedObjects;
  38006. }
  38007. // Internal interface used by befriended PropertyBinding.Composite:
  38008. subscribe_( path, parsedPath ) {
  38009. // returns an array of bindings for the given path that is changed
  38010. // according to the contained objects in the group
  38011. const indicesByPath = this._bindingsIndicesByPath;
  38012. let index = indicesByPath[ path ];
  38013. const bindings = this._bindings;
  38014. if ( index !== undefined ) return bindings[ index ];
  38015. const paths = this._paths,
  38016. parsedPaths = this._parsedPaths,
  38017. objects = this._objects,
  38018. nObjects = objects.length,
  38019. nCachedObjects = this.nCachedObjects_,
  38020. bindingsForPath = new Array( nObjects );
  38021. index = bindings.length;
  38022. indicesByPath[ path ] = index;
  38023. paths.push( path );
  38024. parsedPaths.push( parsedPath );
  38025. bindings.push( bindingsForPath );
  38026. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38027. const object = objects[ i ];
  38028. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38029. }
  38030. return bindingsForPath;
  38031. }
  38032. unsubscribe_( path ) {
  38033. // tells the group to forget about a property path and no longer
  38034. // update the array previously obtained with 'subscribe_'
  38035. const indicesByPath = this._bindingsIndicesByPath,
  38036. index = indicesByPath[ path ];
  38037. if ( index !== undefined ) {
  38038. const paths = this._paths,
  38039. parsedPaths = this._parsedPaths,
  38040. bindings = this._bindings,
  38041. lastBindingsIndex = bindings.length - 1,
  38042. lastBindings = bindings[ lastBindingsIndex ],
  38043. lastBindingsPath = path[ lastBindingsIndex ];
  38044. indicesByPath[ lastBindingsPath ] = index;
  38045. bindings[ index ] = lastBindings;
  38046. bindings.pop();
  38047. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38048. parsedPaths.pop();
  38049. paths[ index ] = paths[ lastBindingsIndex ];
  38050. paths.pop();
  38051. }
  38052. }
  38053. }
  38054. /**
  38055. * An instance of `AnimationAction` schedules the playback of an animation which is
  38056. * stored in {@link AnimationClip}.
  38057. */
  38058. class AnimationAction {
  38059. /**
  38060. * Constructs a new animation action.
  38061. *
  38062. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38063. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38064. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38065. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38066. */
  38067. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38068. this._mixer = mixer;
  38069. this._clip = clip;
  38070. this._localRoot = localRoot;
  38071. /**
  38072. * Defines how the animation is blended/combined when two or more animations
  38073. * are simultaneously played.
  38074. *
  38075. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38076. */
  38077. this.blendMode = blendMode;
  38078. const tracks = clip.tracks,
  38079. nTracks = tracks.length,
  38080. interpolants = new Array( nTracks );
  38081. const interpolantSettings = {
  38082. endingStart: ZeroCurvatureEnding,
  38083. endingEnd: ZeroCurvatureEnding
  38084. };
  38085. for ( let i = 0; i !== nTracks; ++ i ) {
  38086. const interpolant = tracks[ i ].createInterpolant( null );
  38087. interpolants[ i ] = interpolant;
  38088. interpolant.settings = interpolantSettings;
  38089. }
  38090. this._interpolantSettings = interpolantSettings;
  38091. this._interpolants = interpolants; // bound by the mixer
  38092. // inside: PropertyMixer (managed by the mixer)
  38093. this._propertyBindings = new Array( nTracks );
  38094. this._cacheIndex = null; // for the memory manager
  38095. this._byClipCacheIndex = null; // for the memory manager
  38096. this._timeScaleInterpolant = null;
  38097. this._weightInterpolant = null;
  38098. /**
  38099. * The loop mode, set via {@link AnimationAction#setLoop}.
  38100. *
  38101. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38102. * @default LoopRepeat
  38103. */
  38104. this.loop = LoopRepeat;
  38105. this._loopCount = -1;
  38106. // global mixer time when the action is to be started
  38107. // it's set back to 'null' upon start of the action
  38108. this._startTime = null;
  38109. /**
  38110. * The local time of this action (in seconds, starting with `0`).
  38111. *
  38112. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38113. * loop state).
  38114. *
  38115. * @type {number}
  38116. * @default Infinity
  38117. */
  38118. this.time = 0;
  38119. /**
  38120. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38121. * animation to pause. Negative values cause the animation to play backwards.
  38122. *
  38123. * @type {number}
  38124. * @default 1
  38125. */
  38126. this.timeScale = 1;
  38127. this._effectiveTimeScale = 1;
  38128. /**
  38129. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38130. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38131. * several actions.
  38132. *
  38133. * @type {number}
  38134. * @default 1
  38135. */
  38136. this.weight = 1;
  38137. this._effectiveWeight = 1;
  38138. /**
  38139. * The number of repetitions of the performed clip over the course of this action.
  38140. * Can be set via {@link AnimationAction#setLoop}.
  38141. *
  38142. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38143. * `THREE:LoopOnce`.
  38144. *
  38145. * @type {number}
  38146. * @default Infinity
  38147. */
  38148. this.repetitions = Infinity;
  38149. /**
  38150. * If set to `true`, the playback of the action is paused.
  38151. *
  38152. * @type {boolean}
  38153. * @default false
  38154. */
  38155. this.paused = false;
  38156. /**
  38157. * If set to `false`, the action is disabled so it has no impact.
  38158. *
  38159. * When the action is re-enabled, the animation continues from its current
  38160. * time (setting `enabled` to `false` doesn't reset the action).
  38161. *
  38162. * @type {boolean}
  38163. * @default true
  38164. */
  38165. this.enabled = true;
  38166. /**
  38167. * If set to true the animation will automatically be paused on its last frame.
  38168. *
  38169. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38170. * to `false` when the last loop of the action has finished, so that this action has
  38171. * no further impact.
  38172. *
  38173. * Note: This member has no impact if the action is interrupted (it
  38174. * has only an effect if its last loop has really finished).
  38175. *
  38176. * @type {boolean}
  38177. * @default false
  38178. */
  38179. this.clampWhenFinished = false;
  38180. /**
  38181. * Enables smooth interpolation without separate clips for start, loop and end.
  38182. *
  38183. * @type {boolean}
  38184. * @default true
  38185. */
  38186. this.zeroSlopeAtStart = true;
  38187. /**
  38188. * Enables smooth interpolation without separate clips for start, loop and end.
  38189. *
  38190. * @type {boolean}
  38191. * @default true
  38192. */
  38193. this.zeroSlopeAtEnd = true;
  38194. }
  38195. /**
  38196. * Starts the playback of the animation.
  38197. *
  38198. * @return {AnimationAction} A reference to this animation action.
  38199. */
  38200. play() {
  38201. this._mixer._activateAction( this );
  38202. return this;
  38203. }
  38204. /**
  38205. * Stops the playback of the animation.
  38206. *
  38207. * @return {AnimationAction} A reference to this animation action.
  38208. */
  38209. stop() {
  38210. this._mixer._deactivateAction( this );
  38211. return this.reset();
  38212. }
  38213. /**
  38214. * Resets the playback of the animation.
  38215. *
  38216. * @return {AnimationAction} A reference to this animation action.
  38217. */
  38218. reset() {
  38219. this.paused = false;
  38220. this.enabled = true;
  38221. this.time = 0; // restart clip
  38222. this._loopCount = -1;// forget previous loops
  38223. this._startTime = null;// forget scheduling
  38224. return this.stopFading().stopWarping();
  38225. }
  38226. /**
  38227. * Returns `true` if the animation is running.
  38228. *
  38229. * @return {boolean} Whether the animation is running or not.
  38230. */
  38231. isRunning() {
  38232. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38233. this._startTime === null && this._mixer._isActiveAction( this );
  38234. }
  38235. /**
  38236. * Returns `true` when {@link AnimationAction#play} has been called.
  38237. *
  38238. * @return {boolean} Whether the animation is scheduled or not.
  38239. */
  38240. isScheduled() {
  38241. return this._mixer._isActiveAction( this );
  38242. }
  38243. /**
  38244. * Defines the time when the animation should start.
  38245. *
  38246. * @param {number} time - The start time in seconds.
  38247. * @return {AnimationAction} A reference to this animation action.
  38248. */
  38249. startAt( time ) {
  38250. this._startTime = time;
  38251. return this;
  38252. }
  38253. /**
  38254. * Configures the loop settings for this action.
  38255. *
  38256. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38257. * @param {number} repetitions - The number of repetitions.
  38258. * @return {AnimationAction} A reference to this animation action.
  38259. */
  38260. setLoop( mode, repetitions ) {
  38261. this.loop = mode;
  38262. this.repetitions = repetitions;
  38263. return this;
  38264. }
  38265. /**
  38266. * Sets the effective weight of this action.
  38267. *
  38268. * An action has no effect and thus an effective weight of zero when the
  38269. * action is disabled.
  38270. *
  38271. * @param {number} weight - The weight to set.
  38272. * @return {AnimationAction} A reference to this animation action.
  38273. */
  38274. setEffectiveWeight( weight ) {
  38275. this.weight = weight;
  38276. // note: same logic as when updated at runtime
  38277. this._effectiveWeight = this.enabled ? weight : 0;
  38278. return this.stopFading();
  38279. }
  38280. /**
  38281. * Returns the effective weight of this action.
  38282. *
  38283. * @return {number} The effective weight.
  38284. */
  38285. getEffectiveWeight() {
  38286. return this._effectiveWeight;
  38287. }
  38288. /**
  38289. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38290. * within the passed time interval.
  38291. *
  38292. * @param {number} duration - The duration of the fade.
  38293. * @return {AnimationAction} A reference to this animation action.
  38294. */
  38295. fadeIn( duration ) {
  38296. return this._scheduleFading( duration, 0, 1 );
  38297. }
  38298. /**
  38299. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38300. * within the passed time interval.
  38301. *
  38302. * @param {number} duration - The duration of the fade.
  38303. * @return {AnimationAction} A reference to this animation action.
  38304. */
  38305. fadeOut( duration ) {
  38306. return this._scheduleFading( duration, 1, 0 );
  38307. }
  38308. /**
  38309. * Causes this action to fade in and the given action to fade out,
  38310. * within the passed time interval.
  38311. *
  38312. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38313. * @param {number} duration - The duration of the fade.
  38314. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38315. * @return {AnimationAction} A reference to this animation action.
  38316. */
  38317. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38318. fadeOutAction.fadeOut( duration );
  38319. this.fadeIn( duration );
  38320. if ( warp === true ) {
  38321. const fadeInDuration = this._clip.duration,
  38322. fadeOutDuration = fadeOutAction._clip.duration,
  38323. startEndRatio = fadeOutDuration / fadeInDuration,
  38324. endStartRatio = fadeInDuration / fadeOutDuration;
  38325. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38326. this.warp( endStartRatio, 1.0, duration );
  38327. }
  38328. return this;
  38329. }
  38330. /**
  38331. * Causes this action to fade out and the given action to fade in,
  38332. * within the passed time interval.
  38333. *
  38334. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38335. * @param {number} duration - The duration of the fade.
  38336. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38337. * @return {AnimationAction} A reference to this animation action.
  38338. */
  38339. crossFadeTo( fadeInAction, duration, warp = false ) {
  38340. return fadeInAction.crossFadeFrom( this, duration, warp );
  38341. }
  38342. /**
  38343. * Stops any fading which is applied to this action.
  38344. *
  38345. * @return {AnimationAction} A reference to this animation action.
  38346. */
  38347. stopFading() {
  38348. const weightInterpolant = this._weightInterpolant;
  38349. if ( weightInterpolant !== null ) {
  38350. this._weightInterpolant = null;
  38351. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38352. }
  38353. return this;
  38354. }
  38355. /**
  38356. * Sets the effective time scale of this action.
  38357. *
  38358. * An action has no effect and thus an effective time scale of zero when the
  38359. * action is paused.
  38360. *
  38361. * @param {number} timeScale - The time scale to set.
  38362. * @return {AnimationAction} A reference to this animation action.
  38363. */
  38364. setEffectiveTimeScale( timeScale ) {
  38365. this.timeScale = timeScale;
  38366. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38367. return this.stopWarping();
  38368. }
  38369. /**
  38370. * Returns the effective time scale of this action.
  38371. *
  38372. * @return {number} The effective time scale.
  38373. */
  38374. getEffectiveTimeScale() {
  38375. return this._effectiveTimeScale;
  38376. }
  38377. /**
  38378. * Sets the duration for a single loop of this action.
  38379. *
  38380. * @param {number} duration - The duration to set.
  38381. * @return {AnimationAction} A reference to this animation action.
  38382. */
  38383. setDuration( duration ) {
  38384. this.timeScale = this._clip.duration / duration;
  38385. return this.stopWarping();
  38386. }
  38387. /**
  38388. * Synchronizes this action with the passed other action.
  38389. *
  38390. * @param {AnimationAction} action - The action to sync with.
  38391. * @return {AnimationAction} A reference to this animation action.
  38392. */
  38393. syncWith( action ) {
  38394. this.time = action.time;
  38395. this.timeScale = action.timeScale;
  38396. return this.stopWarping();
  38397. }
  38398. /**
  38399. * Decelerates this animation's speed to `0` within the passed time interval.
  38400. *
  38401. * @param {number} duration - The duration.
  38402. * @return {AnimationAction} A reference to this animation action.
  38403. */
  38404. halt( duration ) {
  38405. return this.warp( this._effectiveTimeScale, 0, duration );
  38406. }
  38407. /**
  38408. * Changes the playback speed, within the passed time interval, by modifying
  38409. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38410. * `endTimeScale`.
  38411. *
  38412. * @param {number} startTimeScale - The start time scale.
  38413. * @param {number} endTimeScale - The end time scale.
  38414. * @param {number} duration - The duration.
  38415. * @return {AnimationAction} A reference to this animation action.
  38416. */
  38417. warp( startTimeScale, endTimeScale, duration ) {
  38418. const mixer = this._mixer,
  38419. now = mixer.time,
  38420. timeScale = this.timeScale;
  38421. let interpolant = this._timeScaleInterpolant;
  38422. if ( interpolant === null ) {
  38423. interpolant = mixer._lendControlInterpolant();
  38424. this._timeScaleInterpolant = interpolant;
  38425. }
  38426. const times = interpolant.parameterPositions,
  38427. values = interpolant.sampleValues;
  38428. times[ 0 ] = now;
  38429. times[ 1 ] = now + duration;
  38430. values[ 0 ] = startTimeScale / timeScale;
  38431. values[ 1 ] = endTimeScale / timeScale;
  38432. return this;
  38433. }
  38434. /**
  38435. * Stops any scheduled warping which is applied to this action.
  38436. *
  38437. * @return {AnimationAction} A reference to this animation action.
  38438. */
  38439. stopWarping() {
  38440. const timeScaleInterpolant = this._timeScaleInterpolant;
  38441. if ( timeScaleInterpolant !== null ) {
  38442. this._timeScaleInterpolant = null;
  38443. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38444. }
  38445. return this;
  38446. }
  38447. /**
  38448. * Returns the animation mixer of this animation action.
  38449. *
  38450. * @return {AnimationMixer} The animation mixer.
  38451. */
  38452. getMixer() {
  38453. return this._mixer;
  38454. }
  38455. /**
  38456. * Returns the animation clip of this animation action.
  38457. *
  38458. * @return {AnimationClip} The animation clip.
  38459. */
  38460. getClip() {
  38461. return this._clip;
  38462. }
  38463. /**
  38464. * Returns the root object of this animation action.
  38465. *
  38466. * @return {Object3D} The root object.
  38467. */
  38468. getRoot() {
  38469. return this._localRoot || this._mixer._root;
  38470. }
  38471. // Interna
  38472. _update( time, deltaTime, timeDirection, accuIndex ) {
  38473. // called by the mixer
  38474. if ( ! this.enabled ) {
  38475. // call ._updateWeight() to update ._effectiveWeight
  38476. this._updateWeight( time );
  38477. return;
  38478. }
  38479. const startTime = this._startTime;
  38480. if ( startTime !== null ) {
  38481. // check for scheduled start of action
  38482. const timeRunning = ( time - startTime ) * timeDirection;
  38483. if ( timeRunning < 0 || timeDirection === 0 ) {
  38484. deltaTime = 0;
  38485. } else {
  38486. this._startTime = null; // unschedule
  38487. deltaTime = timeDirection * timeRunning;
  38488. }
  38489. }
  38490. // apply time scale and advance time
  38491. deltaTime *= this._updateTimeScale( time );
  38492. const clipTime = this._updateTime( deltaTime );
  38493. // note: _updateTime may disable the action resulting in
  38494. // an effective weight of 0
  38495. const weight = this._updateWeight( time );
  38496. if ( weight > 0 ) {
  38497. const interpolants = this._interpolants;
  38498. const propertyMixers = this._propertyBindings;
  38499. switch ( this.blendMode ) {
  38500. case AdditiveAnimationBlendMode:
  38501. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38502. interpolants[ j ].evaluate( clipTime );
  38503. propertyMixers[ j ].accumulateAdditive( weight );
  38504. }
  38505. break;
  38506. case NormalAnimationBlendMode:
  38507. default:
  38508. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38509. interpolants[ j ].evaluate( clipTime );
  38510. propertyMixers[ j ].accumulate( accuIndex, weight );
  38511. }
  38512. }
  38513. }
  38514. }
  38515. _updateWeight( time ) {
  38516. let weight = 0;
  38517. if ( this.enabled ) {
  38518. weight = this.weight;
  38519. const interpolant = this._weightInterpolant;
  38520. if ( interpolant !== null ) {
  38521. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38522. weight *= interpolantValue;
  38523. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38524. this.stopFading();
  38525. if ( interpolantValue === 0 ) {
  38526. // faded out, disable
  38527. this.enabled = false;
  38528. }
  38529. }
  38530. }
  38531. }
  38532. this._effectiveWeight = weight;
  38533. return weight;
  38534. }
  38535. _updateTimeScale( time ) {
  38536. let timeScale = 0;
  38537. if ( ! this.paused ) {
  38538. timeScale = this.timeScale;
  38539. const interpolant = this._timeScaleInterpolant;
  38540. if ( interpolant !== null ) {
  38541. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38542. timeScale *= interpolantValue;
  38543. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38544. this.stopWarping();
  38545. if ( timeScale === 0 ) {
  38546. // motion has halted, pause
  38547. this.paused = true;
  38548. } else {
  38549. // warp done - apply final time scale
  38550. this.timeScale = timeScale;
  38551. }
  38552. }
  38553. }
  38554. }
  38555. this._effectiveTimeScale = timeScale;
  38556. return timeScale;
  38557. }
  38558. _updateTime( deltaTime ) {
  38559. const duration = this._clip.duration;
  38560. const loop = this.loop;
  38561. let time = this.time + deltaTime;
  38562. let loopCount = this._loopCount;
  38563. const pingPong = ( loop === LoopPingPong );
  38564. if ( deltaTime === 0 ) {
  38565. if ( loopCount === -1 ) return time;
  38566. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38567. }
  38568. if ( loop === LoopOnce ) {
  38569. if ( loopCount === -1 ) {
  38570. // just started
  38571. this._loopCount = 0;
  38572. this._setEndings( true, true, false );
  38573. }
  38574. handle_stop: {
  38575. if ( time >= duration ) {
  38576. time = duration;
  38577. } else if ( time < 0 ) {
  38578. time = 0;
  38579. } else {
  38580. this.time = time;
  38581. break handle_stop;
  38582. }
  38583. if ( this.clampWhenFinished ) this.paused = true;
  38584. else this.enabled = false;
  38585. this.time = time;
  38586. this._mixer.dispatchEvent( {
  38587. type: 'finished', action: this,
  38588. direction: deltaTime < 0 ? -1 : 1
  38589. } );
  38590. }
  38591. } else { // repetitive Repeat or PingPong
  38592. if ( loopCount === -1 ) {
  38593. // just started
  38594. if ( deltaTime >= 0 ) {
  38595. loopCount = 0;
  38596. this._setEndings( true, this.repetitions === 0, pingPong );
  38597. } else {
  38598. // when looping in reverse direction, the initial
  38599. // transition through zero counts as a repetition,
  38600. // so leave loopCount at -1
  38601. this._setEndings( this.repetitions === 0, true, pingPong );
  38602. }
  38603. }
  38604. if ( time >= duration || time < 0 ) {
  38605. // wrap around
  38606. const loopDelta = Math.floor( time / duration ); // signed
  38607. time -= duration * loopDelta;
  38608. loopCount += Math.abs( loopDelta );
  38609. const pending = this.repetitions - loopCount;
  38610. if ( pending <= 0 ) {
  38611. // have to stop (switch state, clamp time, fire event)
  38612. if ( this.clampWhenFinished ) this.paused = true;
  38613. else this.enabled = false;
  38614. time = deltaTime > 0 ? duration : 0;
  38615. this.time = time;
  38616. this._mixer.dispatchEvent( {
  38617. type: 'finished', action: this,
  38618. direction: deltaTime > 0 ? 1 : -1
  38619. } );
  38620. } else {
  38621. // keep running
  38622. if ( pending === 1 ) {
  38623. // entering the last round
  38624. const atStart = deltaTime < 0;
  38625. this._setEndings( atStart, ! atStart, pingPong );
  38626. } else {
  38627. this._setEndings( false, false, pingPong );
  38628. }
  38629. this._loopCount = loopCount;
  38630. this.time = time;
  38631. this._mixer.dispatchEvent( {
  38632. type: 'loop', action: this, loopDelta: loopDelta
  38633. } );
  38634. }
  38635. } else {
  38636. this.time = time;
  38637. }
  38638. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38639. // invert time for the "pong round"
  38640. return duration - time;
  38641. }
  38642. }
  38643. return time;
  38644. }
  38645. _setEndings( atStart, atEnd, pingPong ) {
  38646. const settings = this._interpolantSettings;
  38647. if ( pingPong ) {
  38648. settings.endingStart = ZeroSlopeEnding;
  38649. settings.endingEnd = ZeroSlopeEnding;
  38650. } else {
  38651. // assuming for LoopOnce atStart == atEnd == true
  38652. if ( atStart ) {
  38653. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38654. } else {
  38655. settings.endingStart = WrapAroundEnding;
  38656. }
  38657. if ( atEnd ) {
  38658. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38659. } else {
  38660. settings.endingEnd = WrapAroundEnding;
  38661. }
  38662. }
  38663. }
  38664. _scheduleFading( duration, weightNow, weightThen ) {
  38665. const mixer = this._mixer, now = mixer.time;
  38666. let interpolant = this._weightInterpolant;
  38667. if ( interpolant === null ) {
  38668. interpolant = mixer._lendControlInterpolant();
  38669. this._weightInterpolant = interpolant;
  38670. }
  38671. const times = interpolant.parameterPositions,
  38672. values = interpolant.sampleValues;
  38673. times[ 0 ] = now;
  38674. values[ 0 ] = weightNow;
  38675. times[ 1 ] = now + duration;
  38676. values[ 1 ] = weightThen;
  38677. return this;
  38678. }
  38679. }
  38680. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38681. /**
  38682. * `AnimationMixer` is a player for animations on a particular object in
  38683. * the scene. When multiple objects in the scene are animated independently,
  38684. * one `AnimationMixer` may be used for each object.
  38685. */
  38686. class AnimationMixer extends EventDispatcher {
  38687. /**
  38688. * Constructs a new animation mixer.
  38689. *
  38690. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38691. */
  38692. constructor( root ) {
  38693. super();
  38694. this._root = root;
  38695. this._initMemoryManager();
  38696. this._accuIndex = 0;
  38697. /**
  38698. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38699. *
  38700. * @type {number}
  38701. * @default 0
  38702. */
  38703. this.time = 0;
  38704. /**
  38705. * A scaling factor for the global time.
  38706. *
  38707. * Note: Setting this member to `0` and later back to `1` is a
  38708. * possibility to pause/unpause all actions that are controlled by this
  38709. * mixer.
  38710. *
  38711. * @type {number}
  38712. * @default 1
  38713. */
  38714. this.timeScale = 1.0;
  38715. }
  38716. _bindAction( action, prototypeAction ) {
  38717. const root = action._localRoot || this._root,
  38718. tracks = action._clip.tracks,
  38719. nTracks = tracks.length,
  38720. bindings = action._propertyBindings,
  38721. interpolants = action._interpolants,
  38722. rootUuid = root.uuid,
  38723. bindingsByRoot = this._bindingsByRootAndName;
  38724. let bindingsByName = bindingsByRoot[ rootUuid ];
  38725. if ( bindingsByName === undefined ) {
  38726. bindingsByName = {};
  38727. bindingsByRoot[ rootUuid ] = bindingsByName;
  38728. }
  38729. for ( let i = 0; i !== nTracks; ++ i ) {
  38730. const track = tracks[ i ],
  38731. trackName = track.name;
  38732. let binding = bindingsByName[ trackName ];
  38733. if ( binding !== undefined ) {
  38734. ++ binding.referenceCount;
  38735. bindings[ i ] = binding;
  38736. } else {
  38737. binding = bindings[ i ];
  38738. if ( binding !== undefined ) {
  38739. // existing binding, make sure the cache knows
  38740. if ( binding._cacheIndex === null ) {
  38741. ++ binding.referenceCount;
  38742. this._addInactiveBinding( binding, rootUuid, trackName );
  38743. }
  38744. continue;
  38745. }
  38746. const path = prototypeAction && prototypeAction.
  38747. _propertyBindings[ i ].binding.parsedPath;
  38748. binding = new PropertyMixer(
  38749. PropertyBinding.create( root, trackName, path ),
  38750. track.ValueTypeName, track.getValueSize() );
  38751. ++ binding.referenceCount;
  38752. this._addInactiveBinding( binding, rootUuid, trackName );
  38753. bindings[ i ] = binding;
  38754. }
  38755. interpolants[ i ].resultBuffer = binding.buffer;
  38756. }
  38757. }
  38758. _activateAction( action ) {
  38759. if ( ! this._isActiveAction( action ) ) {
  38760. if ( action._cacheIndex === null ) {
  38761. // this action has been forgotten by the cache, but the user
  38762. // appears to be still using it -> rebind
  38763. const rootUuid = ( action._localRoot || this._root ).uuid,
  38764. clipUuid = action._clip.uuid,
  38765. actionsForClip = this._actionsByClip[ clipUuid ];
  38766. this._bindAction( action,
  38767. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38768. this._addInactiveAction( action, clipUuid, rootUuid );
  38769. }
  38770. const bindings = action._propertyBindings;
  38771. // increment reference counts / sort out state
  38772. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38773. const binding = bindings[ i ];
  38774. if ( binding.useCount ++ === 0 ) {
  38775. this._lendBinding( binding );
  38776. binding.saveOriginalState();
  38777. }
  38778. }
  38779. this._lendAction( action );
  38780. }
  38781. }
  38782. _deactivateAction( action ) {
  38783. if ( this._isActiveAction( action ) ) {
  38784. const bindings = action._propertyBindings;
  38785. // decrement reference counts / sort out state
  38786. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38787. const binding = bindings[ i ];
  38788. if ( -- binding.useCount === 0 ) {
  38789. binding.restoreOriginalState();
  38790. this._takeBackBinding( binding );
  38791. }
  38792. }
  38793. this._takeBackAction( action );
  38794. }
  38795. }
  38796. // Memory manager
  38797. _initMemoryManager() {
  38798. this._actions = []; // 'nActiveActions' followed by inactive ones
  38799. this._nActiveActions = 0;
  38800. this._actionsByClip = {};
  38801. // inside:
  38802. // {
  38803. // knownActions: Array< AnimationAction > - used as prototypes
  38804. // actionByRoot: AnimationAction - lookup
  38805. // }
  38806. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38807. this._nActiveBindings = 0;
  38808. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38809. this._controlInterpolants = []; // same game as above
  38810. this._nActiveControlInterpolants = 0;
  38811. const scope = this;
  38812. this.stats = {
  38813. actions: {
  38814. get total() {
  38815. return scope._actions.length;
  38816. },
  38817. get inUse() {
  38818. return scope._nActiveActions;
  38819. }
  38820. },
  38821. bindings: {
  38822. get total() {
  38823. return scope._bindings.length;
  38824. },
  38825. get inUse() {
  38826. return scope._nActiveBindings;
  38827. }
  38828. },
  38829. controlInterpolants: {
  38830. get total() {
  38831. return scope._controlInterpolants.length;
  38832. },
  38833. get inUse() {
  38834. return scope._nActiveControlInterpolants;
  38835. }
  38836. }
  38837. };
  38838. }
  38839. // Memory management for AnimationAction objects
  38840. _isActiveAction( action ) {
  38841. const index = action._cacheIndex;
  38842. return index !== null && index < this._nActiveActions;
  38843. }
  38844. _addInactiveAction( action, clipUuid, rootUuid ) {
  38845. const actions = this._actions,
  38846. actionsByClip = this._actionsByClip;
  38847. let actionsForClip = actionsByClip[ clipUuid ];
  38848. if ( actionsForClip === undefined ) {
  38849. actionsForClip = {
  38850. knownActions: [ action ],
  38851. actionByRoot: {}
  38852. };
  38853. action._byClipCacheIndex = 0;
  38854. actionsByClip[ clipUuid ] = actionsForClip;
  38855. } else {
  38856. const knownActions = actionsForClip.knownActions;
  38857. action._byClipCacheIndex = knownActions.length;
  38858. knownActions.push( action );
  38859. }
  38860. action._cacheIndex = actions.length;
  38861. actions.push( action );
  38862. actionsForClip.actionByRoot[ rootUuid ] = action;
  38863. }
  38864. _removeInactiveAction( action ) {
  38865. const actions = this._actions,
  38866. lastInactiveAction = actions[ actions.length - 1 ],
  38867. cacheIndex = action._cacheIndex;
  38868. lastInactiveAction._cacheIndex = cacheIndex;
  38869. actions[ cacheIndex ] = lastInactiveAction;
  38870. actions.pop();
  38871. action._cacheIndex = null;
  38872. const clipUuid = action._clip.uuid,
  38873. actionsByClip = this._actionsByClip,
  38874. actionsForClip = actionsByClip[ clipUuid ],
  38875. knownActionsForClip = actionsForClip.knownActions,
  38876. lastKnownAction =
  38877. knownActionsForClip[ knownActionsForClip.length - 1 ],
  38878. byClipCacheIndex = action._byClipCacheIndex;
  38879. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  38880. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  38881. knownActionsForClip.pop();
  38882. action._byClipCacheIndex = null;
  38883. const actionByRoot = actionsForClip.actionByRoot,
  38884. rootUuid = ( action._localRoot || this._root ).uuid;
  38885. delete actionByRoot[ rootUuid ];
  38886. if ( knownActionsForClip.length === 0 ) {
  38887. delete actionsByClip[ clipUuid ];
  38888. }
  38889. this._removeInactiveBindingsForAction( action );
  38890. }
  38891. _removeInactiveBindingsForAction( action ) {
  38892. const bindings = action._propertyBindings;
  38893. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38894. const binding = bindings[ i ];
  38895. if ( -- binding.referenceCount === 0 ) {
  38896. this._removeInactiveBinding( binding );
  38897. }
  38898. }
  38899. }
  38900. _lendAction( action ) {
  38901. // [ active actions | inactive actions ]
  38902. // [ active actions >| inactive actions ]
  38903. // s a
  38904. // <-swap->
  38905. // a s
  38906. const actions = this._actions,
  38907. prevIndex = action._cacheIndex,
  38908. lastActiveIndex = this._nActiveActions ++,
  38909. firstInactiveAction = actions[ lastActiveIndex ];
  38910. action._cacheIndex = lastActiveIndex;
  38911. actions[ lastActiveIndex ] = action;
  38912. firstInactiveAction._cacheIndex = prevIndex;
  38913. actions[ prevIndex ] = firstInactiveAction;
  38914. }
  38915. _takeBackAction( action ) {
  38916. // [ active actions | inactive actions ]
  38917. // [ active actions |< inactive actions ]
  38918. // a s
  38919. // <-swap->
  38920. // s a
  38921. const actions = this._actions,
  38922. prevIndex = action._cacheIndex,
  38923. firstInactiveIndex = -- this._nActiveActions,
  38924. lastActiveAction = actions[ firstInactiveIndex ];
  38925. action._cacheIndex = firstInactiveIndex;
  38926. actions[ firstInactiveIndex ] = action;
  38927. lastActiveAction._cacheIndex = prevIndex;
  38928. actions[ prevIndex ] = lastActiveAction;
  38929. }
  38930. // Memory management for PropertyMixer objects
  38931. _addInactiveBinding( binding, rootUuid, trackName ) {
  38932. const bindingsByRoot = this._bindingsByRootAndName,
  38933. bindings = this._bindings;
  38934. let bindingByName = bindingsByRoot[ rootUuid ];
  38935. if ( bindingByName === undefined ) {
  38936. bindingByName = {};
  38937. bindingsByRoot[ rootUuid ] = bindingByName;
  38938. }
  38939. bindingByName[ trackName ] = binding;
  38940. binding._cacheIndex = bindings.length;
  38941. bindings.push( binding );
  38942. }
  38943. _removeInactiveBinding( binding ) {
  38944. const bindings = this._bindings,
  38945. propBinding = binding.binding,
  38946. rootUuid = propBinding.rootNode.uuid,
  38947. trackName = propBinding.path,
  38948. bindingsByRoot = this._bindingsByRootAndName,
  38949. bindingByName = bindingsByRoot[ rootUuid ],
  38950. lastInactiveBinding = bindings[ bindings.length - 1 ],
  38951. cacheIndex = binding._cacheIndex;
  38952. lastInactiveBinding._cacheIndex = cacheIndex;
  38953. bindings[ cacheIndex ] = lastInactiveBinding;
  38954. bindings.pop();
  38955. delete bindingByName[ trackName ];
  38956. if ( Object.keys( bindingByName ).length === 0 ) {
  38957. delete bindingsByRoot[ rootUuid ];
  38958. }
  38959. }
  38960. _lendBinding( binding ) {
  38961. const bindings = this._bindings,
  38962. prevIndex = binding._cacheIndex,
  38963. lastActiveIndex = this._nActiveBindings ++,
  38964. firstInactiveBinding = bindings[ lastActiveIndex ];
  38965. binding._cacheIndex = lastActiveIndex;
  38966. bindings[ lastActiveIndex ] = binding;
  38967. firstInactiveBinding._cacheIndex = prevIndex;
  38968. bindings[ prevIndex ] = firstInactiveBinding;
  38969. }
  38970. _takeBackBinding( binding ) {
  38971. const bindings = this._bindings,
  38972. prevIndex = binding._cacheIndex,
  38973. firstInactiveIndex = -- this._nActiveBindings,
  38974. lastActiveBinding = bindings[ firstInactiveIndex ];
  38975. binding._cacheIndex = firstInactiveIndex;
  38976. bindings[ firstInactiveIndex ] = binding;
  38977. lastActiveBinding._cacheIndex = prevIndex;
  38978. bindings[ prevIndex ] = lastActiveBinding;
  38979. }
  38980. // Memory management of Interpolants for weight and time scale
  38981. _lendControlInterpolant() {
  38982. const interpolants = this._controlInterpolants,
  38983. lastActiveIndex = this._nActiveControlInterpolants ++;
  38984. let interpolant = interpolants[ lastActiveIndex ];
  38985. if ( interpolant === undefined ) {
  38986. interpolant = new LinearInterpolant(
  38987. new Float32Array( 2 ), new Float32Array( 2 ),
  38988. 1, _controlInterpolantsResultBuffer );
  38989. interpolant.__cacheIndex = lastActiveIndex;
  38990. interpolants[ lastActiveIndex ] = interpolant;
  38991. }
  38992. return interpolant;
  38993. }
  38994. _takeBackControlInterpolant( interpolant ) {
  38995. const interpolants = this._controlInterpolants,
  38996. prevIndex = interpolant.__cacheIndex,
  38997. firstInactiveIndex = -- this._nActiveControlInterpolants,
  38998. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  38999. interpolant.__cacheIndex = firstInactiveIndex;
  39000. interpolants[ firstInactiveIndex ] = interpolant;
  39001. lastActiveInterpolant.__cacheIndex = prevIndex;
  39002. interpolants[ prevIndex ] = lastActiveInterpolant;
  39003. }
  39004. /**
  39005. * Returns an instance of {@link AnimationAction} for the passed clip.
  39006. *
  39007. * If an action fitting the clip and root parameters doesn't yet exist, it
  39008. * will be created by this method. Calling this method several times with the
  39009. * same clip and root parameters always returns the same action.
  39010. *
  39011. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39012. * @param {Object3D} [optionalRoot] - An alternative root object.
  39013. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39014. * @return {?AnimationAction} The animation action.
  39015. */
  39016. clipAction( clip, optionalRoot, blendMode ) {
  39017. const root = optionalRoot || this._root,
  39018. rootUuid = root.uuid;
  39019. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39020. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39021. const actionsForClip = this._actionsByClip[ clipUuid ];
  39022. let prototypeAction = null;
  39023. if ( blendMode === undefined ) {
  39024. if ( clipObject !== null ) {
  39025. blendMode = clipObject.blendMode;
  39026. } else {
  39027. blendMode = NormalAnimationBlendMode;
  39028. }
  39029. }
  39030. if ( actionsForClip !== undefined ) {
  39031. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39032. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39033. return existingAction;
  39034. }
  39035. // we know the clip, so we don't have to parse all
  39036. // the bindings again but can just copy
  39037. prototypeAction = actionsForClip.knownActions[ 0 ];
  39038. // also, take the clip from the prototype action
  39039. if ( clipObject === null )
  39040. clipObject = prototypeAction._clip;
  39041. }
  39042. // clip must be known when specified via string
  39043. if ( clipObject === null ) return null;
  39044. // allocate all resources required to run it
  39045. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39046. this._bindAction( newAction, prototypeAction );
  39047. // and make the action known to the memory manager
  39048. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39049. return newAction;
  39050. }
  39051. /**
  39052. * Returns an existing animation action for the passed clip.
  39053. *
  39054. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39055. * @param {Object3D} [optionalRoot] - An alternative root object.
  39056. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39057. */
  39058. existingAction( clip, optionalRoot ) {
  39059. const root = optionalRoot || this._root,
  39060. rootUuid = root.uuid,
  39061. clipObject = typeof clip === 'string' ?
  39062. AnimationClip.findByName( root, clip ) : clip,
  39063. clipUuid = clipObject ? clipObject.uuid : clip,
  39064. actionsForClip = this._actionsByClip[ clipUuid ];
  39065. if ( actionsForClip !== undefined ) {
  39066. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39067. }
  39068. return null;
  39069. }
  39070. /**
  39071. * Deactivates all previously scheduled actions on this mixer.
  39072. *
  39073. * @return {AnimationMixer} A reference to thi animation mixer.
  39074. */
  39075. stopAllAction() {
  39076. const actions = this._actions,
  39077. nActions = this._nActiveActions;
  39078. for ( let i = nActions - 1; i >= 0; -- i ) {
  39079. actions[ i ].stop();
  39080. }
  39081. return this;
  39082. }
  39083. /**
  39084. * Advances the global mixer time and updates the animation.
  39085. *
  39086. * This is usually done in the render loop by passing the delta
  39087. * time from {@link Clock} or {@link Timer}.
  39088. *
  39089. * @param {number} deltaTime - The delta time in seconds.
  39090. * @return {AnimationMixer} A reference to thi animation mixer.
  39091. */
  39092. update( deltaTime ) {
  39093. deltaTime *= this.timeScale;
  39094. const actions = this._actions,
  39095. nActions = this._nActiveActions,
  39096. time = this.time += deltaTime,
  39097. timeDirection = Math.sign( deltaTime ),
  39098. accuIndex = this._accuIndex ^= 1;
  39099. // run active actions
  39100. for ( let i = 0; i !== nActions; ++ i ) {
  39101. const action = actions[ i ];
  39102. action._update( time, deltaTime, timeDirection, accuIndex );
  39103. }
  39104. // update scene graph
  39105. const bindings = this._bindings,
  39106. nBindings = this._nActiveBindings;
  39107. for ( let i = 0; i !== nBindings; ++ i ) {
  39108. bindings[ i ].apply( accuIndex );
  39109. }
  39110. return this;
  39111. }
  39112. /**
  39113. * Sets the global mixer to a specific time and updates the animation accordingly.
  39114. *
  39115. * This is useful when you need to jump to an exact time in an animation. The
  39116. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39117. *
  39118. * @param {number} time - The time to set in seconds.
  39119. * @return {AnimationMixer} A reference to thi animation mixer.
  39120. */
  39121. setTime( time ) {
  39122. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39123. for ( let i = 0; i < this._actions.length; i ++ ) {
  39124. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39125. }
  39126. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39127. }
  39128. /**
  39129. * Returns this mixer's root object.
  39130. *
  39131. * @return {Object3D} The mixer's root object.
  39132. */
  39133. getRoot() {
  39134. return this._root;
  39135. }
  39136. /**
  39137. * Deallocates all memory resources for a clip. Before using this method make
  39138. * sure to call {@link AnimationAction#stop} for all related actions.
  39139. *
  39140. * @param {AnimationClip} clip - The clip to uncache.
  39141. */
  39142. uncacheClip( clip ) {
  39143. const actions = this._actions,
  39144. clipUuid = clip.uuid,
  39145. actionsByClip = this._actionsByClip,
  39146. actionsForClip = actionsByClip[ clipUuid ];
  39147. if ( actionsForClip !== undefined ) {
  39148. // note: just calling _removeInactiveAction would mess up the
  39149. // iteration state and also require updating the state we can
  39150. // just throw away
  39151. const actionsToRemove = actionsForClip.knownActions;
  39152. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39153. const action = actionsToRemove[ i ];
  39154. this._deactivateAction( action );
  39155. const cacheIndex = action._cacheIndex,
  39156. lastInactiveAction = actions[ actions.length - 1 ];
  39157. action._cacheIndex = null;
  39158. action._byClipCacheIndex = null;
  39159. lastInactiveAction._cacheIndex = cacheIndex;
  39160. actions[ cacheIndex ] = lastInactiveAction;
  39161. actions.pop();
  39162. this._removeInactiveBindingsForAction( action );
  39163. }
  39164. delete actionsByClip[ clipUuid ];
  39165. }
  39166. }
  39167. /**
  39168. * Deallocates all memory resources for a root object. Before using this
  39169. * method make sure to call {@link AnimationAction#stop} for all related
  39170. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39171. * mixer operates on a single root.
  39172. *
  39173. * @param {Object3D} root - The root object to uncache.
  39174. */
  39175. uncacheRoot( root ) {
  39176. const rootUuid = root.uuid,
  39177. actionsByClip = this._actionsByClip;
  39178. for ( const clipUuid in actionsByClip ) {
  39179. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39180. action = actionByRoot[ rootUuid ];
  39181. if ( action !== undefined ) {
  39182. this._deactivateAction( action );
  39183. this._removeInactiveAction( action );
  39184. }
  39185. }
  39186. const bindingsByRoot = this._bindingsByRootAndName,
  39187. bindingByName = bindingsByRoot[ rootUuid ];
  39188. if ( bindingByName !== undefined ) {
  39189. for ( const trackName in bindingByName ) {
  39190. const binding = bindingByName[ trackName ];
  39191. binding.restoreOriginalState();
  39192. this._removeInactiveBinding( binding );
  39193. }
  39194. }
  39195. }
  39196. /**
  39197. * Deallocates all memory resources for an action. The action is identified by the
  39198. * given clip and an optional root object. Before using this method make
  39199. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39200. *
  39201. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39202. * @param {Object3D} [optionalRoot] - An alternative root object.
  39203. */
  39204. uncacheAction( clip, optionalRoot ) {
  39205. const action = this.existingAction( clip, optionalRoot );
  39206. if ( action !== null ) {
  39207. this._deactivateAction( action );
  39208. this._removeInactiveAction( action );
  39209. }
  39210. }
  39211. }
  39212. /**
  39213. * Represents a 3D render target.
  39214. *
  39215. * @augments RenderTarget
  39216. */
  39217. class RenderTarget3D extends RenderTarget {
  39218. /**
  39219. * Constructs a new 3D render target.
  39220. *
  39221. * @param {number} [width=1] - The width of the render target.
  39222. * @param {number} [height=1] - The height of the render target.
  39223. * @param {number} [depth=1] - The height of the render target.
  39224. * @param {RenderTarget~Options} [options] - The configuration object.
  39225. */
  39226. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39227. super( width, height, options );
  39228. /**
  39229. * This flag can be used for type testing.
  39230. *
  39231. * @type {boolean}
  39232. * @readonly
  39233. * @default true
  39234. */
  39235. this.isRenderTarget3D = true;
  39236. this.depth = depth;
  39237. /**
  39238. * Overwritten with a different texture type.
  39239. *
  39240. * @type {Data3DTexture}
  39241. */
  39242. this.texture = new Data3DTexture( null, width, height, depth );
  39243. this._setTextureOptions( options );
  39244. this.texture.isRenderTargetTexture = true;
  39245. }
  39246. }
  39247. /**
  39248. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39249. *
  39250. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39251. * ```js
  39252. * uniforms: {
  39253. * time: { value: 1.0 },
  39254. * resolution: new Uniform( new Vector2() )
  39255. * };
  39256. * ```
  39257. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39258. * in {@link WebGLRenderer}.
  39259. */
  39260. class Uniform {
  39261. /**
  39262. * Constructs a new uniform.
  39263. *
  39264. * @param {any} value - The uniform value.
  39265. */
  39266. constructor( value ) {
  39267. /**
  39268. * The uniform value.
  39269. *
  39270. * @type {any}
  39271. */
  39272. this.value = value;
  39273. }
  39274. /**
  39275. * Returns a new uniform with copied values from this instance.
  39276. * If the value has a `clone()` method, the value is cloned as well.
  39277. *
  39278. * @return {Uniform} A clone of this instance.
  39279. */
  39280. clone() {
  39281. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39282. }
  39283. }
  39284. let _id$1 = 0;
  39285. /**
  39286. * A class for managing multiple uniforms in a single group. The renderer will process
  39287. * such a definition as a single UBO.
  39288. *
  39289. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39290. * in {@link WebGLRenderer}.
  39291. *
  39292. * @augments EventDispatcher
  39293. */
  39294. class UniformsGroup extends EventDispatcher {
  39295. /**
  39296. * Constructs a new uniforms group.
  39297. */
  39298. constructor() {
  39299. super();
  39300. /**
  39301. * This flag can be used for type testing.
  39302. *
  39303. * @type {boolean}
  39304. * @readonly
  39305. * @default true
  39306. */
  39307. this.isUniformsGroup = true;
  39308. /**
  39309. * The ID of the 3D object.
  39310. *
  39311. * @name UniformsGroup#id
  39312. * @type {number}
  39313. * @readonly
  39314. */
  39315. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39316. /**
  39317. * The name of the uniforms group.
  39318. *
  39319. * @type {string}
  39320. */
  39321. this.name = '';
  39322. /**
  39323. * The buffer usage.
  39324. *
  39325. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39326. * @default StaticDrawUsage
  39327. */
  39328. this.usage = StaticDrawUsage;
  39329. /**
  39330. * An array holding the uniforms.
  39331. *
  39332. * @type {Array<Uniform>}
  39333. */
  39334. this.uniforms = [];
  39335. }
  39336. /**
  39337. * Adds the given uniform to this uniforms group.
  39338. *
  39339. * @param {Uniform} uniform - The uniform to add.
  39340. * @return {UniformsGroup} A reference to this uniforms group.
  39341. */
  39342. add( uniform ) {
  39343. this.uniforms.push( uniform );
  39344. return this;
  39345. }
  39346. /**
  39347. * Removes the given uniform from this uniforms group.
  39348. *
  39349. * @param {Uniform} uniform - The uniform to remove.
  39350. * @return {UniformsGroup} A reference to this uniforms group.
  39351. */
  39352. remove( uniform ) {
  39353. const index = this.uniforms.indexOf( uniform );
  39354. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39355. return this;
  39356. }
  39357. /**
  39358. * Sets the name of this uniforms group.
  39359. *
  39360. * @param {string} name - The name to set.
  39361. * @return {UniformsGroup} A reference to this uniforms group.
  39362. */
  39363. setName( name ) {
  39364. this.name = name;
  39365. return this;
  39366. }
  39367. /**
  39368. * Sets the usage of this uniforms group.
  39369. *
  39370. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39371. * @return {UniformsGroup} A reference to this uniforms group.
  39372. */
  39373. setUsage( value ) {
  39374. this.usage = value;
  39375. return this;
  39376. }
  39377. /**
  39378. * Frees the GPU-related resources allocated by this instance. Call this
  39379. * method whenever this instance is no longer used in your app.
  39380. *
  39381. * @fires Texture#dispose
  39382. */
  39383. dispose() {
  39384. this.dispatchEvent( { type: 'dispose' } );
  39385. }
  39386. /**
  39387. * Copies the values of the given uniforms group to this instance.
  39388. *
  39389. * @param {UniformsGroup} source - The uniforms group to copy.
  39390. * @return {UniformsGroup} A reference to this uniforms group.
  39391. */
  39392. copy( source ) {
  39393. this.name = source.name;
  39394. this.usage = source.usage;
  39395. const uniformsSource = source.uniforms;
  39396. this.uniforms.length = 0;
  39397. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39398. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39399. for ( let j = 0; j < uniforms.length; j ++ ) {
  39400. this.uniforms.push( uniforms[ j ].clone() );
  39401. }
  39402. }
  39403. return this;
  39404. }
  39405. /**
  39406. * Returns a new uniforms group with copied values from this instance.
  39407. *
  39408. * @return {UniformsGroup} A clone of this instance.
  39409. */
  39410. clone() {
  39411. return new this.constructor().copy( this );
  39412. }
  39413. }
  39414. /**
  39415. * An instanced version of an interleaved buffer.
  39416. *
  39417. * @augments InterleavedBuffer
  39418. */
  39419. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39420. /**
  39421. * Constructs a new instanced interleaved buffer.
  39422. *
  39423. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39424. * @param {number} stride - The number of typed-array elements per vertex.
  39425. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39426. */
  39427. constructor( array, stride, meshPerAttribute = 1 ) {
  39428. super( array, stride );
  39429. /**
  39430. * This flag can be used for type testing.
  39431. *
  39432. * @type {boolean}
  39433. * @readonly
  39434. * @default true
  39435. */
  39436. this.isInstancedInterleavedBuffer = true;
  39437. /**
  39438. * Defines how often a value of this buffer attribute should be repeated,
  39439. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39440. *
  39441. * @type {number}
  39442. * @default 1
  39443. */
  39444. this.meshPerAttribute = meshPerAttribute;
  39445. }
  39446. copy( source ) {
  39447. super.copy( source );
  39448. this.meshPerAttribute = source.meshPerAttribute;
  39449. return this;
  39450. }
  39451. clone( data ) {
  39452. const ib = super.clone( data );
  39453. ib.meshPerAttribute = this.meshPerAttribute;
  39454. return ib;
  39455. }
  39456. toJSON( data ) {
  39457. const json = super.toJSON( data );
  39458. json.isInstancedInterleavedBuffer = true;
  39459. json.meshPerAttribute = this.meshPerAttribute;
  39460. return json;
  39461. }
  39462. }
  39463. /**
  39464. * An alternative version of a buffer attribute with more control over the VBO.
  39465. *
  39466. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39467. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39468. *
  39469. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39470. * or even produces the VBOs in question.
  39471. *
  39472. * Notice that this class can only be used with {@link WebGLRenderer}.
  39473. */
  39474. class GLBufferAttribute {
  39475. /**
  39476. * Constructs a new GL buffer attribute.
  39477. *
  39478. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39479. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39480. * @param {number} itemSize - The item size.
  39481. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39482. * @param {number} count - The expected number of vertices in VBO.
  39483. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39484. */
  39485. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39486. /**
  39487. * This flag can be used for type testing.
  39488. *
  39489. * @type {boolean}
  39490. * @readonly
  39491. * @default true
  39492. */
  39493. this.isGLBufferAttribute = true;
  39494. /**
  39495. * The name of the buffer attribute.
  39496. *
  39497. * @type {string}
  39498. */
  39499. this.name = '';
  39500. /**
  39501. * The native WebGL buffer.
  39502. *
  39503. * @type {WebGLBuffer}
  39504. */
  39505. this.buffer = buffer;
  39506. /**
  39507. * The native data type.
  39508. *
  39509. * @type {number}
  39510. */
  39511. this.type = type;
  39512. /**
  39513. * The item size, see {@link BufferAttribute#itemSize}.
  39514. *
  39515. * @type {number}
  39516. */
  39517. this.itemSize = itemSize;
  39518. /**
  39519. * The corresponding size (in bytes) for the given `type` parameter.
  39520. *
  39521. * @type {number}
  39522. */
  39523. this.elementSize = elementSize;
  39524. /**
  39525. * The expected number of vertices in VBO.
  39526. *
  39527. * @type {number}
  39528. */
  39529. this.count = count;
  39530. /**
  39531. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39532. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39533. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39534. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39535. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39536. *
  39537. * @type {boolean}
  39538. */
  39539. this.normalized = normalized;
  39540. /**
  39541. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39542. *
  39543. * @type {number}
  39544. */
  39545. this.version = 0;
  39546. }
  39547. /**
  39548. * Flag to indicate that this attribute has changed and should be re-sent to
  39549. * the GPU. Set this to `true` when you modify the value of the array.
  39550. *
  39551. * @type {number}
  39552. * @default false
  39553. * @param {boolean} value
  39554. */
  39555. set needsUpdate( value ) {
  39556. if ( value === true ) this.version ++;
  39557. }
  39558. /**
  39559. * Sets the given native WebGL buffer.
  39560. *
  39561. * @param {WebGLBuffer} buffer - The buffer to set.
  39562. * @return {BufferAttribute} A reference to this instance.
  39563. */
  39564. setBuffer( buffer ) {
  39565. this.buffer = buffer;
  39566. return this;
  39567. }
  39568. /**
  39569. * Sets the given native data type and element size.
  39570. *
  39571. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39572. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39573. * @return {BufferAttribute} A reference to this instance.
  39574. */
  39575. setType( type, elementSize ) {
  39576. this.type = type;
  39577. this.elementSize = elementSize;
  39578. return this;
  39579. }
  39580. /**
  39581. * Sets the item size.
  39582. *
  39583. * @param {number} itemSize - The item size.
  39584. * @return {BufferAttribute} A reference to this instance.
  39585. */
  39586. setItemSize( itemSize ) {
  39587. this.itemSize = itemSize;
  39588. return this;
  39589. }
  39590. /**
  39591. * Sets the count (the expected number of vertices in VBO).
  39592. *
  39593. * @param {number} count - The count.
  39594. * @return {BufferAttribute} A reference to this instance.
  39595. */
  39596. setCount( count ) {
  39597. this.count = count;
  39598. return this;
  39599. }
  39600. }
  39601. const _matrix = /*@__PURE__*/ new Matrix4();
  39602. /**
  39603. * This class is designed to assist with raycasting. Raycasting is used for
  39604. * mouse picking (working out what objects in the 3d space the mouse is over)
  39605. * amongst other things.
  39606. */
  39607. class Raycaster {
  39608. /**
  39609. * Constructs a new raycaster.
  39610. *
  39611. * @param {Vector3} origin - The origin vector where the ray casts from.
  39612. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39613. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39614. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39615. */
  39616. constructor( origin, direction, near = 0, far = Infinity ) {
  39617. /**
  39618. * The ray used for raycasting.
  39619. *
  39620. * @type {Ray}
  39621. */
  39622. this.ray = new Ray( origin, direction );
  39623. /**
  39624. * All results returned are further away than near. Near can't be negative.
  39625. *
  39626. * @type {number}
  39627. * @default 0
  39628. */
  39629. this.near = near;
  39630. /**
  39631. * All results returned are further away than near. Near can't be negative.
  39632. *
  39633. * @type {number}
  39634. * @default Infinity
  39635. */
  39636. this.far = far;
  39637. /**
  39638. * The camera to use when raycasting against view-dependent objects such as
  39639. * billboarded objects like sprites. This field can be set manually or
  39640. * is set when calling `setFromCamera()`.
  39641. *
  39642. * @type {?Camera}
  39643. * @default null
  39644. */
  39645. this.camera = null;
  39646. /**
  39647. * Allows to selectively ignore 3D objects when performing intersection tests.
  39648. * The following code example ensures that only 3D objects on layer `1` will be
  39649. * honored by raycaster.
  39650. * ```js
  39651. * raycaster.layers.set( 1 );
  39652. * object.layers.enable( 1 );
  39653. * ```
  39654. *
  39655. * @type {Layers}
  39656. */
  39657. this.layers = new Layers();
  39658. /**
  39659. * A parameter object that configures the raycasting. It has the structure:
  39660. *
  39661. * ```
  39662. * {
  39663. * Mesh: {},
  39664. * Line: { threshold: 1 },
  39665. * LOD: {},
  39666. * Points: { threshold: 1 },
  39667. * Sprite: {}
  39668. * }
  39669. * ```
  39670. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39671. *
  39672. * @type {Object}
  39673. */
  39674. this.params = {
  39675. Mesh: {},
  39676. Line: { threshold: 1 },
  39677. LOD: {},
  39678. Points: { threshold: 1 },
  39679. Sprite: {}
  39680. };
  39681. }
  39682. /**
  39683. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39684. *
  39685. * @param {Vector3} origin - The origin vector where the ray casts from.
  39686. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39687. */
  39688. set( origin, direction ) {
  39689. // direction is assumed to be normalized (for accurate distance calculations)
  39690. this.ray.set( origin, direction );
  39691. }
  39692. /**
  39693. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39694. *
  39695. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39696. * X and Y components should be between `-1` and `1`.
  39697. * @param {Camera} camera - The camera from which the ray should originate.
  39698. */
  39699. setFromCamera( coords, camera ) {
  39700. if ( camera.isPerspectiveCamera ) {
  39701. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39702. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39703. this.camera = camera;
  39704. } else if ( camera.isOrthographicCamera ) {
  39705. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39706. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39707. this.camera = camera;
  39708. } else {
  39709. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39710. }
  39711. }
  39712. /**
  39713. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39714. *
  39715. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39716. * @return {Raycaster} A reference to this raycaster.
  39717. */
  39718. setFromXRController( controller ) {
  39719. _matrix.identity().extractRotation( controller.matrixWorld );
  39720. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39721. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39722. return this;
  39723. }
  39724. /**
  39725. * The intersection point of a raycaster intersection test.
  39726. * @typedef {Object} Raycaster~Intersection
  39727. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39728. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39729. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39730. * @property {Vector3} point - The intersection point, in world coordinates.
  39731. * @property {Object} face - The face that has been intersected.
  39732. * @property {number} faceIndex - The face index.
  39733. * @property {Object3D} object - The 3D object that has been intersected.
  39734. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39735. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39736. * @property {Vector3} uv1 - Interpolated normal vector at point of intersection.
  39737. * @property {number} instanceId - The index number of the instance where the ray
  39738. * intersects the {@link InstancedMesh}.
  39739. */
  39740. /**
  39741. * Checks all intersection between the ray and the object with or without the
  39742. * descendants. Intersections are returned sorted by distance, closest first.
  39743. *
  39744. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39745. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39746. * differently to ray casting than lines or points.
  39747. *
  39748. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39749. * to be detected; intersections of the ray passing through the back of a face will not
  39750. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39751. * to `THREE.DoubleSide`.
  39752. *
  39753. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39754. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39755. * Otherwise it only checks intersection with the object.
  39756. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39757. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39758. */
  39759. intersectObject( object, recursive = true, intersects = [] ) {
  39760. intersect( object, this, intersects, recursive );
  39761. intersects.sort( ascSort );
  39762. return intersects;
  39763. }
  39764. /**
  39765. * Checks all intersection between the ray and the objects with or without
  39766. * the descendants. Intersections are returned sorted by distance, closest first.
  39767. *
  39768. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39769. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39770. * Otherwise it only checks intersection with the object.
  39771. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39772. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39773. */
  39774. intersectObjects( objects, recursive = true, intersects = [] ) {
  39775. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39776. intersect( objects[ i ], this, intersects, recursive );
  39777. }
  39778. intersects.sort( ascSort );
  39779. return intersects;
  39780. }
  39781. }
  39782. function ascSort( a, b ) {
  39783. return a.distance - b.distance;
  39784. }
  39785. function intersect( object, raycaster, intersects, recursive ) {
  39786. let propagate = true;
  39787. if ( object.layers.test( raycaster.layers ) ) {
  39788. const result = object.raycast( raycaster, intersects );
  39789. if ( result === false ) propagate = false;
  39790. }
  39791. if ( propagate === true && recursive === true ) {
  39792. const children = object.children;
  39793. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39794. intersect( children[ i ], raycaster, intersects, true );
  39795. }
  39796. }
  39797. }
  39798. /**
  39799. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39800. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39801. *
  39802. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39803. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39804. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39805. * is inactive (e.g. tab switched or browser hidden).
  39806. *
  39807. * ```js
  39808. * const timer = new Timer();
  39809. * timer.connect( document ); // use Page Visibility API
  39810. * ```
  39811. */
  39812. class Timer {
  39813. /**
  39814. * Constructs a new timer.
  39815. */
  39816. constructor() {
  39817. this._previousTime = 0;
  39818. this._currentTime = 0;
  39819. this._startTime = performance.now();
  39820. this._delta = 0;
  39821. this._elapsed = 0;
  39822. this._timescale = 1;
  39823. this._document = null;
  39824. this._pageVisibilityHandler = null;
  39825. }
  39826. /**
  39827. * Connect the timer to the given document.Calling this method is not mandatory to
  39828. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39829. * delta values.
  39830. *
  39831. * @param {Document} document - The document.
  39832. */
  39833. connect( document ) {
  39834. this._document = document;
  39835. // use Page Visibility API to avoid large time delta values
  39836. if ( document.hidden !== undefined ) {
  39837. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  39838. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  39839. }
  39840. }
  39841. /**
  39842. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  39843. */
  39844. disconnect() {
  39845. if ( this._pageVisibilityHandler !== null ) {
  39846. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  39847. this._pageVisibilityHandler = null;
  39848. }
  39849. this._document = null;
  39850. }
  39851. /**
  39852. * Returns the time delta in seconds.
  39853. *
  39854. * @return {number} The time delta in second.
  39855. */
  39856. getDelta() {
  39857. return this._delta / 1000;
  39858. }
  39859. /**
  39860. * Returns the elapsed time in seconds.
  39861. *
  39862. * @return {number} The elapsed time in second.
  39863. */
  39864. getElapsed() {
  39865. return this._elapsed / 1000;
  39866. }
  39867. /**
  39868. * Returns the timescale.
  39869. *
  39870. * @return {number} The timescale.
  39871. */
  39872. getTimescale() {
  39873. return this._timescale;
  39874. }
  39875. /**
  39876. * Sets the given timescale which scale the time delta computation
  39877. * in `update()`.
  39878. *
  39879. * @param {number} timescale - The timescale to set.
  39880. * @return {Timer} A reference to this timer.
  39881. */
  39882. setTimescale( timescale ) {
  39883. this._timescale = timescale;
  39884. return this;
  39885. }
  39886. /**
  39887. * Resets the time computation for the current simulation step.
  39888. *
  39889. * @return {Timer} A reference to this timer.
  39890. */
  39891. reset() {
  39892. this._currentTime = performance.now() - this._startTime;
  39893. return this;
  39894. }
  39895. /**
  39896. * Can be used to free all internal resources. Usually called when
  39897. * the timer instance isn't required anymore.
  39898. */
  39899. dispose() {
  39900. this.disconnect();
  39901. }
  39902. /**
  39903. * Updates the internal state of the timer. This method should be called
  39904. * once per simulation step and before you perform queries against the timer
  39905. * (e.g. via `getDelta()`).
  39906. *
  39907. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  39908. * from the `requestAnimationFrame` callback argument. If not provided, the current
  39909. * time will be determined with `performance.now`.
  39910. * @return {Timer} A reference to this timer.
  39911. */
  39912. update( timestamp ) {
  39913. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  39914. this._delta = 0;
  39915. } else {
  39916. this._previousTime = this._currentTime;
  39917. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  39918. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  39919. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  39920. }
  39921. return this;
  39922. }
  39923. }
  39924. function handleVisibilityChange() {
  39925. if ( this._document.hidden === false ) this.reset();
  39926. }
  39927. /**
  39928. * This class can be used to represent points in 3D space as
  39929. * [Spherical coordinates]{@link https://en.wikipedia.org/wiki/Spherical_coordinate_system}.
  39930. */
  39931. class Spherical {
  39932. /**
  39933. * Constructs a new spherical.
  39934. *
  39935. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39936. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  39937. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  39938. */
  39939. constructor( radius = 1, phi = 0, theta = 0 ) {
  39940. /**
  39941. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  39942. *
  39943. * @type {number}
  39944. * @default 1
  39945. */
  39946. this.radius = radius;
  39947. /**
  39948. * The polar angle in radians from the y (up) axis.
  39949. *
  39950. * @type {number}
  39951. * @default 0
  39952. */
  39953. this.phi = phi;
  39954. /**
  39955. * The equator/azimuthal angle in radians around the y (up) axis.
  39956. *
  39957. * @type {number}
  39958. * @default 0
  39959. */
  39960. this.theta = theta;
  39961. }
  39962. /**
  39963. * Sets the spherical components by copying the given values.
  39964. *
  39965. * @param {number} radius - The radius.
  39966. * @param {number} phi - The polar angle.
  39967. * @param {number} theta - The azimuthal angle.
  39968. * @return {Spherical} A reference to this spherical.
  39969. */
  39970. set( radius, phi, theta ) {
  39971. this.radius = radius;
  39972. this.phi = phi;
  39973. this.theta = theta;
  39974. return this;
  39975. }
  39976. /**
  39977. * Copies the values of the given spherical to this instance.
  39978. *
  39979. * @param {Spherical} other - The spherical to copy.
  39980. * @return {Spherical} A reference to this spherical.
  39981. */
  39982. copy( other ) {
  39983. this.radius = other.radius;
  39984. this.phi = other.phi;
  39985. this.theta = other.theta;
  39986. return this;
  39987. }
  39988. /**
  39989. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  39990. * `0.000001`.
  39991. *
  39992. * @return {Spherical} A reference to this spherical.
  39993. */
  39994. makeSafe() {
  39995. const EPS = 0.000001;
  39996. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  39997. return this;
  39998. }
  39999. /**
  40000. * Sets the spherical components from the given vector which is assumed to hold
  40001. * Cartesian coordinates.
  40002. *
  40003. * @param {Vector3} v - The vector to set.
  40004. * @return {Spherical} A reference to this spherical.
  40005. */
  40006. setFromVector3( v ) {
  40007. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40008. }
  40009. /**
  40010. * Sets the spherical components from the given Cartesian coordinates.
  40011. *
  40012. * @param {number} x - The x value.
  40013. * @param {number} y - The y value.
  40014. * @param {number} z - The z value.
  40015. * @return {Spherical} A reference to this spherical.
  40016. */
  40017. setFromCartesianCoords( x, y, z ) {
  40018. this.radius = Math.sqrt( x * x + y * y + z * z );
  40019. if ( this.radius === 0 ) {
  40020. this.theta = 0;
  40021. this.phi = 0;
  40022. } else {
  40023. this.theta = Math.atan2( x, z );
  40024. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40025. }
  40026. return this;
  40027. }
  40028. /**
  40029. * Returns a new spherical with copied values from this instance.
  40030. *
  40031. * @return {Spherical} A clone of this instance.
  40032. */
  40033. clone() {
  40034. return new this.constructor().copy( this );
  40035. }
  40036. }
  40037. /**
  40038. * This class can be used to represent points in 3D space as
  40039. * [Cylindrical coordinates]{@link https://en.wikipedia.org/wiki/Cylindrical_coordinate_system}.
  40040. */
  40041. class Cylindrical {
  40042. /**
  40043. * Constructs a new cylindrical.
  40044. *
  40045. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40046. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40047. * @param {number} [y=0] - The height above the x-z plane.
  40048. */
  40049. constructor( radius = 1, theta = 0, y = 0 ) {
  40050. /**
  40051. * The distance from the origin to a point in the x-z plane.
  40052. *
  40053. * @type {number}
  40054. * @default 1
  40055. */
  40056. this.radius = radius;
  40057. /**
  40058. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40059. *
  40060. * @type {number}
  40061. * @default 0
  40062. */
  40063. this.theta = theta;
  40064. /**
  40065. * The height above the x-z plane.
  40066. *
  40067. * @type {number}
  40068. * @default 0
  40069. */
  40070. this.y = y;
  40071. }
  40072. /**
  40073. * Sets the cylindrical components by copying the given values.
  40074. *
  40075. * @param {number} radius - The radius.
  40076. * @param {number} theta - The theta angle.
  40077. * @param {number} y - The height value.
  40078. * @return {Cylindrical} A reference to this cylindrical.
  40079. */
  40080. set( radius, theta, y ) {
  40081. this.radius = radius;
  40082. this.theta = theta;
  40083. this.y = y;
  40084. return this;
  40085. }
  40086. /**
  40087. * Copies the values of the given cylindrical to this instance.
  40088. *
  40089. * @param {Cylindrical} other - The cylindrical to copy.
  40090. * @return {Cylindrical} A reference to this cylindrical.
  40091. */
  40092. copy( other ) {
  40093. this.radius = other.radius;
  40094. this.theta = other.theta;
  40095. this.y = other.y;
  40096. return this;
  40097. }
  40098. /**
  40099. * Sets the cylindrical components from the given vector which is assumed to hold
  40100. * Cartesian coordinates.
  40101. *
  40102. * @param {Vector3} v - The vector to set.
  40103. * @return {Cylindrical} A reference to this cylindrical.
  40104. */
  40105. setFromVector3( v ) {
  40106. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40107. }
  40108. /**
  40109. * Sets the cylindrical components from the given Cartesian coordinates.
  40110. *
  40111. * @param {number} x - The x value.
  40112. * @param {number} y - The x value.
  40113. * @param {number} z - The x value.
  40114. * @return {Cylindrical} A reference to this cylindrical.
  40115. */
  40116. setFromCartesianCoords( x, y, z ) {
  40117. this.radius = Math.sqrt( x * x + z * z );
  40118. this.theta = Math.atan2( x, z );
  40119. this.y = y;
  40120. return this;
  40121. }
  40122. /**
  40123. * Returns a new cylindrical with copied values from this instance.
  40124. *
  40125. * @return {Cylindrical} A clone of this instance.
  40126. */
  40127. clone() {
  40128. return new this.constructor().copy( this );
  40129. }
  40130. }
  40131. /**
  40132. * Represents a 2x2 matrix.
  40133. *
  40134. * A Note on Row-Major and Column-Major Ordering:
  40135. *
  40136. * The constructor and {@link Matrix2#set} method take arguments in
  40137. * [row-major]{@link https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order}
  40138. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40139. * This means that calling:
  40140. * ```js
  40141. * const m = new THREE.Matrix2();
  40142. * m.set( 11, 12,
  40143. * 21, 22 );
  40144. * ```
  40145. * will result in the elements array containing:
  40146. * ```js
  40147. * m.elements = [ 11, 21,
  40148. * 12, 22 ];
  40149. * ```
  40150. * and internally all calculations are performed using column-major ordering.
  40151. * However, as the actual ordering makes no difference mathematically and
  40152. * most people are used to thinking about matrices in row-major order, the
  40153. * three.js documentation shows matrices in row-major order. Just bear in
  40154. * mind that if you are reading the source code, you'll have to take the
  40155. * transpose of any matrices outlined here to make sense of the calculations.
  40156. */
  40157. class Matrix2 {
  40158. /**
  40159. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40160. * in row-major order. If no arguments are provided, the constructor
  40161. * initializes the matrix as an identity matrix.
  40162. *
  40163. * @param {number} [n11] - 1-1 matrix element.
  40164. * @param {number} [n12] - 1-2 matrix element.
  40165. * @param {number} [n21] - 2-1 matrix element.
  40166. * @param {number} [n22] - 2-2 matrix element.
  40167. */
  40168. constructor( n11, n12, n21, n22 ) {
  40169. /**
  40170. * This flag can be used for type testing.
  40171. *
  40172. * @type {boolean}
  40173. * @readonly
  40174. * @default true
  40175. */
  40176. Matrix2.prototype.isMatrix2 = true;
  40177. /**
  40178. * A column-major list of matrix values.
  40179. *
  40180. * @type {Array<number>}
  40181. */
  40182. this.elements = [
  40183. 1, 0,
  40184. 0, 1,
  40185. ];
  40186. if ( n11 !== undefined ) {
  40187. this.set( n11, n12, n21, n22 );
  40188. }
  40189. }
  40190. /**
  40191. * Sets this matrix to the 2x2 identity matrix.
  40192. *
  40193. * @return {Matrix2} A reference to this matrix.
  40194. */
  40195. identity() {
  40196. this.set(
  40197. 1, 0,
  40198. 0, 1,
  40199. );
  40200. return this;
  40201. }
  40202. /**
  40203. * Sets the elements of the matrix from the given array.
  40204. *
  40205. * @param {Array<number>} array - The matrix elements in column-major order.
  40206. * @param {number} [offset=0] - Index of the first element in the array.
  40207. * @return {Matrix2} A reference to this matrix.
  40208. */
  40209. fromArray( array, offset = 0 ) {
  40210. for ( let i = 0; i < 4; i ++ ) {
  40211. this.elements[ i ] = array[ i + offset ];
  40212. }
  40213. return this;
  40214. }
  40215. /**
  40216. * Sets the elements of the matrix.The arguments are supposed to be
  40217. * in row-major order.
  40218. *
  40219. * @param {number} n11 - 1-1 matrix element.
  40220. * @param {number} n12 - 1-2 matrix element.
  40221. * @param {number} n21 - 2-1 matrix element.
  40222. * @param {number} n22 - 2-2 matrix element.
  40223. * @return {Matrix2} A reference to this matrix.
  40224. */
  40225. set( n11, n12, n21, n22 ) {
  40226. const te = this.elements;
  40227. te[ 0 ] = n11; te[ 2 ] = n12;
  40228. te[ 1 ] = n21; te[ 3 ] = n22;
  40229. return this;
  40230. }
  40231. }
  40232. const _vector$4 = /*@__PURE__*/ new Vector2();
  40233. /**
  40234. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40235. */
  40236. class Box2 {
  40237. /**
  40238. * Constructs a new bounding box.
  40239. *
  40240. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40241. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40242. */
  40243. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40244. /**
  40245. * This flag can be used for type testing.
  40246. *
  40247. * @type {boolean}
  40248. * @readonly
  40249. * @default true
  40250. */
  40251. this.isBox2 = true;
  40252. /**
  40253. * The lower boundary of the box.
  40254. *
  40255. * @type {Vector2}
  40256. */
  40257. this.min = min;
  40258. /**
  40259. * The upper boundary of the box.
  40260. *
  40261. * @type {Vector2}
  40262. */
  40263. this.max = max;
  40264. }
  40265. /**
  40266. * Sets the lower and upper boundaries of this box.
  40267. * Please note that this method only copies the values from the given objects.
  40268. *
  40269. * @param {Vector2} min - The lower boundary of the box.
  40270. * @param {Vector2} max - The upper boundary of the box.
  40271. * @return {Box2} A reference to this bounding box.
  40272. */
  40273. set( min, max ) {
  40274. this.min.copy( min );
  40275. this.max.copy( max );
  40276. return this;
  40277. }
  40278. /**
  40279. * Sets the upper and lower bounds of this box so it encloses the position data
  40280. * in the given array.
  40281. *
  40282. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40283. * @return {Box2} A reference to this bounding box.
  40284. */
  40285. setFromPoints( points ) {
  40286. this.makeEmpty();
  40287. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40288. this.expandByPoint( points[ i ] );
  40289. }
  40290. return this;
  40291. }
  40292. /**
  40293. * Centers this box on the given center vector and sets this box's width, height and
  40294. * depth to the given size values.
  40295. *
  40296. * @param {Vector2} center - The center of the box.
  40297. * @param {Vector2} size - The x and y dimensions of the box.
  40298. * @return {Box2} A reference to this bounding box.
  40299. */
  40300. setFromCenterAndSize( center, size ) {
  40301. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40302. this.min.copy( center ).sub( halfSize );
  40303. this.max.copy( center ).add( halfSize );
  40304. return this;
  40305. }
  40306. /**
  40307. * Returns a new box with copied values from this instance.
  40308. *
  40309. * @return {Box2} A clone of this instance.
  40310. */
  40311. clone() {
  40312. return new this.constructor().copy( this );
  40313. }
  40314. /**
  40315. * Copies the values of the given box to this instance.
  40316. *
  40317. * @param {Box2} box - The box to copy.
  40318. * @return {Box2} A reference to this bounding box.
  40319. */
  40320. copy( box ) {
  40321. this.min.copy( box.min );
  40322. this.max.copy( box.max );
  40323. return this;
  40324. }
  40325. /**
  40326. * Makes this box empty which means in encloses a zero space in 2D.
  40327. *
  40328. * @return {Box2} A reference to this bounding box.
  40329. */
  40330. makeEmpty() {
  40331. this.min.x = this.min.y = + Infinity;
  40332. this.max.x = this.max.y = - Infinity;
  40333. return this;
  40334. }
  40335. /**
  40336. * Returns true if this box includes zero points within its bounds.
  40337. * Note that a box with equal lower and upper bounds still includes one
  40338. * point, the one both bounds share.
  40339. *
  40340. * @return {boolean} Whether this box is empty or not.
  40341. */
  40342. isEmpty() {
  40343. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40344. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40345. }
  40346. /**
  40347. * Returns the center point of this box.
  40348. *
  40349. * @param {Vector2} target - The target vector that is used to store the method's result.
  40350. * @return {Vector2} The center point.
  40351. */
  40352. getCenter( target ) {
  40353. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40354. }
  40355. /**
  40356. * Returns the dimensions of this box.
  40357. *
  40358. * @param {Vector2} target - The target vector that is used to store the method's result.
  40359. * @return {Vector2} The size.
  40360. */
  40361. getSize( target ) {
  40362. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40363. }
  40364. /**
  40365. * Expands the boundaries of this box to include the given point.
  40366. *
  40367. * @param {Vector2} point - The point that should be included by the bounding box.
  40368. * @return {Box2} A reference to this bounding box.
  40369. */
  40370. expandByPoint( point ) {
  40371. this.min.min( point );
  40372. this.max.max( point );
  40373. return this;
  40374. }
  40375. /**
  40376. * Expands this box equilaterally by the given vector. The width of this
  40377. * box will be expanded by the x component of the vector in both
  40378. * directions. The height of this box will be expanded by the y component of
  40379. * the vector in both directions.
  40380. *
  40381. * @param {Vector2} vector - The vector that should expand the bounding box.
  40382. * @return {Box2} A reference to this bounding box.
  40383. */
  40384. expandByVector( vector ) {
  40385. this.min.sub( vector );
  40386. this.max.add( vector );
  40387. return this;
  40388. }
  40389. /**
  40390. * Expands each dimension of the box by the given scalar. If negative, the
  40391. * dimensions of the box will be contracted.
  40392. *
  40393. * @param {number} scalar - The scalar value that should expand the bounding box.
  40394. * @return {Box2} A reference to this bounding box.
  40395. */
  40396. expandByScalar( scalar ) {
  40397. this.min.addScalar( - scalar );
  40398. this.max.addScalar( scalar );
  40399. return this;
  40400. }
  40401. /**
  40402. * Returns `true` if the given point lies within or on the boundaries of this box.
  40403. *
  40404. * @param {Vector2} point - The point to test.
  40405. * @return {boolean} Whether the bounding box contains the given point or not.
  40406. */
  40407. containsPoint( point ) {
  40408. return point.x >= this.min.x && point.x <= this.max.x &&
  40409. point.y >= this.min.y && point.y <= this.max.y;
  40410. }
  40411. /**
  40412. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40413. * If this box and the given one are identical, this function also returns `true`.
  40414. *
  40415. * @param {Box2} box - The bounding box to test.
  40416. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40417. */
  40418. containsBox( box ) {
  40419. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40420. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40421. }
  40422. /**
  40423. * Returns a point as a proportion of this box's width and height.
  40424. *
  40425. * @param {Vector2} point - A point in 2D space.
  40426. * @param {Vector2} target - The target vector that is used to store the method's result.
  40427. * @return {Vector2} A point as a proportion of this box's width and height.
  40428. */
  40429. getParameter( point, target ) {
  40430. // This can potentially have a divide by zero if the box
  40431. // has a size dimension of 0.
  40432. return target.set(
  40433. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40434. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40435. );
  40436. }
  40437. /**
  40438. * Returns `true` if the given bounding box intersects with this bounding box.
  40439. *
  40440. * @param {Box2} box - The bounding box to test.
  40441. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40442. */
  40443. intersectsBox( box ) {
  40444. // using 4 splitting planes to rule out intersections
  40445. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40446. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40447. }
  40448. /**
  40449. * Clamps the given point within the bounds of this box.
  40450. *
  40451. * @param {Vector2} point - The point to clamp.
  40452. * @param {Vector2} target - The target vector that is used to store the method's result.
  40453. * @return {Vector2} The clamped point.
  40454. */
  40455. clampPoint( point, target ) {
  40456. return target.copy( point ).clamp( this.min, this.max );
  40457. }
  40458. /**
  40459. * Returns the euclidean distance from any edge of this box to the specified point. If
  40460. * the given point lies inside of this box, the distance will be `0`.
  40461. *
  40462. * @param {Vector2} point - The point to compute the distance to.
  40463. * @return {number} The euclidean distance.
  40464. */
  40465. distanceToPoint( point ) {
  40466. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40467. }
  40468. /**
  40469. * Computes the intersection of this bounding box and the given one, setting the upper
  40470. * bound of this box to the lesser of the two boxes' upper bounds and the
  40471. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40472. * there's no overlap, makes this box empty.
  40473. *
  40474. * @param {Box2} box - The bounding box to intersect with.
  40475. * @return {Box2} A reference to this bounding box.
  40476. */
  40477. intersect( box ) {
  40478. this.min.max( box.min );
  40479. this.max.min( box.max );
  40480. if ( this.isEmpty() ) this.makeEmpty();
  40481. return this;
  40482. }
  40483. /**
  40484. * Computes the union of this box and another and the given one, setting the upper
  40485. * bound of this box to the greater of the two boxes' upper bounds and the
  40486. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40487. *
  40488. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40489. * @return {Box2} A reference to this bounding box.
  40490. */
  40491. union( box ) {
  40492. this.min.min( box.min );
  40493. this.max.max( box.max );
  40494. return this;
  40495. }
  40496. /**
  40497. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40498. * effectively moving it in 2D space.
  40499. *
  40500. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40501. * @return {Box2} A reference to this bounding box.
  40502. */
  40503. translate( offset ) {
  40504. this.min.add( offset );
  40505. this.max.add( offset );
  40506. return this;
  40507. }
  40508. /**
  40509. * Returns `true` if this bounding box is equal with the given one.
  40510. *
  40511. * @param {Box2} box - The box to test for equality.
  40512. * @return {boolean} Whether this bounding box is equal with the given one.
  40513. */
  40514. equals( box ) {
  40515. return box.min.equals( this.min ) && box.max.equals( this.max );
  40516. }
  40517. }
  40518. const _startP = /*@__PURE__*/ new Vector3();
  40519. const _startEnd = /*@__PURE__*/ new Vector3();
  40520. const _d1 = /*@__PURE__*/ new Vector3();
  40521. const _d2 = /*@__PURE__*/ new Vector3();
  40522. const _r = /*@__PURE__*/ new Vector3();
  40523. const _c1 = /*@__PURE__*/ new Vector3();
  40524. const _c2 = /*@__PURE__*/ new Vector3();
  40525. /**
  40526. * An analytical line segment in 3D space represented by a start and end point.
  40527. */
  40528. class Line3 {
  40529. /**
  40530. * Constructs a new line segment.
  40531. *
  40532. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40533. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40534. */
  40535. constructor( start = new Vector3(), end = new Vector3() ) {
  40536. /**
  40537. * Start of the line segment.
  40538. *
  40539. * @type {Vector3}
  40540. */
  40541. this.start = start;
  40542. /**
  40543. * End of the line segment.
  40544. *
  40545. * @type {Vector3}
  40546. */
  40547. this.end = end;
  40548. }
  40549. /**
  40550. * Sets the start and end values by copying the given vectors.
  40551. *
  40552. * @param {Vector3} start - The start point.
  40553. * @param {Vector3} end - The end point.
  40554. * @return {Line3} A reference to this line segment.
  40555. */
  40556. set( start, end ) {
  40557. this.start.copy( start );
  40558. this.end.copy( end );
  40559. return this;
  40560. }
  40561. /**
  40562. * Copies the values of the given line segment to this instance.
  40563. *
  40564. * @param {Line3} line - The line segment to copy.
  40565. * @return {Line3} A reference to this line segment.
  40566. */
  40567. copy( line ) {
  40568. this.start.copy( line.start );
  40569. this.end.copy( line.end );
  40570. return this;
  40571. }
  40572. /**
  40573. * Returns the center of the line segment.
  40574. *
  40575. * @param {Vector3} target - The target vector that is used to store the method's result.
  40576. * @return {Vector3} The center point.
  40577. */
  40578. getCenter( target ) {
  40579. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40580. }
  40581. /**
  40582. * Returns the delta vector of the line segment's start and end point.
  40583. *
  40584. * @param {Vector3} target - The target vector that is used to store the method's result.
  40585. * @return {Vector3} The delta vector.
  40586. */
  40587. delta( target ) {
  40588. return target.subVectors( this.end, this.start );
  40589. }
  40590. /**
  40591. * Returns the squared Euclidean distance between the line' start and end point.
  40592. *
  40593. * @return {number} The squared Euclidean distance.
  40594. */
  40595. distanceSq() {
  40596. return this.start.distanceToSquared( this.end );
  40597. }
  40598. /**
  40599. * Returns the Euclidean distance between the line' start and end point.
  40600. *
  40601. * @return {number} The Euclidean distance.
  40602. */
  40603. distance() {
  40604. return this.start.distanceTo( this.end );
  40605. }
  40606. /**
  40607. * Returns a vector at a certain position along the line segment.
  40608. *
  40609. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40610. * @param {Vector3} target - The target vector that is used to store the method's result.
  40611. * @return {Vector3} The delta vector.
  40612. */
  40613. at( t, target ) {
  40614. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40615. }
  40616. /**
  40617. * Returns a point parameter based on the closest point as projected on the line segment.
  40618. *
  40619. * @param {Vector3} point - The point for which to return a point parameter.
  40620. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40621. * @return {number} The point parameter.
  40622. */
  40623. closestPointToPointParameter( point, clampToLine ) {
  40624. _startP.subVectors( point, this.start );
  40625. _startEnd.subVectors( this.end, this.start );
  40626. const startEnd2 = _startEnd.dot( _startEnd );
  40627. const startEnd_startP = _startEnd.dot( _startP );
  40628. let t = startEnd_startP / startEnd2;
  40629. if ( clampToLine ) {
  40630. t = clamp( t, 0, 1 );
  40631. }
  40632. return t;
  40633. }
  40634. /**
  40635. * Returns the closest point on the line for a given point.
  40636. *
  40637. * @param {Vector3} point - The point to compute the closest point on the line for.
  40638. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40639. * @param {Vector3} target - The target vector that is used to store the method's result.
  40640. * @return {Vector3} The closest point on the line.
  40641. */
  40642. closestPointToPoint( point, clampToLine, target ) {
  40643. const t = this.closestPointToPointParameter( point, clampToLine );
  40644. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40645. }
  40646. /**
  40647. * Returns the closest squared distance between this line segment and the given one.
  40648. *
  40649. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40650. * @param {Vector3} [c1] - The closest point on this line segment.
  40651. * @param {Vector3} [c2] - The closest point on the given line segment.
  40652. * @return {number} The squared distance between this line segment and the given one.
  40653. */
  40654. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40655. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40656. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40657. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40658. // distance between between S1(s) and S2(t)
  40659. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40660. let s, t;
  40661. const p1 = this.start;
  40662. const p2 = line.start;
  40663. const q1 = this.end;
  40664. const q2 = line.end;
  40665. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40666. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40667. _r.subVectors( p1, p2 );
  40668. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40669. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40670. const f = _d2.dot( _r );
  40671. // Check if either or both segments degenerate into points
  40672. if ( a <= EPSILON && e <= EPSILON ) {
  40673. // Both segments degenerate into points
  40674. c1.copy( p1 );
  40675. c2.copy( p2 );
  40676. c1.sub( c2 );
  40677. return c1.dot( c1 );
  40678. }
  40679. if ( a <= EPSILON ) {
  40680. // First segment degenerates into a point
  40681. s = 0;
  40682. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40683. t = clamp( t, 0, 1 );
  40684. } else {
  40685. const c = _d1.dot( _r );
  40686. if ( e <= EPSILON ) {
  40687. // Second segment degenerates into a point
  40688. t = 0;
  40689. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40690. } else {
  40691. // The general nondegenerate case starts here
  40692. const b = _d1.dot( _d2 );
  40693. const denom = a * e - b * b; // Always nonnegative
  40694. // If segments not parallel, compute closest point on L1 to L2 and
  40695. // clamp to segment S1. Else pick arbitrary s (here 0)
  40696. if ( denom !== 0 ) {
  40697. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40698. } else {
  40699. s = 0;
  40700. }
  40701. // Compute point on L2 closest to S1(s) using
  40702. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40703. t = ( b * s + f ) / e;
  40704. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40705. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40706. // and clamp s to [0, 1]
  40707. if ( t < 0 ) {
  40708. t = 0.;
  40709. s = clamp( - c / a, 0, 1 );
  40710. } else if ( t > 1 ) {
  40711. t = 1;
  40712. s = clamp( ( b - c ) / a, 0, 1 );
  40713. }
  40714. }
  40715. }
  40716. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40717. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40718. c1.sub( c2 );
  40719. return c1.dot( c1 );
  40720. }
  40721. /**
  40722. * Applies a 4x4 transformation matrix to this line segment.
  40723. *
  40724. * @param {Matrix4} matrix - The transformation matrix.
  40725. * @return {Line3} A reference to this line segment.
  40726. */
  40727. applyMatrix4( matrix ) {
  40728. this.start.applyMatrix4( matrix );
  40729. this.end.applyMatrix4( matrix );
  40730. return this;
  40731. }
  40732. /**
  40733. * Returns `true` if this line segment is equal with the given one.
  40734. *
  40735. * @param {Line3} line - The line segment to test for equality.
  40736. * @return {boolean} Whether this line segment is equal with the given one.
  40737. */
  40738. equals( line ) {
  40739. return line.start.equals( this.start ) && line.end.equals( this.end );
  40740. }
  40741. /**
  40742. * Returns a new line segment with copied values from this instance.
  40743. *
  40744. * @return {Line3} A clone of this instance.
  40745. */
  40746. clone() {
  40747. return new this.constructor().copy( this );
  40748. }
  40749. }
  40750. const _vector$3 = /*@__PURE__*/ new Vector3();
  40751. /**
  40752. * This displays a cone shaped helper object for a {@link SpotLight}.
  40753. *
  40754. * ```js
  40755. * const spotLight = new THREE.SpotLight( 0xffffff );
  40756. * spotLight.position.set( 10, 10, 10 );
  40757. * scene.add( spotLight );
  40758. *
  40759. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40760. * scene.add( spotLightHelper );
  40761. * ```
  40762. *
  40763. * @augments Object3D
  40764. */
  40765. class SpotLightHelper extends Object3D {
  40766. /**
  40767. * Constructs a new spot light helper.
  40768. *
  40769. * @param {HemisphereLight} light - The light to be visualized.
  40770. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40771. * the color of the light.
  40772. */
  40773. constructor( light, color ) {
  40774. super();
  40775. /**
  40776. * The light being visualized.
  40777. *
  40778. * @type {SpotLight}
  40779. */
  40780. this.light = light;
  40781. this.matrixAutoUpdate = false;
  40782. /**
  40783. * The color parameter passed in the constructor.
  40784. * If not set, the helper will take the color of the light.
  40785. *
  40786. * @type {number|Color|string}
  40787. */
  40788. this.color = color;
  40789. this.type = 'SpotLightHelper';
  40790. const geometry = new BufferGeometry();
  40791. const positions = [
  40792. 0, 0, 0, 0, 0, 1,
  40793. 0, 0, 0, 1, 0, 1,
  40794. 0, 0, 0, -1, 0, 1,
  40795. 0, 0, 0, 0, 1, 1,
  40796. 0, 0, 0, 0, -1, 1
  40797. ];
  40798. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40799. const p1 = ( i / l ) * Math.PI * 2;
  40800. const p2 = ( j / l ) * Math.PI * 2;
  40801. positions.push(
  40802. Math.cos( p1 ), Math.sin( p1 ), 1,
  40803. Math.cos( p2 ), Math.sin( p2 ), 1
  40804. );
  40805. }
  40806. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40807. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40808. this.cone = new LineSegments( geometry, material );
  40809. this.add( this.cone );
  40810. this.update();
  40811. }
  40812. /**
  40813. * Frees the GPU-related resources allocated by this instance. Call this
  40814. * method whenever this instance is no longer used in your app.
  40815. */
  40816. dispose() {
  40817. this.cone.geometry.dispose();
  40818. this.cone.material.dispose();
  40819. }
  40820. /**
  40821. * Updates the helper to match the position and direction of the
  40822. * light being visualized.
  40823. */
  40824. update() {
  40825. this.light.updateWorldMatrix( true, false );
  40826. this.light.target.updateWorldMatrix( true, false );
  40827. // update the local matrix based on the parent and light target transforms
  40828. if ( this.parent ) {
  40829. this.parent.updateWorldMatrix( true );
  40830. this.matrix
  40831. .copy( this.parent.matrixWorld )
  40832. .invert()
  40833. .multiply( this.light.matrixWorld );
  40834. } else {
  40835. this.matrix.copy( this.light.matrixWorld );
  40836. }
  40837. this.matrixWorld.copy( this.light.matrixWorld );
  40838. const coneLength = this.light.distance ? this.light.distance : 1000;
  40839. const coneWidth = coneLength * Math.tan( this.light.angle );
  40840. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  40841. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  40842. this.cone.lookAt( _vector$3 );
  40843. if ( this.color !== undefined ) {
  40844. this.cone.material.color.set( this.color );
  40845. } else {
  40846. this.cone.material.color.copy( this.light.color );
  40847. }
  40848. }
  40849. }
  40850. const _vector$2 = /*@__PURE__*/ new Vector3();
  40851. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  40852. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  40853. /**
  40854. * A helper object to assist with visualizing a {@link Skeleton}.
  40855. *
  40856. * ```js
  40857. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  40858. * scene.add( helper );
  40859. * ```
  40860. *
  40861. * @augments LineSegments
  40862. */
  40863. class SkeletonHelper extends LineSegments {
  40864. /**
  40865. * Constructs a new skeleton helper.
  40866. *
  40867. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  40868. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  40869. */
  40870. constructor( object ) {
  40871. const bones = getBoneList( object );
  40872. const geometry = new BufferGeometry();
  40873. const vertices = [];
  40874. const colors = [];
  40875. for ( let i = 0; i < bones.length; i ++ ) {
  40876. const bone = bones[ i ];
  40877. if ( bone.parent && bone.parent.isBone ) {
  40878. vertices.push( 0, 0, 0 );
  40879. vertices.push( 0, 0, 0 );
  40880. colors.push( 0, 0, 0 );
  40881. colors.push( 0, 0, 0 );
  40882. }
  40883. }
  40884. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  40885. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  40886. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  40887. super( geometry, material );
  40888. /**
  40889. * This flag can be used for type testing.
  40890. *
  40891. * @type {boolean}
  40892. * @readonly
  40893. * @default true
  40894. */
  40895. this.isSkeletonHelper = true;
  40896. this.type = 'SkeletonHelper';
  40897. /**
  40898. * The object being visualized.
  40899. *
  40900. * @type {Object3D}
  40901. */
  40902. this.root = object;
  40903. /**
  40904. * The list of bones that the helper visualizes.
  40905. *
  40906. * @type {Array<Bone>}
  40907. */
  40908. this.bones = bones;
  40909. this.matrix = object.matrixWorld;
  40910. this.matrixAutoUpdate = false;
  40911. // colors
  40912. const color1 = new Color( 0x0000ff );
  40913. const color2 = new Color( 0x00ff00 );
  40914. this.setColors( color1, color2 );
  40915. }
  40916. updateMatrixWorld( force ) {
  40917. const bones = this.bones;
  40918. const geometry = this.geometry;
  40919. const position = geometry.getAttribute( 'position' );
  40920. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  40921. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  40922. const bone = bones[ i ];
  40923. if ( bone.parent && bone.parent.isBone ) {
  40924. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  40925. _vector$2.setFromMatrixPosition( _boneMatrix );
  40926. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  40927. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  40928. _vector$2.setFromMatrixPosition( _boneMatrix );
  40929. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  40930. j += 2;
  40931. }
  40932. }
  40933. geometry.getAttribute( 'position' ).needsUpdate = true;
  40934. super.updateMatrixWorld( force );
  40935. }
  40936. /**
  40937. * Defines the colors of the helper.
  40938. *
  40939. * @param {Color} color1 - The first line color for each bone.
  40940. * @param {Color} color2 - The second line color for each bone.
  40941. * @return {SkeletonHelper} A reference to this helper.
  40942. */
  40943. setColors( color1, color2 ) {
  40944. const geometry = this.geometry;
  40945. const colorAttribute = geometry.getAttribute( 'color' );
  40946. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  40947. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  40948. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  40949. }
  40950. colorAttribute.needsUpdate = true;
  40951. return this;
  40952. }
  40953. /**
  40954. * Frees the GPU-related resources allocated by this instance. Call this
  40955. * method whenever this instance is no longer used in your app.
  40956. */
  40957. dispose() {
  40958. this.geometry.dispose();
  40959. this.material.dispose();
  40960. }
  40961. }
  40962. function getBoneList( object ) {
  40963. const boneList = [];
  40964. if ( object.isBone === true ) {
  40965. boneList.push( object );
  40966. }
  40967. for ( let i = 0; i < object.children.length; i ++ ) {
  40968. boneList.push( ...getBoneList( object.children[ i ] ) );
  40969. }
  40970. return boneList;
  40971. }
  40972. /**
  40973. * This displays a helper object consisting of a spherical mesh for
  40974. * visualizing an instance of {@link PointLight}.
  40975. *
  40976. * ```js
  40977. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  40978. * pointLight.position.set( 10, 10, 10 );
  40979. * scene.add( pointLight );
  40980. *
  40981. * const sphereSize = 1;
  40982. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  40983. * scene.add( pointLightHelper );
  40984. * ```
  40985. *
  40986. * @augments Mesh
  40987. */
  40988. class PointLightHelper extends Mesh {
  40989. /**
  40990. * Constructs a new point light helper.
  40991. *
  40992. * @param {PointLight} light - The light to be visualized.
  40993. * @param {number} [sphereSize=1] - The size of the sphere helper.
  40994. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40995. * the color of the light.
  40996. */
  40997. constructor( light, sphereSize, color ) {
  40998. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  40999. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41000. super( geometry, material );
  41001. /**
  41002. * The light being visualized.
  41003. *
  41004. * @type {HemisphereLight}
  41005. */
  41006. this.light = light;
  41007. /**
  41008. * The color parameter passed in the constructor.
  41009. * If not set, the helper will take the color of the light.
  41010. *
  41011. * @type {number|Color|string}
  41012. */
  41013. this.color = color;
  41014. this.type = 'PointLightHelper';
  41015. this.matrix = this.light.matrixWorld;
  41016. this.matrixAutoUpdate = false;
  41017. this.update();
  41018. /*
  41019. // TODO: delete this comment?
  41020. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41021. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41022. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41023. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41024. const d = light.distance;
  41025. if ( d === 0.0 ) {
  41026. this.lightDistance.visible = false;
  41027. } else {
  41028. this.lightDistance.scale.set( d, d, d );
  41029. }
  41030. this.add( this.lightDistance );
  41031. */
  41032. }
  41033. /**
  41034. * Frees the GPU-related resources allocated by this instance. Call this
  41035. * method whenever this instance is no longer used in your app.
  41036. */
  41037. dispose() {
  41038. this.geometry.dispose();
  41039. this.material.dispose();
  41040. }
  41041. /**
  41042. * Updates the helper to match the position of the
  41043. * light being visualized.
  41044. */
  41045. update() {
  41046. this.light.updateWorldMatrix( true, false );
  41047. if ( this.color !== undefined ) {
  41048. this.material.color.set( this.color );
  41049. } else {
  41050. this.material.color.copy( this.light.color );
  41051. }
  41052. /*
  41053. const d = this.light.distance;
  41054. if ( d === 0.0 ) {
  41055. this.lightDistance.visible = false;
  41056. } else {
  41057. this.lightDistance.visible = true;
  41058. this.lightDistance.scale.set( d, d, d );
  41059. }
  41060. */
  41061. }
  41062. }
  41063. const _vector$1 = /*@__PURE__*/ new Vector3();
  41064. const _color1 = /*@__PURE__*/ new Color();
  41065. const _color2 = /*@__PURE__*/ new Color();
  41066. /**
  41067. * Creates a visual aid consisting of a spherical mesh for a
  41068. * given {@link HemisphereLight}.
  41069. *
  41070. * ```js
  41071. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41072. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41073. * scene.add( helper );
  41074. * ```
  41075. *
  41076. * @augments Object3D
  41077. */
  41078. class HemisphereLightHelper extends Object3D {
  41079. /**
  41080. * Constructs a new hemisphere light helper.
  41081. *
  41082. * @param {HemisphereLight} light - The light to be visualized.
  41083. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41084. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41085. * the color of the light.
  41086. */
  41087. constructor( light, size, color ) {
  41088. super();
  41089. /**
  41090. * The light being visualized.
  41091. *
  41092. * @type {HemisphereLight}
  41093. */
  41094. this.light = light;
  41095. this.matrix = light.matrixWorld;
  41096. this.matrixAutoUpdate = false;
  41097. /**
  41098. * The color parameter passed in the constructor.
  41099. * If not set, the helper will take the color of the light.
  41100. *
  41101. * @type {number|Color|string}
  41102. */
  41103. this.color = color;
  41104. this.type = 'HemisphereLightHelper';
  41105. const geometry = new OctahedronGeometry( size );
  41106. geometry.rotateY( Math.PI * 0.5 );
  41107. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41108. if ( this.color === undefined ) this.material.vertexColors = true;
  41109. const position = geometry.getAttribute( 'position' );
  41110. const colors = new Float32Array( position.count * 3 );
  41111. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41112. this.add( new Mesh( geometry, this.material ) );
  41113. this.update();
  41114. }
  41115. /**
  41116. * Frees the GPU-related resources allocated by this instance. Call this
  41117. * method whenever this instance is no longer used in your app.
  41118. */
  41119. dispose() {
  41120. this.children[ 0 ].geometry.dispose();
  41121. this.children[ 0 ].material.dispose();
  41122. }
  41123. /**
  41124. * Updates the helper to match the position and direction of the
  41125. * light being visualized.
  41126. */
  41127. update() {
  41128. const mesh = this.children[ 0 ];
  41129. if ( this.color !== undefined ) {
  41130. this.material.color.set( this.color );
  41131. } else {
  41132. const colors = mesh.geometry.getAttribute( 'color' );
  41133. _color1.copy( this.light.color );
  41134. _color2.copy( this.light.groundColor );
  41135. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41136. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41137. colors.setXYZ( i, color.r, color.g, color.b );
  41138. }
  41139. colors.needsUpdate = true;
  41140. }
  41141. this.light.updateWorldMatrix( true, false );
  41142. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41143. }
  41144. }
  41145. /**
  41146. * The helper is an object to define grids. Grids are two-dimensional
  41147. * arrays of lines.
  41148. *
  41149. * ```js
  41150. * const size = 10;
  41151. * const divisions = 10;
  41152. *
  41153. * const gridHelper = new THREE.GridHelper( size, divisions );
  41154. * scene.add( gridHelper );
  41155. * ```
  41156. *
  41157. * @augments LineSegments
  41158. */
  41159. class GridHelper extends LineSegments {
  41160. /**
  41161. * Constructs a new grid helper.
  41162. *
  41163. * @param {number} [size=10] - The size of the grid.
  41164. * @param {number} [divisions=10] - The number of divisions across the grid.
  41165. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41166. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41167. */
  41168. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41169. color1 = new Color( color1 );
  41170. color2 = new Color( color2 );
  41171. const center = divisions / 2;
  41172. const step = size / divisions;
  41173. const halfSize = size / 2;
  41174. const vertices = [], colors = [];
  41175. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41176. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41177. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41178. const color = i === center ? color1 : color2;
  41179. color.toArray( colors, j ); j += 3;
  41180. color.toArray( colors, j ); j += 3;
  41181. color.toArray( colors, j ); j += 3;
  41182. color.toArray( colors, j ); j += 3;
  41183. }
  41184. const geometry = new BufferGeometry();
  41185. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41186. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41187. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41188. super( geometry, material );
  41189. this.type = 'GridHelper';
  41190. }
  41191. /**
  41192. * Frees the GPU-related resources allocated by this instance. Call this
  41193. * method whenever this instance is no longer used in your app.
  41194. */
  41195. dispose() {
  41196. this.geometry.dispose();
  41197. this.material.dispose();
  41198. }
  41199. }
  41200. /**
  41201. * This helper is an object to define polar grids. Grids are
  41202. * two-dimensional arrays of lines.
  41203. *
  41204. * ```js
  41205. * const radius = 10;
  41206. * const sectors = 16;
  41207. * const rings = 8;
  41208. * const divisions = 64;
  41209. *
  41210. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41211. * scene.add( helper );
  41212. * ```
  41213. *
  41214. * @augments LineSegments
  41215. */
  41216. class PolarGridHelper extends LineSegments {
  41217. /**
  41218. * Constructs a new polar grid helper.
  41219. *
  41220. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41221. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41222. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41223. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41224. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41225. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41226. */
  41227. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41228. color1 = new Color( color1 );
  41229. color2 = new Color( color2 );
  41230. const vertices = [];
  41231. const colors = [];
  41232. // create the sectors
  41233. if ( sectors > 1 ) {
  41234. for ( let i = 0; i < sectors; i ++ ) {
  41235. const v = ( i / sectors ) * ( Math.PI * 2 );
  41236. const x = Math.sin( v ) * radius;
  41237. const z = Math.cos( v ) * radius;
  41238. vertices.push( 0, 0, 0 );
  41239. vertices.push( x, 0, z );
  41240. const color = ( i & 1 ) ? color1 : color2;
  41241. colors.push( color.r, color.g, color.b );
  41242. colors.push( color.r, color.g, color.b );
  41243. }
  41244. }
  41245. // create the rings
  41246. for ( let i = 0; i < rings; i ++ ) {
  41247. const color = ( i & 1 ) ? color1 : color2;
  41248. const r = radius - ( radius / rings * i );
  41249. for ( let j = 0; j < divisions; j ++ ) {
  41250. // first vertex
  41251. let v = ( j / divisions ) * ( Math.PI * 2 );
  41252. let x = Math.sin( v ) * r;
  41253. let z = Math.cos( v ) * r;
  41254. vertices.push( x, 0, z );
  41255. colors.push( color.r, color.g, color.b );
  41256. // second vertex
  41257. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41258. x = Math.sin( v ) * r;
  41259. z = Math.cos( v ) * r;
  41260. vertices.push( x, 0, z );
  41261. colors.push( color.r, color.g, color.b );
  41262. }
  41263. }
  41264. const geometry = new BufferGeometry();
  41265. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41266. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41267. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41268. super( geometry, material );
  41269. this.type = 'PolarGridHelper';
  41270. }
  41271. /**
  41272. * Frees the GPU-related resources allocated by this instance. Call this
  41273. * method whenever this instance is no longer used in your app.
  41274. */
  41275. dispose() {
  41276. this.geometry.dispose();
  41277. this.material.dispose();
  41278. }
  41279. }
  41280. const _v1 = /*@__PURE__*/ new Vector3();
  41281. const _v2 = /*@__PURE__*/ new Vector3();
  41282. const _v3 = /*@__PURE__*/ new Vector3();
  41283. /**
  41284. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41285. * effect on the scene. This consists of plane and a line representing the
  41286. * light's position and direction.
  41287. *
  41288. * ```js
  41289. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41290. * scene.add( light );
  41291. *
  41292. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41293. * scene.add( helper );
  41294. * ```
  41295. *
  41296. * @augments Object3D
  41297. */
  41298. class DirectionalLightHelper extends Object3D {
  41299. /**
  41300. * Constructs a new directional light helper.
  41301. *
  41302. * @param {DirectionalLight} light - The light to be visualized.
  41303. * @param {number} [size=1] - The dimensions of the plane.
  41304. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41305. * the color of the light.
  41306. */
  41307. constructor( light, size, color ) {
  41308. super();
  41309. /**
  41310. * The light being visualized.
  41311. *
  41312. * @type {DirectionalLight}
  41313. */
  41314. this.light = light;
  41315. this.matrix = light.matrixWorld;
  41316. this.matrixAutoUpdate = false;
  41317. /**
  41318. * The color parameter passed in the constructor.
  41319. * If not set, the helper will take the color of the light.
  41320. *
  41321. * @type {number|Color|string}
  41322. */
  41323. this.color = color;
  41324. this.type = 'DirectionalLightHelper';
  41325. if ( size === undefined ) size = 1;
  41326. let geometry = new BufferGeometry();
  41327. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41328. - size, size, 0,
  41329. size, size, 0,
  41330. size, - size, 0,
  41331. - size, - size, 0,
  41332. - size, size, 0
  41333. ], 3 ) );
  41334. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41335. /**
  41336. * Contains the line showing the location of the directional light.
  41337. *
  41338. * @type {Line}
  41339. */
  41340. this.lightPlane = new Line( geometry, material );
  41341. this.add( this.lightPlane );
  41342. geometry = new BufferGeometry();
  41343. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41344. /**
  41345. * Represents the target line of the directional light.
  41346. *
  41347. * @type {Line}
  41348. */
  41349. this.targetLine = new Line( geometry, material );
  41350. this.add( this.targetLine );
  41351. this.update();
  41352. }
  41353. /**
  41354. * Frees the GPU-related resources allocated by this instance. Call this
  41355. * method whenever this instance is no longer used in your app.
  41356. */
  41357. dispose() {
  41358. this.lightPlane.geometry.dispose();
  41359. this.lightPlane.material.dispose();
  41360. this.targetLine.geometry.dispose();
  41361. this.targetLine.material.dispose();
  41362. }
  41363. /**
  41364. * Updates the helper to match the position and direction of the
  41365. * light being visualized.
  41366. */
  41367. update() {
  41368. this.light.updateWorldMatrix( true, false );
  41369. this.light.target.updateWorldMatrix( true, false );
  41370. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41371. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41372. _v3.subVectors( _v2, _v1 );
  41373. this.lightPlane.lookAt( _v2 );
  41374. if ( this.color !== undefined ) {
  41375. this.lightPlane.material.color.set( this.color );
  41376. this.targetLine.material.color.set( this.color );
  41377. } else {
  41378. this.lightPlane.material.color.copy( this.light.color );
  41379. this.targetLine.material.color.copy( this.light.color );
  41380. }
  41381. this.targetLine.lookAt( _v2 );
  41382. this.targetLine.scale.z = _v3.length();
  41383. }
  41384. }
  41385. const _vector = /*@__PURE__*/ new Vector3();
  41386. const _camera = /*@__PURE__*/ new Camera();
  41387. /**
  41388. * This helps with visualizing what a camera contains in its frustum. It
  41389. * visualizes the frustum of a camera using a line segments.
  41390. *
  41391. * Based on frustum visualization in [lightgl.js shadowmap example]{@link https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html}.
  41392. *
  41393. * `CameraHelper` must be a child of the scene.
  41394. *
  41395. * ```js
  41396. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41397. * const helper = new THREE.CameraHelper( camera );
  41398. * scene.add( helper );
  41399. * ```
  41400. *
  41401. * @augments LineSegments
  41402. */
  41403. class CameraHelper extends LineSegments {
  41404. /**
  41405. * Constructs a new arrow helper.
  41406. *
  41407. * @param {Camera} camera - The camera to visualize.
  41408. */
  41409. constructor( camera ) {
  41410. const geometry = new BufferGeometry();
  41411. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41412. const vertices = [];
  41413. const colors = [];
  41414. const pointMap = {};
  41415. // near
  41416. addLine( 'n1', 'n2' );
  41417. addLine( 'n2', 'n4' );
  41418. addLine( 'n4', 'n3' );
  41419. addLine( 'n3', 'n1' );
  41420. // far
  41421. addLine( 'f1', 'f2' );
  41422. addLine( 'f2', 'f4' );
  41423. addLine( 'f4', 'f3' );
  41424. addLine( 'f3', 'f1' );
  41425. // sides
  41426. addLine( 'n1', 'f1' );
  41427. addLine( 'n2', 'f2' );
  41428. addLine( 'n3', 'f3' );
  41429. addLine( 'n4', 'f4' );
  41430. // cone
  41431. addLine( 'p', 'n1' );
  41432. addLine( 'p', 'n2' );
  41433. addLine( 'p', 'n3' );
  41434. addLine( 'p', 'n4' );
  41435. // up
  41436. addLine( 'u1', 'u2' );
  41437. addLine( 'u2', 'u3' );
  41438. addLine( 'u3', 'u1' );
  41439. // target
  41440. addLine( 'c', 't' );
  41441. addLine( 'p', 'c' );
  41442. // cross
  41443. addLine( 'cn1', 'cn2' );
  41444. addLine( 'cn3', 'cn4' );
  41445. addLine( 'cf1', 'cf2' );
  41446. addLine( 'cf3', 'cf4' );
  41447. function addLine( a, b ) {
  41448. addPoint( a );
  41449. addPoint( b );
  41450. }
  41451. function addPoint( id ) {
  41452. vertices.push( 0, 0, 0 );
  41453. colors.push( 0, 0, 0 );
  41454. if ( pointMap[ id ] === undefined ) {
  41455. pointMap[ id ] = [];
  41456. }
  41457. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41458. }
  41459. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41460. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41461. super( geometry, material );
  41462. this.type = 'CameraHelper';
  41463. /**
  41464. * The camera being visualized.
  41465. *
  41466. * @type {Camera}
  41467. */
  41468. this.camera = camera;
  41469. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41470. this.matrix = camera.matrixWorld;
  41471. this.matrixAutoUpdate = false;
  41472. /**
  41473. * This contains the points used to visualize the camera.
  41474. *
  41475. * @type {Object<string,Array<number>>}
  41476. */
  41477. this.pointMap = pointMap;
  41478. this.update();
  41479. // colors
  41480. const colorFrustum = new Color( 0xffaa00 );
  41481. const colorCone = new Color( 0xff0000 );
  41482. const colorUp = new Color( 0x00aaff );
  41483. const colorTarget = new Color( 0xffffff );
  41484. const colorCross = new Color( 0x333333 );
  41485. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41486. }
  41487. /**
  41488. * Defines the colors of the helper.
  41489. *
  41490. * @param {Color} frustum - The frustum line color.
  41491. * @param {Color} cone - The cone line color.
  41492. * @param {Color} up - The up line color.
  41493. * @param {Color} target - The target line color.
  41494. * @param {Color} cross - The cross line color.
  41495. * @return {CameraHelper} A reference to this helper.
  41496. */
  41497. setColors( frustum, cone, up, target, cross ) {
  41498. const geometry = this.geometry;
  41499. const colorAttribute = geometry.getAttribute( 'color' );
  41500. // near
  41501. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41502. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41503. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41504. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41505. // far
  41506. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41507. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41508. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41509. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41510. // sides
  41511. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41512. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41513. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41514. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41515. // cone
  41516. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41517. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41518. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41519. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41520. // up
  41521. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41522. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41523. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41524. // target
  41525. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41526. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41527. // cross
  41528. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41529. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41530. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41531. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41532. colorAttribute.needsUpdate = true;
  41533. return this;
  41534. }
  41535. /**
  41536. * Updates the helper based on the projection matrix of the camera.
  41537. */
  41538. update() {
  41539. const geometry = this.geometry;
  41540. const pointMap = this.pointMap;
  41541. const w = 1, h = 1;
  41542. let nearZ, farZ;
  41543. // we need just camera projection matrix inverse
  41544. // world matrix must be identity
  41545. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41546. // Adjust z values based on coordinate system
  41547. if ( this.camera.reversedDepth === true ) {
  41548. nearZ = 1;
  41549. farZ = 0;
  41550. } else {
  41551. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41552. nearZ = -1;
  41553. farZ = 1;
  41554. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41555. nearZ = 0;
  41556. farZ = 1;
  41557. } else {
  41558. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41559. }
  41560. }
  41561. // center / target
  41562. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41563. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41564. // near
  41565. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41566. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41567. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41568. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41569. // far
  41570. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41571. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41572. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41573. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41574. // up
  41575. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41576. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41577. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41578. // cross
  41579. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41580. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41581. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41582. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41583. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41584. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41585. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41586. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41587. geometry.getAttribute( 'position' ).needsUpdate = true;
  41588. }
  41589. /**
  41590. * Frees the GPU-related resources allocated by this instance. Call this
  41591. * method whenever this instance is no longer used in your app.
  41592. */
  41593. dispose() {
  41594. this.geometry.dispose();
  41595. this.material.dispose();
  41596. }
  41597. }
  41598. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41599. _vector.set( x, y, z ).unproject( camera );
  41600. const points = pointMap[ point ];
  41601. if ( points !== undefined ) {
  41602. const position = geometry.getAttribute( 'position' );
  41603. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41604. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41605. }
  41606. }
  41607. }
  41608. const _box = /*@__PURE__*/ new Box3();
  41609. /**
  41610. * Helper object to graphically show the world-axis-aligned bounding box
  41611. * around an object. The actual bounding box is handled with {@link Box3},
  41612. * this is just a visual helper for debugging. It can be automatically
  41613. * resized with {@link BoxHelper#update} when the object it's created from
  41614. * is transformed. Note that the object must have a geometry for this to work,
  41615. * so it won't work with sprites.
  41616. *
  41617. * ```js
  41618. * const sphere = new THREE.SphereGeometry();
  41619. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41620. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41621. * scene.add( box );
  41622. * ```
  41623. *
  41624. * @augments LineSegments
  41625. */
  41626. class BoxHelper extends LineSegments {
  41627. /**
  41628. * Constructs a new box helper.
  41629. *
  41630. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41631. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41632. */
  41633. constructor( object, color = 0xffff00 ) {
  41634. 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 ] );
  41635. const positions = new Float32Array( 8 * 3 );
  41636. const geometry = new BufferGeometry();
  41637. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41638. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41639. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41640. /**
  41641. * The 3D object being visualized.
  41642. *
  41643. * @type {Object3D}
  41644. */
  41645. this.object = object;
  41646. this.type = 'BoxHelper';
  41647. this.matrixAutoUpdate = false;
  41648. this.update();
  41649. }
  41650. /**
  41651. * Updates the helper's geometry to match the dimensions of the object,
  41652. * including any children.
  41653. */
  41654. update() {
  41655. if ( this.object !== undefined ) {
  41656. _box.setFromObject( this.object );
  41657. }
  41658. if ( _box.isEmpty() ) return;
  41659. const min = _box.min;
  41660. const max = _box.max;
  41661. /*
  41662. 5____4
  41663. 1/___0/|
  41664. | 6__|_7
  41665. 2/___3/
  41666. 0: max.x, max.y, max.z
  41667. 1: min.x, max.y, max.z
  41668. 2: min.x, min.y, max.z
  41669. 3: max.x, min.y, max.z
  41670. 4: max.x, max.y, min.z
  41671. 5: min.x, max.y, min.z
  41672. 6: min.x, min.y, min.z
  41673. 7: max.x, min.y, min.z
  41674. */
  41675. const position = this.geometry.attributes.position;
  41676. const array = position.array;
  41677. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41678. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41679. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41680. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41681. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41682. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41683. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41684. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41685. position.needsUpdate = true;
  41686. this.geometry.computeBoundingSphere();
  41687. }
  41688. /**
  41689. * Updates the wireframe box for the passed object.
  41690. *
  41691. * @param {Object3D} object - The 3D object to create the helper for.
  41692. * @return {BoxHelper} A reference to this instance.
  41693. */
  41694. setFromObject( object ) {
  41695. this.object = object;
  41696. this.update();
  41697. return this;
  41698. }
  41699. copy( source, recursive ) {
  41700. super.copy( source, recursive );
  41701. this.object = source.object;
  41702. return this;
  41703. }
  41704. /**
  41705. * Frees the GPU-related resources allocated by this instance. Call this
  41706. * method whenever this instance is no longer used in your app.
  41707. */
  41708. dispose() {
  41709. this.geometry.dispose();
  41710. this.material.dispose();
  41711. }
  41712. }
  41713. /**
  41714. * A helper object to visualize an instance of {@link Box3}.
  41715. *
  41716. * ```js
  41717. * const box = new THREE.Box3();
  41718. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41719. *
  41720. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41721. * scene.add( helper )
  41722. * ```
  41723. *
  41724. * @augments LineSegments
  41725. */
  41726. class Box3Helper extends LineSegments {
  41727. /**
  41728. * Constructs a new box3 helper.
  41729. *
  41730. * @param {Box3} box - The box to visualize.
  41731. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41732. */
  41733. constructor( box, color = 0xffff00 ) {
  41734. 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 ] );
  41735. 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 ];
  41736. const geometry = new BufferGeometry();
  41737. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41738. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41739. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41740. /**
  41741. * The box being visualized.
  41742. *
  41743. * @type {Box3}
  41744. */
  41745. this.box = box;
  41746. this.type = 'Box3Helper';
  41747. this.geometry.computeBoundingSphere();
  41748. }
  41749. updateMatrixWorld( force ) {
  41750. const box = this.box;
  41751. if ( box.isEmpty() ) return;
  41752. box.getCenter( this.position );
  41753. box.getSize( this.scale );
  41754. this.scale.multiplyScalar( 0.5 );
  41755. super.updateMatrixWorld( force );
  41756. }
  41757. /**
  41758. * Frees the GPU-related resources allocated by this instance. Call this
  41759. * method whenever this instance is no longer used in your app.
  41760. */
  41761. dispose() {
  41762. this.geometry.dispose();
  41763. this.material.dispose();
  41764. }
  41765. }
  41766. /**
  41767. * A helper object to visualize an instance of {@link Plane}.
  41768. *
  41769. * ```js
  41770. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41771. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41772. * scene.add( helper );
  41773. * ```
  41774. *
  41775. * @augments Line
  41776. */
  41777. class PlaneHelper extends Line {
  41778. /**
  41779. * Constructs a new plane helper.
  41780. *
  41781. * @param {Plane} plane - The plane to be visualized.
  41782. * @param {number} [size=1] - The side length of plane helper.
  41783. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41784. */
  41785. constructor( plane, size = 1, hex = 0xffff00 ) {
  41786. const color = hex;
  41787. 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 ];
  41788. const geometry = new BufferGeometry();
  41789. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41790. geometry.computeBoundingSphere();
  41791. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41792. this.type = 'PlaneHelper';
  41793. /**
  41794. * The plane being visualized.
  41795. *
  41796. * @type {Plane}
  41797. */
  41798. this.plane = plane;
  41799. /**
  41800. * The side length of plane helper.
  41801. *
  41802. * @type {number}
  41803. * @default 1
  41804. */
  41805. this.size = size;
  41806. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41807. const geometry2 = new BufferGeometry();
  41808. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41809. geometry2.computeBoundingSphere();
  41810. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41811. }
  41812. updateMatrixWorld( force ) {
  41813. this.position.set( 0, 0, 0 );
  41814. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41815. this.lookAt( this.plane.normal );
  41816. this.translateZ( - this.plane.constant );
  41817. super.updateMatrixWorld( force );
  41818. }
  41819. /**
  41820. * Updates the helper to match the position and direction of the
  41821. * light being visualized.
  41822. */
  41823. dispose() {
  41824. this.geometry.dispose();
  41825. this.material.dispose();
  41826. this.children[ 0 ].geometry.dispose();
  41827. this.children[ 0 ].material.dispose();
  41828. }
  41829. }
  41830. const _axis = /*@__PURE__*/ new Vector3();
  41831. let _lineGeometry, _coneGeometry;
  41832. /**
  41833. * An 3D arrow object for visualizing directions.
  41834. *
  41835. * ```js
  41836. * const dir = new THREE.Vector3( 1, 2, 0 );
  41837. *
  41838. * //normalize the direction vector (convert to vector of length 1)
  41839. * dir.normalize();
  41840. *
  41841. * const origin = new THREE.Vector3( 0, 0, 0 );
  41842. * const length = 1;
  41843. * const hex = 0xffff00;
  41844. *
  41845. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  41846. * scene.add( arrowHelper );
  41847. * ```
  41848. *
  41849. * @augments Object3D
  41850. */
  41851. class ArrowHelper extends Object3D {
  41852. /**
  41853. * Constructs a new arrow helper.
  41854. *
  41855. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  41856. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  41857. * @param {number} [length=1] - Length of the arrow in world units.
  41858. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  41859. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41860. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41861. */
  41862. 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 ) {
  41863. super();
  41864. this.type = 'ArrowHelper';
  41865. if ( _lineGeometry === undefined ) {
  41866. _lineGeometry = new BufferGeometry();
  41867. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  41868. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  41869. _coneGeometry.translate( 0, -0.5, 0 );
  41870. }
  41871. this.position.copy( origin );
  41872. /**
  41873. * The line part of the arrow helper.
  41874. *
  41875. * @type {Line}
  41876. */
  41877. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41878. this.line.matrixAutoUpdate = false;
  41879. this.add( this.line );
  41880. /**
  41881. * The cone part of the arrow helper.
  41882. *
  41883. * @type {Mesh}
  41884. */
  41885. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  41886. this.cone.matrixAutoUpdate = false;
  41887. this.add( this.cone );
  41888. this.setDirection( dir );
  41889. this.setLength( length, headLength, headWidth );
  41890. }
  41891. /**
  41892. * Sets the direction of the helper.
  41893. *
  41894. * @param {Vector3} dir - The normalized direction vector.
  41895. */
  41896. setDirection( dir ) {
  41897. // dir is assumed to be normalized
  41898. if ( dir.y > 0.99999 ) {
  41899. this.quaternion.set( 0, 0, 0, 1 );
  41900. } else if ( dir.y < -0.99999 ) {
  41901. this.quaternion.set( 1, 0, 0, 0 );
  41902. } else {
  41903. _axis.set( dir.z, 0, - dir.x ).normalize();
  41904. const radians = Math.acos( dir.y );
  41905. this.quaternion.setFromAxisAngle( _axis, radians );
  41906. }
  41907. }
  41908. /**
  41909. * Sets the length of the helper.
  41910. *
  41911. * @param {number} length - Length of the arrow in world units.
  41912. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  41913. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  41914. */
  41915. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  41916. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  41917. this.line.updateMatrix();
  41918. this.cone.scale.set( headWidth, headLength, headWidth );
  41919. this.cone.position.y = length;
  41920. this.cone.updateMatrix();
  41921. }
  41922. /**
  41923. * Sets the color of the helper.
  41924. *
  41925. * @param {number|Color|string} color - The color to set.
  41926. */
  41927. setColor( color ) {
  41928. this.line.material.color.set( color );
  41929. this.cone.material.color.set( color );
  41930. }
  41931. copy( source ) {
  41932. super.copy( source, false );
  41933. this.line.copy( source.line );
  41934. this.cone.copy( source.cone );
  41935. return this;
  41936. }
  41937. /**
  41938. * Frees the GPU-related resources allocated by this instance. Call this
  41939. * method whenever this instance is no longer used in your app.
  41940. */
  41941. dispose() {
  41942. this.line.geometry.dispose();
  41943. this.line.material.dispose();
  41944. this.cone.geometry.dispose();
  41945. this.cone.material.dispose();
  41946. }
  41947. }
  41948. /**
  41949. * An axis object to visualize the 3 axes in a simple way.
  41950. * The X axis is red. The Y axis is green. The Z axis is blue.
  41951. *
  41952. * ```js
  41953. * const axesHelper = new THREE.AxesHelper( 5 );
  41954. * scene.add( axesHelper );
  41955. * ```
  41956. *
  41957. * @augments LineSegments
  41958. */
  41959. class AxesHelper extends LineSegments {
  41960. /**
  41961. * Constructs a new axes helper.
  41962. *
  41963. * @param {number} [size=1] - Size of the lines representing the axes.
  41964. */
  41965. constructor( size = 1 ) {
  41966. const vertices = [
  41967. 0, 0, 0, size, 0, 0,
  41968. 0, 0, 0, 0, size, 0,
  41969. 0, 0, 0, 0, 0, size
  41970. ];
  41971. const colors = [
  41972. 1, 0, 0, 1, 0.6, 0,
  41973. 0, 1, 0, 0.6, 1, 0,
  41974. 0, 0, 1, 0, 0.6, 1
  41975. ];
  41976. const geometry = new BufferGeometry();
  41977. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41978. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41979. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41980. super( geometry, material );
  41981. this.type = 'AxesHelper';
  41982. }
  41983. /**
  41984. * Defines the colors of the axes helper.
  41985. *
  41986. * @param {number|Color|string} xAxisColor - The color for the x axis.
  41987. * @param {number|Color|string} yAxisColor - The color for the y axis.
  41988. * @param {number|Color|string} zAxisColor - The color for the z axis.
  41989. * @return {AxesHelper} A reference to this axes helper.
  41990. */
  41991. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  41992. const color = new Color();
  41993. const array = this.geometry.attributes.color.array;
  41994. color.set( xAxisColor );
  41995. color.toArray( array, 0 );
  41996. color.toArray( array, 3 );
  41997. color.set( yAxisColor );
  41998. color.toArray( array, 6 );
  41999. color.toArray( array, 9 );
  42000. color.set( zAxisColor );
  42001. color.toArray( array, 12 );
  42002. color.toArray( array, 15 );
  42003. this.geometry.attributes.color.needsUpdate = true;
  42004. return this;
  42005. }
  42006. /**
  42007. * Frees the GPU-related resources allocated by this instance. Call this
  42008. * method whenever this instance is no longer used in your app.
  42009. */
  42010. dispose() {
  42011. this.geometry.dispose();
  42012. this.material.dispose();
  42013. }
  42014. }
  42015. /**
  42016. * This class is used to convert a series of paths to an array of
  42017. * shapes. It is specifically used in context of fonts and SVG.
  42018. */
  42019. class ShapePath {
  42020. /**
  42021. * Constructs a new shape path.
  42022. */
  42023. constructor() {
  42024. this.type = 'ShapePath';
  42025. /**
  42026. * The color of the shape.
  42027. *
  42028. * @type {Color}
  42029. */
  42030. this.color = new Color();
  42031. /**
  42032. * The paths that have been generated for this shape.
  42033. *
  42034. * @type {Array<Path>}
  42035. * @default null
  42036. */
  42037. this.subPaths = [];
  42038. /**
  42039. * The current path that is being generated.
  42040. *
  42041. * @type {?Path}
  42042. * @default null
  42043. */
  42044. this.currentPath = null;
  42045. }
  42046. /**
  42047. * Creates a new path and moves it current point to the given one.
  42048. *
  42049. * @param {number} x - The x coordinate.
  42050. * @param {number} y - The y coordinate.
  42051. * @return {ShapePath} A reference to this shape path.
  42052. */
  42053. moveTo( x, y ) {
  42054. this.currentPath = new Path();
  42055. this.subPaths.push( this.currentPath );
  42056. this.currentPath.moveTo( x, y );
  42057. return this;
  42058. }
  42059. /**
  42060. * Adds an instance of {@link LineCurve} to the path by connecting
  42061. * the current point with the given one.
  42062. *
  42063. * @param {number} x - The x coordinate of the end point.
  42064. * @param {number} y - The y coordinate of the end point.
  42065. * @return {ShapePath} A reference to this shape path.
  42066. */
  42067. lineTo( x, y ) {
  42068. this.currentPath.lineTo( x, y );
  42069. return this;
  42070. }
  42071. /**
  42072. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42073. * the current point with the given one.
  42074. *
  42075. * @param {number} aCPx - The x coordinate of the control point.
  42076. * @param {number} aCPy - The y coordinate of the control point.
  42077. * @param {number} aX - The x coordinate of the end point.
  42078. * @param {number} aY - The y coordinate of the end point.
  42079. * @return {ShapePath} A reference to this shape path.
  42080. */
  42081. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42082. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42083. return this;
  42084. }
  42085. /**
  42086. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42087. * the current point with the given one.
  42088. *
  42089. * @param {number} aCP1x - The x coordinate of the first control point.
  42090. * @param {number} aCP1y - The y coordinate of the first control point.
  42091. * @param {number} aCP2x - The x coordinate of the second control point.
  42092. * @param {number} aCP2y - The y coordinate of the second control point.
  42093. * @param {number} aX - The x coordinate of the end point.
  42094. * @param {number} aY - The y coordinate of the end point.
  42095. * @return {ShapePath} A reference to this shape path.
  42096. */
  42097. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42098. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42099. return this;
  42100. }
  42101. /**
  42102. * Adds an instance of {@link SplineCurve} to the path by connecting
  42103. * the current point with the given list of points.
  42104. *
  42105. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42106. * @return {ShapePath} A reference to this shape path.
  42107. */
  42108. splineThru( pts ) {
  42109. this.currentPath.splineThru( pts );
  42110. return this;
  42111. }
  42112. /**
  42113. * Converts the paths into an array of shapes.
  42114. *
  42115. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42116. * If this flag is set to `true`, then those are flipped.
  42117. * @return {Array<Shape>} An array of shapes.
  42118. */
  42119. toShapes( isCCW ) {
  42120. function toShapesNoHoles( inSubpaths ) {
  42121. const shapes = [];
  42122. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42123. const tmpPath = inSubpaths[ i ];
  42124. const tmpShape = new Shape();
  42125. tmpShape.curves = tmpPath.curves;
  42126. shapes.push( tmpShape );
  42127. }
  42128. return shapes;
  42129. }
  42130. function isPointInsidePolygon( inPt, inPolygon ) {
  42131. const polyLen = inPolygon.length;
  42132. // inPt on polygon contour => immediate success or
  42133. // toggling of inside/outside at every single! intersection point of an edge
  42134. // with the horizontal line through inPt, left of inPt
  42135. // not counting lowerY endpoints of edges and whole edges on that line
  42136. let inside = false;
  42137. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42138. let edgeLowPt = inPolygon[ p ];
  42139. let edgeHighPt = inPolygon[ q ];
  42140. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42141. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42142. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42143. // not parallel
  42144. if ( edgeDy < 0 ) {
  42145. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42146. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42147. }
  42148. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42149. if ( inPt.y === edgeLowPt.y ) {
  42150. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42151. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42152. } else {
  42153. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42154. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42155. if ( perpEdge < 0 ) continue;
  42156. inside = ! inside; // true intersection left of inPt
  42157. }
  42158. } else {
  42159. // parallel or collinear
  42160. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42161. // edge lies on the same horizontal line as inPt
  42162. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42163. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42164. // continue;
  42165. }
  42166. }
  42167. return inside;
  42168. }
  42169. const isClockWise = ShapeUtils.isClockWise;
  42170. const subPaths = this.subPaths;
  42171. if ( subPaths.length === 0 ) return [];
  42172. let solid, tmpPath, tmpShape;
  42173. const shapes = [];
  42174. if ( subPaths.length === 1 ) {
  42175. tmpPath = subPaths[ 0 ];
  42176. tmpShape = new Shape();
  42177. tmpShape.curves = tmpPath.curves;
  42178. shapes.push( tmpShape );
  42179. return shapes;
  42180. }
  42181. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42182. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42183. // log("Holes first", holesFirst);
  42184. const betterShapeHoles = [];
  42185. const newShapes = [];
  42186. let newShapeHoles = [];
  42187. let mainIdx = 0;
  42188. let tmpPoints;
  42189. newShapes[ mainIdx ] = undefined;
  42190. newShapeHoles[ mainIdx ] = [];
  42191. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42192. tmpPath = subPaths[ i ];
  42193. tmpPoints = tmpPath.getPoints();
  42194. solid = isClockWise( tmpPoints );
  42195. solid = isCCW ? ! solid : solid;
  42196. if ( solid ) {
  42197. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42198. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42199. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42200. if ( holesFirst ) mainIdx ++;
  42201. newShapeHoles[ mainIdx ] = [];
  42202. //log('cw', i);
  42203. } else {
  42204. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42205. //log('ccw', i);
  42206. }
  42207. }
  42208. // only Holes? -> probably all Shapes with wrong orientation
  42209. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42210. if ( newShapes.length > 1 ) {
  42211. let ambiguous = false;
  42212. let toChange = 0;
  42213. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42214. betterShapeHoles[ sIdx ] = [];
  42215. }
  42216. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42217. const sho = newShapeHoles[ sIdx ];
  42218. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42219. const ho = sho[ hIdx ];
  42220. let hole_unassigned = true;
  42221. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42222. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42223. if ( sIdx !== s2Idx ) toChange ++;
  42224. if ( hole_unassigned ) {
  42225. hole_unassigned = false;
  42226. betterShapeHoles[ s2Idx ].push( ho );
  42227. } else {
  42228. ambiguous = true;
  42229. }
  42230. }
  42231. }
  42232. if ( hole_unassigned ) {
  42233. betterShapeHoles[ sIdx ].push( ho );
  42234. }
  42235. }
  42236. }
  42237. if ( toChange > 0 && ambiguous === false ) {
  42238. newShapeHoles = betterShapeHoles;
  42239. }
  42240. }
  42241. let tmpHoles;
  42242. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42243. tmpShape = newShapes[ i ].s;
  42244. shapes.push( tmpShape );
  42245. tmpHoles = newShapeHoles[ i ];
  42246. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42247. tmpShape.holes.push( tmpHoles[ j ].h );
  42248. }
  42249. }
  42250. //log("shape", shapes);
  42251. return shapes;
  42252. }
  42253. }
  42254. /**
  42255. * Abstract base class for controls.
  42256. *
  42257. * @abstract
  42258. * @augments EventDispatcher
  42259. */
  42260. class Controls extends EventDispatcher {
  42261. /**
  42262. * Constructs a new controls instance.
  42263. *
  42264. * @param {Object3D} object - The object that is managed by the controls.
  42265. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42266. */
  42267. constructor( object, domElement = null ) {
  42268. super();
  42269. /**
  42270. * The object that is managed by the controls.
  42271. *
  42272. * @type {Object3D}
  42273. */
  42274. this.object = object;
  42275. /**
  42276. * The HTML element used for event listeners.
  42277. *
  42278. * @type {?HTMLElement}
  42279. * @default null
  42280. */
  42281. this.domElement = domElement;
  42282. /**
  42283. * Whether the controls responds to user input or not.
  42284. *
  42285. * @type {boolean}
  42286. * @default true
  42287. */
  42288. this.enabled = true;
  42289. /**
  42290. * The internal state of the controls.
  42291. *
  42292. * @type {number}
  42293. * @default -1
  42294. */
  42295. this.state = -1;
  42296. /**
  42297. * This object defines the keyboard input of the controls.
  42298. *
  42299. * @type {Object}
  42300. */
  42301. this.keys = {};
  42302. /**
  42303. * This object defines what type of actions are assigned to the available mouse buttons.
  42304. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42305. *
  42306. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42307. */
  42308. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42309. /**
  42310. * This object defines what type of actions are assigned to what kind of touch interaction.
  42311. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42312. *
  42313. * @type {{ONE: ?number, TWO: ?number}}
  42314. */
  42315. this.touches = { ONE: null, TWO: null };
  42316. }
  42317. /**
  42318. * Connects the controls to the DOM. This method has so called "side effects" since
  42319. * it adds the module's event listeners to the DOM.
  42320. *
  42321. * @param {HTMLElement} element - The DOM element to connect to.
  42322. */
  42323. connect( element ) {
  42324. if ( element === undefined ) {
  42325. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42326. return;
  42327. }
  42328. if ( this.domElement !== null ) this.disconnect();
  42329. this.domElement = element;
  42330. }
  42331. /**
  42332. * Disconnects the controls from the DOM.
  42333. */
  42334. disconnect() {}
  42335. /**
  42336. * Call this method if you no longer want use to the controls. It frees all internal
  42337. * resources and removes all event listeners.
  42338. */
  42339. dispose() {}
  42340. /**
  42341. * Controls should implement this method if they have to update their internal state
  42342. * per simulation step.
  42343. *
  42344. * @param {number} [delta] - The time delta in seconds.
  42345. */
  42346. update( /* delta */ ) {}
  42347. }
  42348. /**
  42349. * Scales the texture as large as possible within its surface without cropping
  42350. * or stretching the texture. The method preserves the original aspect ratio of
  42351. * the texture. Akin to CSS `object-fit: contain`
  42352. *
  42353. * @param {Texture} texture - The texture.
  42354. * @param {number} aspect - The texture's aspect ratio.
  42355. * @return {Texture} The updated texture.
  42356. */
  42357. function contain( texture, aspect ) {
  42358. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42359. if ( imageAspect > aspect ) {
  42360. texture.repeat.x = 1;
  42361. texture.repeat.y = imageAspect / aspect;
  42362. texture.offset.x = 0;
  42363. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42364. } else {
  42365. texture.repeat.x = aspect / imageAspect;
  42366. texture.repeat.y = 1;
  42367. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42368. texture.offset.y = 0;
  42369. }
  42370. return texture;
  42371. }
  42372. /**
  42373. * Scales the texture to the smallest possible size to fill the surface, leaving
  42374. * no empty space. The method preserves the original aspect ratio of the texture.
  42375. * Akin to CSS `object-fit: cover`.
  42376. *
  42377. * @param {Texture} texture - The texture.
  42378. * @param {number} aspect - The texture's aspect ratio.
  42379. * @return {Texture} The updated texture.
  42380. */
  42381. function cover( texture, aspect ) {
  42382. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42383. if ( imageAspect > aspect ) {
  42384. texture.repeat.x = aspect / imageAspect;
  42385. texture.repeat.y = 1;
  42386. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42387. texture.offset.y = 0;
  42388. } else {
  42389. texture.repeat.x = 1;
  42390. texture.repeat.y = imageAspect / aspect;
  42391. texture.offset.x = 0;
  42392. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42393. }
  42394. return texture;
  42395. }
  42396. /**
  42397. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42398. *
  42399. * @param {Texture} texture - The texture.
  42400. * @return {Texture} The updated texture.
  42401. */
  42402. function fill( texture ) {
  42403. texture.repeat.x = 1;
  42404. texture.repeat.y = 1;
  42405. texture.offset.x = 0;
  42406. texture.offset.y = 0;
  42407. return texture;
  42408. }
  42409. /**
  42410. * Determines how many bytes must be used to represent the texture.
  42411. *
  42412. * @param {number} width - The width of the texture.
  42413. * @param {number} height - The height of the texture.
  42414. * @param {number} format - The texture's format.
  42415. * @param {number} type - The texture's type.
  42416. * @return {number} The byte length.
  42417. */
  42418. function getByteLength( width, height, format, type ) {
  42419. const typeByteLength = getTextureTypeByteLength( type );
  42420. switch ( format ) {
  42421. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42422. case AlphaFormat:
  42423. return width * height;
  42424. case RedFormat:
  42425. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42426. case RedIntegerFormat:
  42427. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42428. case RGFormat:
  42429. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42430. case RGIntegerFormat:
  42431. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42432. case RGBFormat:
  42433. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42434. case RGBAFormat:
  42435. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42436. case RGBAIntegerFormat:
  42437. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42438. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42439. case RGB_S3TC_DXT1_Format:
  42440. case RGBA_S3TC_DXT1_Format:
  42441. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42442. case RGBA_S3TC_DXT3_Format:
  42443. case RGBA_S3TC_DXT5_Format:
  42444. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42445. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42446. case RGB_PVRTC_2BPPV1_Format:
  42447. case RGBA_PVRTC_2BPPV1_Format:
  42448. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42449. case RGB_PVRTC_4BPPV1_Format:
  42450. case RGBA_PVRTC_4BPPV1_Format:
  42451. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42452. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42453. case RGB_ETC1_Format:
  42454. case RGB_ETC2_Format:
  42455. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42456. case RGBA_ETC2_EAC_Format:
  42457. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42458. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42459. case RGBA_ASTC_4x4_Format:
  42460. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42461. case RGBA_ASTC_5x4_Format:
  42462. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42463. case RGBA_ASTC_5x5_Format:
  42464. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42465. case RGBA_ASTC_6x5_Format:
  42466. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42467. case RGBA_ASTC_6x6_Format:
  42468. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42469. case RGBA_ASTC_8x5_Format:
  42470. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42471. case RGBA_ASTC_8x6_Format:
  42472. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42473. case RGBA_ASTC_8x8_Format:
  42474. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42475. case RGBA_ASTC_10x5_Format:
  42476. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42477. case RGBA_ASTC_10x6_Format:
  42478. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42479. case RGBA_ASTC_10x8_Format:
  42480. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42481. case RGBA_ASTC_10x10_Format:
  42482. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42483. case RGBA_ASTC_12x10_Format:
  42484. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42485. case RGBA_ASTC_12x12_Format:
  42486. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42487. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42488. case RGBA_BPTC_Format:
  42489. case RGB_BPTC_SIGNED_Format:
  42490. case RGB_BPTC_UNSIGNED_Format:
  42491. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42492. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42493. case RED_RGTC1_Format:
  42494. case SIGNED_RED_RGTC1_Format:
  42495. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42496. case RED_GREEN_RGTC2_Format:
  42497. case SIGNED_RED_GREEN_RGTC2_Format:
  42498. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42499. }
  42500. throw new Error(
  42501. `Unable to determine texture byte length for ${format} format.`,
  42502. );
  42503. }
  42504. function getTextureTypeByteLength( type ) {
  42505. switch ( type ) {
  42506. case UnsignedByteType:
  42507. case ByteType:
  42508. return { byteLength: 1, components: 1 };
  42509. case UnsignedShortType:
  42510. case ShortType:
  42511. case HalfFloatType:
  42512. return { byteLength: 2, components: 1 };
  42513. case UnsignedShort4444Type:
  42514. case UnsignedShort5551Type:
  42515. return { byteLength: 2, components: 4 };
  42516. case UnsignedIntType:
  42517. case IntType:
  42518. case FloatType:
  42519. return { byteLength: 4, components: 1 };
  42520. case UnsignedInt5999Type:
  42521. case UnsignedInt101111Type:
  42522. return { byteLength: 4, components: 3 };
  42523. }
  42524. throw new Error( `Unknown texture type ${type}.` );
  42525. }
  42526. /**
  42527. * A class containing utility functions for textures.
  42528. *
  42529. * @hideconstructor
  42530. */
  42531. class TextureUtils {
  42532. /**
  42533. * Scales the texture as large as possible within its surface without cropping
  42534. * or stretching the texture. The method preserves the original aspect ratio of
  42535. * the texture. Akin to CSS `object-fit: contain`
  42536. *
  42537. * @param {Texture} texture - The texture.
  42538. * @param {number} aspect - The texture's aspect ratio.
  42539. * @return {Texture} The updated texture.
  42540. */
  42541. static contain( texture, aspect ) {
  42542. return contain( texture, aspect );
  42543. }
  42544. /**
  42545. * Scales the texture to the smallest possible size to fill the surface, leaving
  42546. * no empty space. The method preserves the original aspect ratio of the texture.
  42547. * Akin to CSS `object-fit: cover`.
  42548. *
  42549. * @param {Texture} texture - The texture.
  42550. * @param {number} aspect - The texture's aspect ratio.
  42551. * @return {Texture} The updated texture.
  42552. */
  42553. static cover( texture, aspect ) {
  42554. return cover( texture, aspect );
  42555. }
  42556. /**
  42557. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42558. *
  42559. * @param {Texture} texture - The texture.
  42560. * @return {Texture} The updated texture.
  42561. */
  42562. static fill( texture ) {
  42563. return fill( texture );
  42564. }
  42565. /**
  42566. * Determines how many bytes must be used to represent the texture.
  42567. *
  42568. * @param {number} width - The width of the texture.
  42569. * @param {number} height - The height of the texture.
  42570. * @param {number} format - The texture's format.
  42571. * @param {number} type - The texture's type.
  42572. * @return {number} The byte length.
  42573. */
  42574. static getByteLength( width, height, format, type ) {
  42575. return getByteLength( width, height, format, type );
  42576. }
  42577. }
  42578. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42579. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42580. revision: REVISION,
  42581. } } ) );
  42582. }
  42583. if ( typeof window !== 'undefined' ) {
  42584. if ( window.__THREE__ ) {
  42585. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42586. } else {
  42587. window.__THREE__ = REVISION;
  42588. }
  42589. }
  42590. function WebGLAnimation() {
  42591. let context = null;
  42592. let isAnimating = false;
  42593. let animationLoop = null;
  42594. let requestId = null;
  42595. function onAnimationFrame( time, frame ) {
  42596. animationLoop( time, frame );
  42597. requestId = context.requestAnimationFrame( onAnimationFrame );
  42598. }
  42599. return {
  42600. start: function () {
  42601. if ( isAnimating === true ) return;
  42602. if ( animationLoop === null ) return;
  42603. requestId = context.requestAnimationFrame( onAnimationFrame );
  42604. isAnimating = true;
  42605. },
  42606. stop: function () {
  42607. context.cancelAnimationFrame( requestId );
  42608. isAnimating = false;
  42609. },
  42610. setAnimationLoop: function ( callback ) {
  42611. animationLoop = callback;
  42612. },
  42613. setContext: function ( value ) {
  42614. context = value;
  42615. }
  42616. };
  42617. }
  42618. function WebGLAttributes( gl ) {
  42619. const buffers = new WeakMap();
  42620. function createBuffer( attribute, bufferType ) {
  42621. const array = attribute.array;
  42622. const usage = attribute.usage;
  42623. const size = array.byteLength;
  42624. const buffer = gl.createBuffer();
  42625. gl.bindBuffer( bufferType, buffer );
  42626. gl.bufferData( bufferType, array, usage );
  42627. attribute.onUploadCallback();
  42628. let type;
  42629. if ( array instanceof Float32Array ) {
  42630. type = gl.FLOAT;
  42631. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42632. type = gl.HALF_FLOAT;
  42633. } else if ( array instanceof Uint16Array ) {
  42634. if ( attribute.isFloat16BufferAttribute ) {
  42635. type = gl.HALF_FLOAT;
  42636. } else {
  42637. type = gl.UNSIGNED_SHORT;
  42638. }
  42639. } else if ( array instanceof Int16Array ) {
  42640. type = gl.SHORT;
  42641. } else if ( array instanceof Uint32Array ) {
  42642. type = gl.UNSIGNED_INT;
  42643. } else if ( array instanceof Int32Array ) {
  42644. type = gl.INT;
  42645. } else if ( array instanceof Int8Array ) {
  42646. type = gl.BYTE;
  42647. } else if ( array instanceof Uint8Array ) {
  42648. type = gl.UNSIGNED_BYTE;
  42649. } else if ( array instanceof Uint8ClampedArray ) {
  42650. type = gl.UNSIGNED_BYTE;
  42651. } else {
  42652. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42653. }
  42654. return {
  42655. buffer: buffer,
  42656. type: type,
  42657. bytesPerElement: array.BYTES_PER_ELEMENT,
  42658. version: attribute.version,
  42659. size: size
  42660. };
  42661. }
  42662. function updateBuffer( buffer, attribute, bufferType ) {
  42663. const array = attribute.array;
  42664. const updateRanges = attribute.updateRanges;
  42665. gl.bindBuffer( bufferType, buffer );
  42666. if ( updateRanges.length === 0 ) {
  42667. // Not using update ranges
  42668. gl.bufferSubData( bufferType, 0, array );
  42669. } else {
  42670. // Before applying update ranges, we merge any adjacent / overlapping
  42671. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42672. // to performance improvements for applications which make heavy use of
  42673. // update ranges. Likely due to GPU command overhead.
  42674. //
  42675. // Note that to reduce garbage collection between frames, we merge the
  42676. // update ranges in-place. This is safe because this method will clear the
  42677. // update ranges once updated.
  42678. updateRanges.sort( ( a, b ) => a.start - b.start );
  42679. // To merge the update ranges in-place, we work from left to right in the
  42680. // existing updateRanges array, merging ranges. This may result in a final
  42681. // array which is smaller than the original. This index tracks the last
  42682. // index representing a merged range, any data after this index can be
  42683. // trimmed once the merge algorithm is completed.
  42684. let mergeIndex = 0;
  42685. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42686. const previousRange = updateRanges[ mergeIndex ];
  42687. const range = updateRanges[ i ];
  42688. // We add one here to merge adjacent ranges. This is safe because ranges
  42689. // operate over positive integers.
  42690. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42691. previousRange.count = Math.max(
  42692. previousRange.count,
  42693. range.start + range.count - previousRange.start
  42694. );
  42695. } else {
  42696. ++ mergeIndex;
  42697. updateRanges[ mergeIndex ] = range;
  42698. }
  42699. }
  42700. // Trim the array to only contain the merged ranges.
  42701. updateRanges.length = mergeIndex + 1;
  42702. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42703. const range = updateRanges[ i ];
  42704. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42705. array, range.start, range.count );
  42706. }
  42707. attribute.clearUpdateRanges();
  42708. }
  42709. attribute.onUploadCallback();
  42710. }
  42711. //
  42712. function get( attribute ) {
  42713. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42714. return buffers.get( attribute );
  42715. }
  42716. function remove( attribute ) {
  42717. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42718. const data = buffers.get( attribute );
  42719. if ( data ) {
  42720. gl.deleteBuffer( data.buffer );
  42721. buffers.delete( attribute );
  42722. }
  42723. }
  42724. function update( attribute, bufferType ) {
  42725. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42726. if ( attribute.isGLBufferAttribute ) {
  42727. const cached = buffers.get( attribute );
  42728. if ( ! cached || cached.version < attribute.version ) {
  42729. buffers.set( attribute, {
  42730. buffer: attribute.buffer,
  42731. type: attribute.type,
  42732. bytesPerElement: attribute.elementSize,
  42733. version: attribute.version
  42734. } );
  42735. }
  42736. return;
  42737. }
  42738. const data = buffers.get( attribute );
  42739. if ( data === undefined ) {
  42740. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42741. } else if ( data.version < attribute.version ) {
  42742. if ( data.size !== attribute.array.byteLength ) {
  42743. 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.' );
  42744. }
  42745. updateBuffer( data.buffer, attribute, bufferType );
  42746. data.version = attribute.version;
  42747. }
  42748. }
  42749. return {
  42750. get: get,
  42751. remove: remove,
  42752. update: update
  42753. };
  42754. }
  42755. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42756. 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";
  42757. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42758. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42759. 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";
  42760. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42761. 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";
  42762. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42763. 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";
  42764. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42765. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42766. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42767. 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";
  42768. 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";
  42769. 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";
  42770. 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";
  42771. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42772. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42773. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42774. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42775. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42776. 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";
  42777. 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";
  42778. 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}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\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";
  42779. 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";
  42780. 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";
  42781. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42782. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42783. 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";
  42784. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42785. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42786. 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}";
  42787. 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";
  42788. 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\t\n#endif";
  42789. 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";
  42790. 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";
  42791. 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";
  42792. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42793. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42794. 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";
  42795. 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";
  42796. 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}";
  42797. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42798. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42799. 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";
  42800. 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";
  42801. 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, roughness * 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";
  42802. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42803. 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";
  42804. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42805. 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";
  42806. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - 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 = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  42807. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\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#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 saturate(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.specularColor;\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 * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in 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.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  42808. 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.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.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";
  42809. 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";
  42810. 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";
  42811. 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";
  42812. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42813. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42814. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42815. 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";
  42816. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42817. 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";
  42818. 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";
  42819. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42820. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42821. 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";
  42822. 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";
  42823. 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";
  42824. 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";
  42825. 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";
  42826. 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;";
  42827. 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";
  42828. 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";
  42829. 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";
  42830. 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";
  42831. 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";
  42832. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42833. 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";
  42834. 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";
  42835. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  42836. 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 );";
  42837. 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}";
  42838. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  42839. 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;";
  42840. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  42841. 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";
  42842. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  42843. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  42844. 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\tuniform sampler2D directionalShadowMap[ 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\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\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 sampler2D pointShadowMap[ 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\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\tfloat depth = unpackRGBAToDepth( texture2D( depths, uv ) );\n\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\treturn step( depth, compare );\n\t\t#else\n\t\t\treturn step( compare, depth );\n\t\t#endif\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow( sampler2D shadow, vec2 uv, float compare ) {\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\tfloat hard_shadow = step( distribution.x, compare );\n\t\t#else\n\t\t\tfloat hard_shadow = step( compare, distribution.x );\n\t\t#endif\n\t\tif ( hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float 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\t\n\t\tfloat lightToPositionLength = length( lightToPosition );\n\t\tif ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\t\tdp += shadowBias;\n\t\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t\t) * ( 1.0 / 9.0 );\n\t\t\t#else\n\t\t\t\tshadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n#endif";
  42845. 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";
  42846. 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";
  42847. 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\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}";
  42848. 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";
  42849. 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";
  42850. 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";
  42851. 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";
  42852. 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";
  42853. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  42854. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  42855. 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; }";
  42856. 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.diffuseColor, material.specularColor, 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";
  42857. 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";
  42858. 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";
  42859. 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";
  42860. 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";
  42861. 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";
  42862. 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}";
  42863. 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}";
  42864. 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}";
  42865. 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}";
  42866. 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}";
  42867. 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}";
  42868. 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}";
  42869. 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}";
  42870. 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}";
  42871. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <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 = packDepthToRGBA( dist );\n}";
  42872. 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}";
  42873. 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}";
  42874. 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}";
  42875. 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}";
  42876. 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}";
  42877. 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}";
  42878. 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}";
  42879. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <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}";
  42880. 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}";
  42881. 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}";
  42882. 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}";
  42883. 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 <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\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( packNormalToRGB( normal ), diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  42884. 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}";
  42885. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <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}";
  42886. 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}";
  42887. 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 <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  42888. 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}";
  42889. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <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}";
  42890. 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}";
  42891. 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}";
  42892. 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}";
  42893. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <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}";
  42894. 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}";
  42895. 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}";
  42896. const ShaderChunk = {
  42897. alphahash_fragment: alphahash_fragment,
  42898. alphahash_pars_fragment: alphahash_pars_fragment,
  42899. alphamap_fragment: alphamap_fragment,
  42900. alphamap_pars_fragment: alphamap_pars_fragment,
  42901. alphatest_fragment: alphatest_fragment,
  42902. alphatest_pars_fragment: alphatest_pars_fragment,
  42903. aomap_fragment: aomap_fragment,
  42904. aomap_pars_fragment: aomap_pars_fragment,
  42905. batching_pars_vertex: batching_pars_vertex,
  42906. batching_vertex: batching_vertex,
  42907. begin_vertex: begin_vertex,
  42908. beginnormal_vertex: beginnormal_vertex,
  42909. bsdfs: bsdfs,
  42910. iridescence_fragment: iridescence_fragment,
  42911. bumpmap_pars_fragment: bumpmap_pars_fragment,
  42912. clipping_planes_fragment: clipping_planes_fragment,
  42913. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  42914. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  42915. clipping_planes_vertex: clipping_planes_vertex,
  42916. color_fragment: color_fragment,
  42917. color_pars_fragment: color_pars_fragment,
  42918. color_pars_vertex: color_pars_vertex,
  42919. color_vertex: color_vertex,
  42920. common: common,
  42921. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  42922. defaultnormal_vertex: defaultnormal_vertex,
  42923. displacementmap_pars_vertex: displacementmap_pars_vertex,
  42924. displacementmap_vertex: displacementmap_vertex,
  42925. emissivemap_fragment: emissivemap_fragment,
  42926. emissivemap_pars_fragment: emissivemap_pars_fragment,
  42927. colorspace_fragment: colorspace_fragment,
  42928. colorspace_pars_fragment: colorspace_pars_fragment,
  42929. envmap_fragment: envmap_fragment,
  42930. envmap_common_pars_fragment: envmap_common_pars_fragment,
  42931. envmap_pars_fragment: envmap_pars_fragment,
  42932. envmap_pars_vertex: envmap_pars_vertex,
  42933. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  42934. envmap_vertex: envmap_vertex,
  42935. fog_vertex: fog_vertex,
  42936. fog_pars_vertex: fog_pars_vertex,
  42937. fog_fragment: fog_fragment,
  42938. fog_pars_fragment: fog_pars_fragment,
  42939. gradientmap_pars_fragment: gradientmap_pars_fragment,
  42940. lightmap_pars_fragment: lightmap_pars_fragment,
  42941. lights_lambert_fragment: lights_lambert_fragment,
  42942. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  42943. lights_pars_begin: lights_pars_begin,
  42944. lights_toon_fragment: lights_toon_fragment,
  42945. lights_toon_pars_fragment: lights_toon_pars_fragment,
  42946. lights_phong_fragment: lights_phong_fragment,
  42947. lights_phong_pars_fragment: lights_phong_pars_fragment,
  42948. lights_physical_fragment: lights_physical_fragment,
  42949. lights_physical_pars_fragment: lights_physical_pars_fragment,
  42950. lights_fragment_begin: lights_fragment_begin,
  42951. lights_fragment_maps: lights_fragment_maps,
  42952. lights_fragment_end: lights_fragment_end,
  42953. logdepthbuf_fragment: logdepthbuf_fragment,
  42954. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  42955. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  42956. logdepthbuf_vertex: logdepthbuf_vertex,
  42957. map_fragment: map_fragment,
  42958. map_pars_fragment: map_pars_fragment,
  42959. map_particle_fragment: map_particle_fragment,
  42960. map_particle_pars_fragment: map_particle_pars_fragment,
  42961. metalnessmap_fragment: metalnessmap_fragment,
  42962. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  42963. morphinstance_vertex: morphinstance_vertex,
  42964. morphcolor_vertex: morphcolor_vertex,
  42965. morphnormal_vertex: morphnormal_vertex,
  42966. morphtarget_pars_vertex: morphtarget_pars_vertex,
  42967. morphtarget_vertex: morphtarget_vertex,
  42968. normal_fragment_begin: normal_fragment_begin,
  42969. normal_fragment_maps: normal_fragment_maps,
  42970. normal_pars_fragment: normal_pars_fragment,
  42971. normal_pars_vertex: normal_pars_vertex,
  42972. normal_vertex: normal_vertex,
  42973. normalmap_pars_fragment: normalmap_pars_fragment,
  42974. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  42975. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  42976. clearcoat_pars_fragment: clearcoat_pars_fragment,
  42977. iridescence_pars_fragment: iridescence_pars_fragment,
  42978. opaque_fragment: opaque_fragment,
  42979. packing: packing,
  42980. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  42981. project_vertex: project_vertex,
  42982. dithering_fragment: dithering_fragment,
  42983. dithering_pars_fragment: dithering_pars_fragment,
  42984. roughnessmap_fragment: roughnessmap_fragment,
  42985. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  42986. shadowmap_pars_fragment: shadowmap_pars_fragment,
  42987. shadowmap_pars_vertex: shadowmap_pars_vertex,
  42988. shadowmap_vertex: shadowmap_vertex,
  42989. shadowmask_pars_fragment: shadowmask_pars_fragment,
  42990. skinbase_vertex: skinbase_vertex,
  42991. skinning_pars_vertex: skinning_pars_vertex,
  42992. skinning_vertex: skinning_vertex,
  42993. skinnormal_vertex: skinnormal_vertex,
  42994. specularmap_fragment: specularmap_fragment,
  42995. specularmap_pars_fragment: specularmap_pars_fragment,
  42996. tonemapping_fragment: tonemapping_fragment,
  42997. tonemapping_pars_fragment: tonemapping_pars_fragment,
  42998. transmission_fragment: transmission_fragment,
  42999. transmission_pars_fragment: transmission_pars_fragment,
  43000. uv_pars_fragment: uv_pars_fragment,
  43001. uv_pars_vertex: uv_pars_vertex,
  43002. uv_vertex: uv_vertex,
  43003. worldpos_vertex: worldpos_vertex,
  43004. background_vert: vertex$h,
  43005. background_frag: fragment$h,
  43006. backgroundCube_vert: vertex$g,
  43007. backgroundCube_frag: fragment$g,
  43008. cube_vert: vertex$f,
  43009. cube_frag: fragment$f,
  43010. depth_vert: vertex$e,
  43011. depth_frag: fragment$e,
  43012. distanceRGBA_vert: vertex$d,
  43013. distanceRGBA_frag: fragment$d,
  43014. equirect_vert: vertex$c,
  43015. equirect_frag: fragment$c,
  43016. linedashed_vert: vertex$b,
  43017. linedashed_frag: fragment$b,
  43018. meshbasic_vert: vertex$a,
  43019. meshbasic_frag: fragment$a,
  43020. meshlambert_vert: vertex$9,
  43021. meshlambert_frag: fragment$9,
  43022. meshmatcap_vert: vertex$8,
  43023. meshmatcap_frag: fragment$8,
  43024. meshnormal_vert: vertex$7,
  43025. meshnormal_frag: fragment$7,
  43026. meshphong_vert: vertex$6,
  43027. meshphong_frag: fragment$6,
  43028. meshphysical_vert: vertex$5,
  43029. meshphysical_frag: fragment$5,
  43030. meshtoon_vert: vertex$4,
  43031. meshtoon_frag: fragment$4,
  43032. points_vert: vertex$3,
  43033. points_frag: fragment$3,
  43034. shadow_vert: vertex$2,
  43035. shadow_frag: fragment$2,
  43036. sprite_vert: vertex$1,
  43037. sprite_frag: fragment$1
  43038. };
  43039. // Uniforms library for shared webgl shaders
  43040. const UniformsLib = {
  43041. common: {
  43042. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43043. opacity: { value: 1.0 },
  43044. map: { value: null },
  43045. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43046. alphaMap: { value: null },
  43047. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43048. alphaTest: { value: 0 }
  43049. },
  43050. specularmap: {
  43051. specularMap: { value: null },
  43052. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43053. },
  43054. envmap: {
  43055. envMap: { value: null },
  43056. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43057. flipEnvMap: { value: -1 },
  43058. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43059. ior: { value: 1.5 }, // physical
  43060. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43061. },
  43062. aomap: {
  43063. aoMap: { value: null },
  43064. aoMapIntensity: { value: 1 },
  43065. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43066. },
  43067. lightmap: {
  43068. lightMap: { value: null },
  43069. lightMapIntensity: { value: 1 },
  43070. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43071. },
  43072. bumpmap: {
  43073. bumpMap: { value: null },
  43074. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43075. bumpScale: { value: 1 }
  43076. },
  43077. normalmap: {
  43078. normalMap: { value: null },
  43079. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43080. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43081. },
  43082. displacementmap: {
  43083. displacementMap: { value: null },
  43084. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43085. displacementScale: { value: 1 },
  43086. displacementBias: { value: 0 }
  43087. },
  43088. emissivemap: {
  43089. emissiveMap: { value: null },
  43090. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43091. },
  43092. metalnessmap: {
  43093. metalnessMap: { value: null },
  43094. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43095. },
  43096. roughnessmap: {
  43097. roughnessMap: { value: null },
  43098. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43099. },
  43100. gradientmap: {
  43101. gradientMap: { value: null }
  43102. },
  43103. fog: {
  43104. fogDensity: { value: 0.00025 },
  43105. fogNear: { value: 1 },
  43106. fogFar: { value: 2000 },
  43107. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43108. },
  43109. lights: {
  43110. ambientLightColor: { value: [] },
  43111. lightProbe: { value: [] },
  43112. directionalLights: { value: [], properties: {
  43113. direction: {},
  43114. color: {}
  43115. } },
  43116. directionalLightShadows: { value: [], properties: {
  43117. shadowIntensity: 1,
  43118. shadowBias: {},
  43119. shadowNormalBias: {},
  43120. shadowRadius: {},
  43121. shadowMapSize: {}
  43122. } },
  43123. directionalShadowMap: { value: [] },
  43124. directionalShadowMatrix: { value: [] },
  43125. spotLights: { value: [], properties: {
  43126. color: {},
  43127. position: {},
  43128. direction: {},
  43129. distance: {},
  43130. coneCos: {},
  43131. penumbraCos: {},
  43132. decay: {}
  43133. } },
  43134. spotLightShadows: { value: [], properties: {
  43135. shadowIntensity: 1,
  43136. shadowBias: {},
  43137. shadowNormalBias: {},
  43138. shadowRadius: {},
  43139. shadowMapSize: {}
  43140. } },
  43141. spotLightMap: { value: [] },
  43142. spotShadowMap: { value: [] },
  43143. spotLightMatrix: { value: [] },
  43144. pointLights: { value: [], properties: {
  43145. color: {},
  43146. position: {},
  43147. decay: {},
  43148. distance: {}
  43149. } },
  43150. pointLightShadows: { value: [], properties: {
  43151. shadowIntensity: 1,
  43152. shadowBias: {},
  43153. shadowNormalBias: {},
  43154. shadowRadius: {},
  43155. shadowMapSize: {},
  43156. shadowCameraNear: {},
  43157. shadowCameraFar: {}
  43158. } },
  43159. pointShadowMap: { value: [] },
  43160. pointShadowMatrix: { value: [] },
  43161. hemisphereLights: { value: [], properties: {
  43162. direction: {},
  43163. skyColor: {},
  43164. groundColor: {}
  43165. } },
  43166. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43167. rectAreaLights: { value: [], properties: {
  43168. color: {},
  43169. position: {},
  43170. width: {},
  43171. height: {}
  43172. } },
  43173. ltc_1: { value: null },
  43174. ltc_2: { value: null }
  43175. },
  43176. points: {
  43177. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43178. opacity: { value: 1.0 },
  43179. size: { value: 1.0 },
  43180. scale: { value: 1.0 },
  43181. map: { value: null },
  43182. alphaMap: { value: null },
  43183. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43184. alphaTest: { value: 0 },
  43185. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43186. },
  43187. sprite: {
  43188. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43189. opacity: { value: 1.0 },
  43190. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43191. rotation: { value: 0.0 },
  43192. map: { value: null },
  43193. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43194. alphaMap: { value: null },
  43195. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43196. alphaTest: { value: 0 }
  43197. }
  43198. };
  43199. const ShaderLib = {
  43200. basic: {
  43201. uniforms: /*@__PURE__*/ mergeUniforms( [
  43202. UniformsLib.common,
  43203. UniformsLib.specularmap,
  43204. UniformsLib.envmap,
  43205. UniformsLib.aomap,
  43206. UniformsLib.lightmap,
  43207. UniformsLib.fog
  43208. ] ),
  43209. vertexShader: ShaderChunk.meshbasic_vert,
  43210. fragmentShader: ShaderChunk.meshbasic_frag
  43211. },
  43212. lambert: {
  43213. uniforms: /*@__PURE__*/ mergeUniforms( [
  43214. UniformsLib.common,
  43215. UniformsLib.specularmap,
  43216. UniformsLib.envmap,
  43217. UniformsLib.aomap,
  43218. UniformsLib.lightmap,
  43219. UniformsLib.emissivemap,
  43220. UniformsLib.bumpmap,
  43221. UniformsLib.normalmap,
  43222. UniformsLib.displacementmap,
  43223. UniformsLib.fog,
  43224. UniformsLib.lights,
  43225. {
  43226. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43227. }
  43228. ] ),
  43229. vertexShader: ShaderChunk.meshlambert_vert,
  43230. fragmentShader: ShaderChunk.meshlambert_frag
  43231. },
  43232. phong: {
  43233. uniforms: /*@__PURE__*/ mergeUniforms( [
  43234. UniformsLib.common,
  43235. UniformsLib.specularmap,
  43236. UniformsLib.envmap,
  43237. UniformsLib.aomap,
  43238. UniformsLib.lightmap,
  43239. UniformsLib.emissivemap,
  43240. UniformsLib.bumpmap,
  43241. UniformsLib.normalmap,
  43242. UniformsLib.displacementmap,
  43243. UniformsLib.fog,
  43244. UniformsLib.lights,
  43245. {
  43246. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43247. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43248. shininess: { value: 30 }
  43249. }
  43250. ] ),
  43251. vertexShader: ShaderChunk.meshphong_vert,
  43252. fragmentShader: ShaderChunk.meshphong_frag
  43253. },
  43254. standard: {
  43255. uniforms: /*@__PURE__*/ mergeUniforms( [
  43256. UniformsLib.common,
  43257. UniformsLib.envmap,
  43258. UniformsLib.aomap,
  43259. UniformsLib.lightmap,
  43260. UniformsLib.emissivemap,
  43261. UniformsLib.bumpmap,
  43262. UniformsLib.normalmap,
  43263. UniformsLib.displacementmap,
  43264. UniformsLib.roughnessmap,
  43265. UniformsLib.metalnessmap,
  43266. UniformsLib.fog,
  43267. UniformsLib.lights,
  43268. {
  43269. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43270. roughness: { value: 1.0 },
  43271. metalness: { value: 0.0 },
  43272. envMapIntensity: { value: 1 }
  43273. }
  43274. ] ),
  43275. vertexShader: ShaderChunk.meshphysical_vert,
  43276. fragmentShader: ShaderChunk.meshphysical_frag
  43277. },
  43278. toon: {
  43279. uniforms: /*@__PURE__*/ mergeUniforms( [
  43280. UniformsLib.common,
  43281. UniformsLib.aomap,
  43282. UniformsLib.lightmap,
  43283. UniformsLib.emissivemap,
  43284. UniformsLib.bumpmap,
  43285. UniformsLib.normalmap,
  43286. UniformsLib.displacementmap,
  43287. UniformsLib.gradientmap,
  43288. UniformsLib.fog,
  43289. UniformsLib.lights,
  43290. {
  43291. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43292. }
  43293. ] ),
  43294. vertexShader: ShaderChunk.meshtoon_vert,
  43295. fragmentShader: ShaderChunk.meshtoon_frag
  43296. },
  43297. matcap: {
  43298. uniforms: /*@__PURE__*/ mergeUniforms( [
  43299. UniformsLib.common,
  43300. UniformsLib.bumpmap,
  43301. UniformsLib.normalmap,
  43302. UniformsLib.displacementmap,
  43303. UniformsLib.fog,
  43304. {
  43305. matcap: { value: null }
  43306. }
  43307. ] ),
  43308. vertexShader: ShaderChunk.meshmatcap_vert,
  43309. fragmentShader: ShaderChunk.meshmatcap_frag
  43310. },
  43311. points: {
  43312. uniforms: /*@__PURE__*/ mergeUniforms( [
  43313. UniformsLib.points,
  43314. UniformsLib.fog
  43315. ] ),
  43316. vertexShader: ShaderChunk.points_vert,
  43317. fragmentShader: ShaderChunk.points_frag
  43318. },
  43319. dashed: {
  43320. uniforms: /*@__PURE__*/ mergeUniforms( [
  43321. UniformsLib.common,
  43322. UniformsLib.fog,
  43323. {
  43324. scale: { value: 1 },
  43325. dashSize: { value: 1 },
  43326. totalSize: { value: 2 }
  43327. }
  43328. ] ),
  43329. vertexShader: ShaderChunk.linedashed_vert,
  43330. fragmentShader: ShaderChunk.linedashed_frag
  43331. },
  43332. depth: {
  43333. uniforms: /*@__PURE__*/ mergeUniforms( [
  43334. UniformsLib.common,
  43335. UniformsLib.displacementmap
  43336. ] ),
  43337. vertexShader: ShaderChunk.depth_vert,
  43338. fragmentShader: ShaderChunk.depth_frag
  43339. },
  43340. normal: {
  43341. uniforms: /*@__PURE__*/ mergeUniforms( [
  43342. UniformsLib.common,
  43343. UniformsLib.bumpmap,
  43344. UniformsLib.normalmap,
  43345. UniformsLib.displacementmap,
  43346. {
  43347. opacity: { value: 1.0 }
  43348. }
  43349. ] ),
  43350. vertexShader: ShaderChunk.meshnormal_vert,
  43351. fragmentShader: ShaderChunk.meshnormal_frag
  43352. },
  43353. sprite: {
  43354. uniforms: /*@__PURE__*/ mergeUniforms( [
  43355. UniformsLib.sprite,
  43356. UniformsLib.fog
  43357. ] ),
  43358. vertexShader: ShaderChunk.sprite_vert,
  43359. fragmentShader: ShaderChunk.sprite_frag
  43360. },
  43361. background: {
  43362. uniforms: {
  43363. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43364. t2D: { value: null },
  43365. backgroundIntensity: { value: 1 }
  43366. },
  43367. vertexShader: ShaderChunk.background_vert,
  43368. fragmentShader: ShaderChunk.background_frag
  43369. },
  43370. backgroundCube: {
  43371. uniforms: {
  43372. envMap: { value: null },
  43373. flipEnvMap: { value: -1 },
  43374. backgroundBlurriness: { value: 0 },
  43375. backgroundIntensity: { value: 1 },
  43376. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43377. },
  43378. vertexShader: ShaderChunk.backgroundCube_vert,
  43379. fragmentShader: ShaderChunk.backgroundCube_frag
  43380. },
  43381. cube: {
  43382. uniforms: {
  43383. tCube: { value: null },
  43384. tFlip: { value: -1 },
  43385. opacity: { value: 1.0 }
  43386. },
  43387. vertexShader: ShaderChunk.cube_vert,
  43388. fragmentShader: ShaderChunk.cube_frag
  43389. },
  43390. equirect: {
  43391. uniforms: {
  43392. tEquirect: { value: null },
  43393. },
  43394. vertexShader: ShaderChunk.equirect_vert,
  43395. fragmentShader: ShaderChunk.equirect_frag
  43396. },
  43397. distanceRGBA: {
  43398. uniforms: /*@__PURE__*/ mergeUniforms( [
  43399. UniformsLib.common,
  43400. UniformsLib.displacementmap,
  43401. {
  43402. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43403. nearDistance: { value: 1 },
  43404. farDistance: { value: 1000 }
  43405. }
  43406. ] ),
  43407. vertexShader: ShaderChunk.distanceRGBA_vert,
  43408. fragmentShader: ShaderChunk.distanceRGBA_frag
  43409. },
  43410. shadow: {
  43411. uniforms: /*@__PURE__*/ mergeUniforms( [
  43412. UniformsLib.lights,
  43413. UniformsLib.fog,
  43414. {
  43415. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43416. opacity: { value: 1.0 }
  43417. },
  43418. ] ),
  43419. vertexShader: ShaderChunk.shadow_vert,
  43420. fragmentShader: ShaderChunk.shadow_frag
  43421. }
  43422. };
  43423. ShaderLib.physical = {
  43424. uniforms: /*@__PURE__*/ mergeUniforms( [
  43425. ShaderLib.standard.uniforms,
  43426. {
  43427. clearcoat: { value: 0 },
  43428. clearcoatMap: { value: null },
  43429. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43430. clearcoatNormalMap: { value: null },
  43431. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43432. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43433. clearcoatRoughness: { value: 0 },
  43434. clearcoatRoughnessMap: { value: null },
  43435. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43436. dispersion: { value: 0 },
  43437. iridescence: { value: 0 },
  43438. iridescenceMap: { value: null },
  43439. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43440. iridescenceIOR: { value: 1.3 },
  43441. iridescenceThicknessMinimum: { value: 100 },
  43442. iridescenceThicknessMaximum: { value: 400 },
  43443. iridescenceThicknessMap: { value: null },
  43444. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43445. sheen: { value: 0 },
  43446. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43447. sheenColorMap: { value: null },
  43448. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43449. sheenRoughness: { value: 1 },
  43450. sheenRoughnessMap: { value: null },
  43451. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43452. transmission: { value: 0 },
  43453. transmissionMap: { value: null },
  43454. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43455. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43456. transmissionSamplerMap: { value: null },
  43457. thickness: { value: 0 },
  43458. thicknessMap: { value: null },
  43459. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43460. attenuationDistance: { value: 0 },
  43461. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43462. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43463. specularColorMap: { value: null },
  43464. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43465. specularIntensity: { value: 1 },
  43466. specularIntensityMap: { value: null },
  43467. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43468. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43469. anisotropyMap: { value: null },
  43470. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43471. }
  43472. ] ),
  43473. vertexShader: ShaderChunk.meshphysical_vert,
  43474. fragmentShader: ShaderChunk.meshphysical_frag
  43475. };
  43476. const _rgb = { r: 0, b: 0, g: 0 };
  43477. const _e1$1 = /*@__PURE__*/ new Euler();
  43478. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43479. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43480. const clearColor = new Color( 0x000000 );
  43481. let clearAlpha = alpha === true ? 0 : 1;
  43482. let planeMesh;
  43483. let boxMesh;
  43484. let currentBackground = null;
  43485. let currentBackgroundVersion = 0;
  43486. let currentTonemapping = null;
  43487. function getBackground( scene ) {
  43488. let background = scene.isScene === true ? scene.background : null;
  43489. if ( background && background.isTexture ) {
  43490. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43491. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43492. }
  43493. return background;
  43494. }
  43495. function render( scene ) {
  43496. let forceClear = false;
  43497. const background = getBackground( scene );
  43498. if ( background === null ) {
  43499. setClear( clearColor, clearAlpha );
  43500. } else if ( background && background.isColor ) {
  43501. setClear( background, 1 );
  43502. forceClear = true;
  43503. }
  43504. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43505. if ( environmentBlendMode === 'additive' ) {
  43506. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43507. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43508. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43509. }
  43510. if ( renderer.autoClear || forceClear ) {
  43511. // buffers might not be writable which is required to ensure a correct clear
  43512. state.buffers.depth.setTest( true );
  43513. state.buffers.depth.setMask( true );
  43514. state.buffers.color.setMask( true );
  43515. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43516. }
  43517. }
  43518. function addToRenderList( renderList, scene ) {
  43519. const background = getBackground( scene );
  43520. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43521. if ( boxMesh === undefined ) {
  43522. boxMesh = new Mesh(
  43523. new BoxGeometry( 1, 1, 1 ),
  43524. new ShaderMaterial( {
  43525. name: 'BackgroundCubeMaterial',
  43526. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43527. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43528. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43529. side: BackSide,
  43530. depthTest: false,
  43531. depthWrite: false,
  43532. fog: false,
  43533. allowOverride: false
  43534. } )
  43535. );
  43536. boxMesh.geometry.deleteAttribute( 'normal' );
  43537. boxMesh.geometry.deleteAttribute( 'uv' );
  43538. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43539. this.matrixWorld.copyPosition( camera.matrixWorld );
  43540. };
  43541. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43542. Object.defineProperty( boxMesh.material, 'envMap', {
  43543. get: function () {
  43544. return this.uniforms.envMap.value;
  43545. }
  43546. } );
  43547. objects.update( boxMesh );
  43548. }
  43549. _e1$1.copy( scene.backgroundRotation );
  43550. // accommodate left-handed frame
  43551. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43552. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43553. // environment maps which are not cube render targets or PMREMs follow a different convention
  43554. _e1$1.y *= -1;
  43555. _e1$1.z *= -1;
  43556. }
  43557. boxMesh.material.uniforms.envMap.value = background;
  43558. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43559. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43560. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43561. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43562. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43563. if ( currentBackground !== background ||
  43564. currentBackgroundVersion !== background.version ||
  43565. currentTonemapping !== renderer.toneMapping ) {
  43566. boxMesh.material.needsUpdate = true;
  43567. currentBackground = background;
  43568. currentBackgroundVersion = background.version;
  43569. currentTonemapping = renderer.toneMapping;
  43570. }
  43571. boxMesh.layers.enableAll();
  43572. // push to the pre-sorted opaque render list
  43573. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43574. } else if ( background && background.isTexture ) {
  43575. if ( planeMesh === undefined ) {
  43576. planeMesh = new Mesh(
  43577. new PlaneGeometry( 2, 2 ),
  43578. new ShaderMaterial( {
  43579. name: 'BackgroundMaterial',
  43580. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43581. vertexShader: ShaderLib.background.vertexShader,
  43582. fragmentShader: ShaderLib.background.fragmentShader,
  43583. side: FrontSide,
  43584. depthTest: false,
  43585. depthWrite: false,
  43586. fog: false,
  43587. allowOverride: false
  43588. } )
  43589. );
  43590. planeMesh.geometry.deleteAttribute( 'normal' );
  43591. // add "map" material property so the renderer can evaluate it like for built-in materials
  43592. Object.defineProperty( planeMesh.material, 'map', {
  43593. get: function () {
  43594. return this.uniforms.t2D.value;
  43595. }
  43596. } );
  43597. objects.update( planeMesh );
  43598. }
  43599. planeMesh.material.uniforms.t2D.value = background;
  43600. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43601. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43602. if ( background.matrixAutoUpdate === true ) {
  43603. background.updateMatrix();
  43604. }
  43605. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43606. if ( currentBackground !== background ||
  43607. currentBackgroundVersion !== background.version ||
  43608. currentTonemapping !== renderer.toneMapping ) {
  43609. planeMesh.material.needsUpdate = true;
  43610. currentBackground = background;
  43611. currentBackgroundVersion = background.version;
  43612. currentTonemapping = renderer.toneMapping;
  43613. }
  43614. planeMesh.layers.enableAll();
  43615. // push to the pre-sorted opaque render list
  43616. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43617. }
  43618. }
  43619. function setClear( color, alpha ) {
  43620. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43621. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43622. }
  43623. function dispose() {
  43624. if ( boxMesh !== undefined ) {
  43625. boxMesh.geometry.dispose();
  43626. boxMesh.material.dispose();
  43627. boxMesh = undefined;
  43628. }
  43629. if ( planeMesh !== undefined ) {
  43630. planeMesh.geometry.dispose();
  43631. planeMesh.material.dispose();
  43632. planeMesh = undefined;
  43633. }
  43634. }
  43635. return {
  43636. getClearColor: function () {
  43637. return clearColor;
  43638. },
  43639. setClearColor: function ( color, alpha = 1 ) {
  43640. clearColor.set( color );
  43641. clearAlpha = alpha;
  43642. setClear( clearColor, clearAlpha );
  43643. },
  43644. getClearAlpha: function () {
  43645. return clearAlpha;
  43646. },
  43647. setClearAlpha: function ( alpha ) {
  43648. clearAlpha = alpha;
  43649. setClear( clearColor, clearAlpha );
  43650. },
  43651. render: render,
  43652. addToRenderList: addToRenderList,
  43653. dispose: dispose
  43654. };
  43655. }
  43656. function WebGLBindingStates( gl, attributes ) {
  43657. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43658. const bindingStates = {};
  43659. const defaultState = createBindingState( null );
  43660. let currentState = defaultState;
  43661. let forceUpdate = false;
  43662. function setup( object, material, program, geometry, index ) {
  43663. let updateBuffers = false;
  43664. const state = getBindingState( geometry, program, material );
  43665. if ( currentState !== state ) {
  43666. currentState = state;
  43667. bindVertexArrayObject( currentState.object );
  43668. }
  43669. updateBuffers = needsUpdate( object, geometry, program, index );
  43670. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43671. if ( index !== null ) {
  43672. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43673. }
  43674. if ( updateBuffers || forceUpdate ) {
  43675. forceUpdate = false;
  43676. setupVertexAttributes( object, material, program, geometry );
  43677. if ( index !== null ) {
  43678. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43679. }
  43680. }
  43681. }
  43682. function createVertexArrayObject() {
  43683. return gl.createVertexArray();
  43684. }
  43685. function bindVertexArrayObject( vao ) {
  43686. return gl.bindVertexArray( vao );
  43687. }
  43688. function deleteVertexArrayObject( vao ) {
  43689. return gl.deleteVertexArray( vao );
  43690. }
  43691. function getBindingState( geometry, program, material ) {
  43692. const wireframe = ( material.wireframe === true );
  43693. let programMap = bindingStates[ geometry.id ];
  43694. if ( programMap === undefined ) {
  43695. programMap = {};
  43696. bindingStates[ geometry.id ] = programMap;
  43697. }
  43698. let stateMap = programMap[ program.id ];
  43699. if ( stateMap === undefined ) {
  43700. stateMap = {};
  43701. programMap[ program.id ] = stateMap;
  43702. }
  43703. let state = stateMap[ wireframe ];
  43704. if ( state === undefined ) {
  43705. state = createBindingState( createVertexArrayObject() );
  43706. stateMap[ wireframe ] = state;
  43707. }
  43708. return state;
  43709. }
  43710. function createBindingState( vao ) {
  43711. const newAttributes = [];
  43712. const enabledAttributes = [];
  43713. const attributeDivisors = [];
  43714. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43715. newAttributes[ i ] = 0;
  43716. enabledAttributes[ i ] = 0;
  43717. attributeDivisors[ i ] = 0;
  43718. }
  43719. return {
  43720. // for backward compatibility on non-VAO support browser
  43721. geometry: null,
  43722. program: null,
  43723. wireframe: false,
  43724. newAttributes: newAttributes,
  43725. enabledAttributes: enabledAttributes,
  43726. attributeDivisors: attributeDivisors,
  43727. object: vao,
  43728. attributes: {},
  43729. index: null
  43730. };
  43731. }
  43732. function needsUpdate( object, geometry, program, index ) {
  43733. const cachedAttributes = currentState.attributes;
  43734. const geometryAttributes = geometry.attributes;
  43735. let attributesNum = 0;
  43736. const programAttributes = program.getAttributes();
  43737. for ( const name in programAttributes ) {
  43738. const programAttribute = programAttributes[ name ];
  43739. if ( programAttribute.location >= 0 ) {
  43740. const cachedAttribute = cachedAttributes[ name ];
  43741. let geometryAttribute = geometryAttributes[ name ];
  43742. if ( geometryAttribute === undefined ) {
  43743. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43744. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43745. }
  43746. if ( cachedAttribute === undefined ) return true;
  43747. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43748. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43749. attributesNum ++;
  43750. }
  43751. }
  43752. if ( currentState.attributesNum !== attributesNum ) return true;
  43753. if ( currentState.index !== index ) return true;
  43754. return false;
  43755. }
  43756. function saveCache( object, geometry, program, index ) {
  43757. const cache = {};
  43758. const attributes = geometry.attributes;
  43759. let attributesNum = 0;
  43760. const programAttributes = program.getAttributes();
  43761. for ( const name in programAttributes ) {
  43762. const programAttribute = programAttributes[ name ];
  43763. if ( programAttribute.location >= 0 ) {
  43764. let attribute = attributes[ name ];
  43765. if ( attribute === undefined ) {
  43766. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43767. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43768. }
  43769. const data = {};
  43770. data.attribute = attribute;
  43771. if ( attribute && attribute.data ) {
  43772. data.data = attribute.data;
  43773. }
  43774. cache[ name ] = data;
  43775. attributesNum ++;
  43776. }
  43777. }
  43778. currentState.attributes = cache;
  43779. currentState.attributesNum = attributesNum;
  43780. currentState.index = index;
  43781. }
  43782. function initAttributes() {
  43783. const newAttributes = currentState.newAttributes;
  43784. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43785. newAttributes[ i ] = 0;
  43786. }
  43787. }
  43788. function enableAttribute( attribute ) {
  43789. enableAttributeAndDivisor( attribute, 0 );
  43790. }
  43791. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43792. const newAttributes = currentState.newAttributes;
  43793. const enabledAttributes = currentState.enabledAttributes;
  43794. const attributeDivisors = currentState.attributeDivisors;
  43795. newAttributes[ attribute ] = 1;
  43796. if ( enabledAttributes[ attribute ] === 0 ) {
  43797. gl.enableVertexAttribArray( attribute );
  43798. enabledAttributes[ attribute ] = 1;
  43799. }
  43800. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43801. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43802. attributeDivisors[ attribute ] = meshPerAttribute;
  43803. }
  43804. }
  43805. function disableUnusedAttributes() {
  43806. const newAttributes = currentState.newAttributes;
  43807. const enabledAttributes = currentState.enabledAttributes;
  43808. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43809. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43810. gl.disableVertexAttribArray( i );
  43811. enabledAttributes[ i ] = 0;
  43812. }
  43813. }
  43814. }
  43815. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43816. if ( integer === true ) {
  43817. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43818. } else {
  43819. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43820. }
  43821. }
  43822. function setupVertexAttributes( object, material, program, geometry ) {
  43823. initAttributes();
  43824. const geometryAttributes = geometry.attributes;
  43825. const programAttributes = program.getAttributes();
  43826. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43827. for ( const name in programAttributes ) {
  43828. const programAttribute = programAttributes[ name ];
  43829. if ( programAttribute.location >= 0 ) {
  43830. let geometryAttribute = geometryAttributes[ name ];
  43831. if ( geometryAttribute === undefined ) {
  43832. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43833. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43834. }
  43835. if ( geometryAttribute !== undefined ) {
  43836. const normalized = geometryAttribute.normalized;
  43837. const size = geometryAttribute.itemSize;
  43838. const attribute = attributes.get( geometryAttribute );
  43839. // TODO Attribute may not be available on context restore
  43840. if ( attribute === undefined ) continue;
  43841. const buffer = attribute.buffer;
  43842. const type = attribute.type;
  43843. const bytesPerElement = attribute.bytesPerElement;
  43844. // check for integer attributes
  43845. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  43846. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  43847. const data = geometryAttribute.data;
  43848. const stride = data.stride;
  43849. const offset = geometryAttribute.offset;
  43850. if ( data.isInstancedInterleavedBuffer ) {
  43851. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43852. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  43853. }
  43854. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43855. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  43856. }
  43857. } else {
  43858. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43859. enableAttribute( programAttribute.location + i );
  43860. }
  43861. }
  43862. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43863. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43864. vertexAttribPointer(
  43865. programAttribute.location + i,
  43866. size / programAttribute.locationSize,
  43867. type,
  43868. normalized,
  43869. stride * bytesPerElement,
  43870. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  43871. integer
  43872. );
  43873. }
  43874. } else {
  43875. if ( geometryAttribute.isInstancedBufferAttribute ) {
  43876. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43877. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  43878. }
  43879. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  43880. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  43881. }
  43882. } else {
  43883. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43884. enableAttribute( programAttribute.location + i );
  43885. }
  43886. }
  43887. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  43888. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  43889. vertexAttribPointer(
  43890. programAttribute.location + i,
  43891. size / programAttribute.locationSize,
  43892. type,
  43893. normalized,
  43894. size * bytesPerElement,
  43895. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  43896. integer
  43897. );
  43898. }
  43899. }
  43900. } else if ( materialDefaultAttributeValues !== undefined ) {
  43901. const value = materialDefaultAttributeValues[ name ];
  43902. if ( value !== undefined ) {
  43903. switch ( value.length ) {
  43904. case 2:
  43905. gl.vertexAttrib2fv( programAttribute.location, value );
  43906. break;
  43907. case 3:
  43908. gl.vertexAttrib3fv( programAttribute.location, value );
  43909. break;
  43910. case 4:
  43911. gl.vertexAttrib4fv( programAttribute.location, value );
  43912. break;
  43913. default:
  43914. gl.vertexAttrib1fv( programAttribute.location, value );
  43915. }
  43916. }
  43917. }
  43918. }
  43919. }
  43920. disableUnusedAttributes();
  43921. }
  43922. function dispose() {
  43923. reset();
  43924. for ( const geometryId in bindingStates ) {
  43925. const programMap = bindingStates[ geometryId ];
  43926. for ( const programId in programMap ) {
  43927. const stateMap = programMap[ programId ];
  43928. for ( const wireframe in stateMap ) {
  43929. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43930. delete stateMap[ wireframe ];
  43931. }
  43932. delete programMap[ programId ];
  43933. }
  43934. delete bindingStates[ geometryId ];
  43935. }
  43936. }
  43937. function releaseStatesOfGeometry( geometry ) {
  43938. if ( bindingStates[ geometry.id ] === undefined ) return;
  43939. const programMap = bindingStates[ geometry.id ];
  43940. for ( const programId in programMap ) {
  43941. const stateMap = programMap[ programId ];
  43942. for ( const wireframe in stateMap ) {
  43943. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43944. delete stateMap[ wireframe ];
  43945. }
  43946. delete programMap[ programId ];
  43947. }
  43948. delete bindingStates[ geometry.id ];
  43949. }
  43950. function releaseStatesOfProgram( program ) {
  43951. for ( const geometryId in bindingStates ) {
  43952. const programMap = bindingStates[ geometryId ];
  43953. if ( programMap[ program.id ] === undefined ) continue;
  43954. const stateMap = programMap[ program.id ];
  43955. for ( const wireframe in stateMap ) {
  43956. deleteVertexArrayObject( stateMap[ wireframe ].object );
  43957. delete stateMap[ wireframe ];
  43958. }
  43959. delete programMap[ program.id ];
  43960. }
  43961. }
  43962. function reset() {
  43963. resetDefaultState();
  43964. forceUpdate = true;
  43965. if ( currentState === defaultState ) return;
  43966. currentState = defaultState;
  43967. bindVertexArrayObject( currentState.object );
  43968. }
  43969. // for backward-compatibility
  43970. function resetDefaultState() {
  43971. defaultState.geometry = null;
  43972. defaultState.program = null;
  43973. defaultState.wireframe = false;
  43974. }
  43975. return {
  43976. setup: setup,
  43977. reset: reset,
  43978. resetDefaultState: resetDefaultState,
  43979. dispose: dispose,
  43980. releaseStatesOfGeometry: releaseStatesOfGeometry,
  43981. releaseStatesOfProgram: releaseStatesOfProgram,
  43982. initAttributes: initAttributes,
  43983. enableAttribute: enableAttribute,
  43984. disableUnusedAttributes: disableUnusedAttributes
  43985. };
  43986. }
  43987. function WebGLBufferRenderer( gl, extensions, info ) {
  43988. let mode;
  43989. function setMode( value ) {
  43990. mode = value;
  43991. }
  43992. function render( start, count ) {
  43993. gl.drawArrays( mode, start, count );
  43994. info.update( count, mode, 1 );
  43995. }
  43996. function renderInstances( start, count, primcount ) {
  43997. if ( primcount === 0 ) return;
  43998. gl.drawArraysInstanced( mode, start, count, primcount );
  43999. info.update( count, mode, primcount );
  44000. }
  44001. function renderMultiDraw( starts, counts, drawCount ) {
  44002. if ( drawCount === 0 ) return;
  44003. const extension = extensions.get( 'WEBGL_multi_draw' );
  44004. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44005. let elementCount = 0;
  44006. for ( let i = 0; i < drawCount; i ++ ) {
  44007. elementCount += counts[ i ];
  44008. }
  44009. info.update( elementCount, mode, 1 );
  44010. }
  44011. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44012. if ( drawCount === 0 ) return;
  44013. const extension = extensions.get( 'WEBGL_multi_draw' );
  44014. if ( extension === null ) {
  44015. for ( let i = 0; i < starts.length; i ++ ) {
  44016. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44017. }
  44018. } else {
  44019. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44020. let elementCount = 0;
  44021. for ( let i = 0; i < drawCount; i ++ ) {
  44022. elementCount += counts[ i ] * primcount[ i ];
  44023. }
  44024. info.update( elementCount, mode, 1 );
  44025. }
  44026. }
  44027. //
  44028. this.setMode = setMode;
  44029. this.render = render;
  44030. this.renderInstances = renderInstances;
  44031. this.renderMultiDraw = renderMultiDraw;
  44032. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44033. }
  44034. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44035. let maxAnisotropy;
  44036. function getMaxAnisotropy() {
  44037. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44038. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44039. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44040. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44041. } else {
  44042. maxAnisotropy = 0;
  44043. }
  44044. return maxAnisotropy;
  44045. }
  44046. function textureFormatReadable( textureFormat ) {
  44047. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44048. return false;
  44049. }
  44050. return true;
  44051. }
  44052. function textureTypeReadable( textureType ) {
  44053. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44054. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44055. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44056. return false;
  44057. }
  44058. return true;
  44059. }
  44060. function getMaxPrecision( precision ) {
  44061. if ( precision === 'highp' ) {
  44062. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44063. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44064. return 'highp';
  44065. }
  44066. precision = 'mediump';
  44067. }
  44068. if ( precision === 'mediump' ) {
  44069. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44070. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44071. return 'mediump';
  44072. }
  44073. }
  44074. return 'lowp';
  44075. }
  44076. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44077. const maxPrecision = getMaxPrecision( precision );
  44078. if ( maxPrecision !== precision ) {
  44079. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44080. precision = maxPrecision;
  44081. }
  44082. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44083. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44084. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44085. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44086. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44087. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44088. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44089. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44090. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44091. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44092. const vertexTextures = maxVertexTextures > 0;
  44093. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44094. return {
  44095. isWebGL2: true, // keeping this for backwards compatibility
  44096. getMaxAnisotropy: getMaxAnisotropy,
  44097. getMaxPrecision: getMaxPrecision,
  44098. textureFormatReadable: textureFormatReadable,
  44099. textureTypeReadable: textureTypeReadable,
  44100. precision: precision,
  44101. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44102. reversedDepthBuffer: reversedDepthBuffer,
  44103. maxTextures: maxTextures,
  44104. maxVertexTextures: maxVertexTextures,
  44105. maxTextureSize: maxTextureSize,
  44106. maxCubemapSize: maxCubemapSize,
  44107. maxAttributes: maxAttributes,
  44108. maxVertexUniforms: maxVertexUniforms,
  44109. maxVaryings: maxVaryings,
  44110. maxFragmentUniforms: maxFragmentUniforms,
  44111. vertexTextures: vertexTextures,
  44112. maxSamples: maxSamples
  44113. };
  44114. }
  44115. function WebGLClipping( properties ) {
  44116. const scope = this;
  44117. let globalState = null,
  44118. numGlobalPlanes = 0,
  44119. localClippingEnabled = false,
  44120. renderingShadows = false;
  44121. const plane = new Plane(),
  44122. viewNormalMatrix = new Matrix3(),
  44123. uniform = { value: null, needsUpdate: false };
  44124. this.uniform = uniform;
  44125. this.numPlanes = 0;
  44126. this.numIntersection = 0;
  44127. this.init = function ( planes, enableLocalClipping ) {
  44128. const enabled =
  44129. planes.length !== 0 ||
  44130. enableLocalClipping ||
  44131. // enable state of previous frame - the clipping code has to
  44132. // run another frame in order to reset the state:
  44133. numGlobalPlanes !== 0 ||
  44134. localClippingEnabled;
  44135. localClippingEnabled = enableLocalClipping;
  44136. numGlobalPlanes = planes.length;
  44137. return enabled;
  44138. };
  44139. this.beginShadows = function () {
  44140. renderingShadows = true;
  44141. projectPlanes( null );
  44142. };
  44143. this.endShadows = function () {
  44144. renderingShadows = false;
  44145. };
  44146. this.setGlobalState = function ( planes, camera ) {
  44147. globalState = projectPlanes( planes, camera, 0 );
  44148. };
  44149. this.setState = function ( material, camera, useCache ) {
  44150. const planes = material.clippingPlanes,
  44151. clipIntersection = material.clipIntersection,
  44152. clipShadows = material.clipShadows;
  44153. const materialProperties = properties.get( material );
  44154. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44155. // there's no local clipping
  44156. if ( renderingShadows ) {
  44157. // there's no global clipping
  44158. projectPlanes( null );
  44159. } else {
  44160. resetGlobalState();
  44161. }
  44162. } else {
  44163. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44164. lGlobal = nGlobal * 4;
  44165. let dstArray = materialProperties.clippingState || null;
  44166. uniform.value = dstArray; // ensure unique state
  44167. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44168. for ( let i = 0; i !== lGlobal; ++ i ) {
  44169. dstArray[ i ] = globalState[ i ];
  44170. }
  44171. materialProperties.clippingState = dstArray;
  44172. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44173. this.numPlanes += nGlobal;
  44174. }
  44175. };
  44176. function resetGlobalState() {
  44177. if ( uniform.value !== globalState ) {
  44178. uniform.value = globalState;
  44179. uniform.needsUpdate = numGlobalPlanes > 0;
  44180. }
  44181. scope.numPlanes = numGlobalPlanes;
  44182. scope.numIntersection = 0;
  44183. }
  44184. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44185. const nPlanes = planes !== null ? planes.length : 0;
  44186. let dstArray = null;
  44187. if ( nPlanes !== 0 ) {
  44188. dstArray = uniform.value;
  44189. if ( skipTransform !== true || dstArray === null ) {
  44190. const flatSize = dstOffset + nPlanes * 4,
  44191. viewMatrix = camera.matrixWorldInverse;
  44192. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44193. if ( dstArray === null || dstArray.length < flatSize ) {
  44194. dstArray = new Float32Array( flatSize );
  44195. }
  44196. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44197. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44198. plane.normal.toArray( dstArray, i4 );
  44199. dstArray[ i4 + 3 ] = plane.constant;
  44200. }
  44201. }
  44202. uniform.value = dstArray;
  44203. uniform.needsUpdate = true;
  44204. }
  44205. scope.numPlanes = nPlanes;
  44206. scope.numIntersection = 0;
  44207. return dstArray;
  44208. }
  44209. }
  44210. function WebGLCubeMaps( renderer ) {
  44211. let cubemaps = new WeakMap();
  44212. function mapTextureMapping( texture, mapping ) {
  44213. if ( mapping === EquirectangularReflectionMapping ) {
  44214. texture.mapping = CubeReflectionMapping;
  44215. } else if ( mapping === EquirectangularRefractionMapping ) {
  44216. texture.mapping = CubeRefractionMapping;
  44217. }
  44218. return texture;
  44219. }
  44220. function get( texture ) {
  44221. if ( texture && texture.isTexture ) {
  44222. const mapping = texture.mapping;
  44223. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44224. if ( cubemaps.has( texture ) ) {
  44225. const cubemap = cubemaps.get( texture ).texture;
  44226. return mapTextureMapping( cubemap, texture.mapping );
  44227. } else {
  44228. const image = texture.image;
  44229. if ( image && image.height > 0 ) {
  44230. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44231. renderTarget.fromEquirectangularTexture( renderer, texture );
  44232. cubemaps.set( texture, renderTarget );
  44233. texture.addEventListener( 'dispose', onTextureDispose );
  44234. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44235. } else {
  44236. // image not yet ready. try the conversion next frame
  44237. return null;
  44238. }
  44239. }
  44240. }
  44241. }
  44242. return texture;
  44243. }
  44244. function onTextureDispose( event ) {
  44245. const texture = event.target;
  44246. texture.removeEventListener( 'dispose', onTextureDispose );
  44247. const cubemap = cubemaps.get( texture );
  44248. if ( cubemap !== undefined ) {
  44249. cubemaps.delete( texture );
  44250. cubemap.dispose();
  44251. }
  44252. }
  44253. function dispose() {
  44254. cubemaps = new WeakMap();
  44255. }
  44256. return {
  44257. get: get,
  44258. dispose: dispose
  44259. };
  44260. }
  44261. const LOD_MIN = 4;
  44262. // The standard deviations (radians) associated with the extra mips. These are
  44263. // chosen to approximate a Trowbridge-Reitz distribution function times the
  44264. // geometric shadowing function. These sigma values squared must match the
  44265. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  44266. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44267. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44268. // samples and exit early, but not recompile the shader.
  44269. const MAX_SAMPLES = 20;
  44270. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44271. const _clearColor = /*@__PURE__*/ new Color();
  44272. let _oldTarget = null;
  44273. let _oldActiveCubeFace = 0;
  44274. let _oldActiveMipmapLevel = 0;
  44275. let _oldXrEnabled = false;
  44276. // Golden Ratio
  44277. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  44278. const INV_PHI = 1 / PHI;
  44279. // Vertices of a dodecahedron (except the opposites, which represent the
  44280. // same axis), used as axis directions evenly spread on a sphere.
  44281. const _axisDirections = [
  44282. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  44283. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  44284. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  44285. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  44286. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  44287. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  44288. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  44289. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  44290. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  44291. /*@__PURE__*/ new Vector3( 1, 1, 1 ) ];
  44292. const _origin = /*@__PURE__*/ new Vector3();
  44293. /**
  44294. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44295. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44296. * blur to be quickly accessed based on material roughness. It is packed into a
  44297. * special CubeUV format that allows us to perform custom interpolation so that
  44298. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44299. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44300. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44301. * higher roughness levels. In this way we maintain resolution to smoothly
  44302. * interpolate diffuse lighting while limiting sampling computation.
  44303. *
  44304. * Paper: Fast, Accurate Image-Based Lighting:
  44305. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  44306. */
  44307. class PMREMGenerator {
  44308. /**
  44309. * Constructs a new PMREM generator.
  44310. *
  44311. * @param {WebGLRenderer} renderer - The renderer.
  44312. */
  44313. constructor( renderer ) {
  44314. this._renderer = renderer;
  44315. this._pingPongRenderTarget = null;
  44316. this._lodMax = 0;
  44317. this._cubeSize = 0;
  44318. this._lodPlanes = [];
  44319. this._sizeLods = [];
  44320. this._sigmas = [];
  44321. this._blurMaterial = null;
  44322. this._cubemapMaterial = null;
  44323. this._equirectMaterial = null;
  44324. this._compileMaterial( this._blurMaterial );
  44325. }
  44326. /**
  44327. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44328. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44329. * in radians to be applied to the scene before PMREM generation. Optional near
  44330. * and far planes ensure the scene is rendered in its entirety.
  44331. *
  44332. * @param {Scene} scene - The scene to be captured.
  44333. * @param {number} [sigma=0] - The blur radius in radians.
  44334. * @param {number} [near=0.1] - The near plane distance.
  44335. * @param {number} [far=100] - The far plane distance.
  44336. * @param {Object} [options={}] - The configuration options.
  44337. * @param {number} [options.size=256] - The texture size of the PMREM.
  44338. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  44339. * @return {WebGLRenderTarget} The resulting PMREM.
  44340. */
  44341. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44342. const {
  44343. size = 256,
  44344. position = _origin,
  44345. } = options;
  44346. _oldTarget = this._renderer.getRenderTarget();
  44347. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44348. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44349. _oldXrEnabled = this._renderer.xr.enabled;
  44350. this._renderer.xr.enabled = false;
  44351. this._setSize( size );
  44352. const cubeUVRenderTarget = this._allocateTargets();
  44353. cubeUVRenderTarget.depthBuffer = true;
  44354. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44355. if ( sigma > 0 ) {
  44356. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44357. }
  44358. this._applyPMREM( cubeUVRenderTarget );
  44359. this._cleanup( cubeUVRenderTarget );
  44360. return cubeUVRenderTarget;
  44361. }
  44362. /**
  44363. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44364. * or HDR. The ideal input image size is 1k (1024 x 512),
  44365. * as this matches best with the 256 x 256 cubemap output.
  44366. *
  44367. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44368. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44369. * @return {WebGLRenderTarget} The resulting PMREM.
  44370. */
  44371. fromEquirectangular( equirectangular, renderTarget = null ) {
  44372. return this._fromTexture( equirectangular, renderTarget );
  44373. }
  44374. /**
  44375. * Generates a PMREM from an cubemap texture, which can be either LDR
  44376. * or HDR. The ideal input cube size is 256 x 256,
  44377. * as this matches best with the 256 x 256 cubemap output.
  44378. *
  44379. * @param {Texture} cubemap - The cubemap texture to be converted.
  44380. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44381. * @return {WebGLRenderTarget} The resulting PMREM.
  44382. */
  44383. fromCubemap( cubemap, renderTarget = null ) {
  44384. return this._fromTexture( cubemap, renderTarget );
  44385. }
  44386. /**
  44387. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44388. * your texture's network fetch for increased concurrency.
  44389. */
  44390. compileCubemapShader() {
  44391. if ( this._cubemapMaterial === null ) {
  44392. this._cubemapMaterial = _getCubemapMaterial();
  44393. this._compileMaterial( this._cubemapMaterial );
  44394. }
  44395. }
  44396. /**
  44397. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44398. * your texture's network fetch for increased concurrency.
  44399. */
  44400. compileEquirectangularShader() {
  44401. if ( this._equirectMaterial === null ) {
  44402. this._equirectMaterial = _getEquirectMaterial();
  44403. this._compileMaterial( this._equirectMaterial );
  44404. }
  44405. }
  44406. /**
  44407. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44408. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44409. * one of them will cause any others to also become unusable.
  44410. */
  44411. dispose() {
  44412. this._dispose();
  44413. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44414. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44415. }
  44416. // private interface
  44417. _setSize( cubeSize ) {
  44418. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44419. this._cubeSize = Math.pow( 2, this._lodMax );
  44420. }
  44421. _dispose() {
  44422. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44423. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44424. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  44425. this._lodPlanes[ i ].dispose();
  44426. }
  44427. }
  44428. _cleanup( outputTarget ) {
  44429. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44430. this._renderer.xr.enabled = _oldXrEnabled;
  44431. outputTarget.scissorTest = false;
  44432. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44433. }
  44434. _fromTexture( texture, renderTarget ) {
  44435. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44436. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44437. } else { // Equirectangular
  44438. this._setSize( texture.image.width / 4 );
  44439. }
  44440. _oldTarget = this._renderer.getRenderTarget();
  44441. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44442. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44443. _oldXrEnabled = this._renderer.xr.enabled;
  44444. this._renderer.xr.enabled = false;
  44445. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44446. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44447. this._applyPMREM( cubeUVRenderTarget );
  44448. this._cleanup( cubeUVRenderTarget );
  44449. return cubeUVRenderTarget;
  44450. }
  44451. _allocateTargets() {
  44452. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44453. const height = 4 * this._cubeSize;
  44454. const params = {
  44455. magFilter: LinearFilter,
  44456. minFilter: LinearFilter,
  44457. generateMipmaps: false,
  44458. type: HalfFloatType,
  44459. format: RGBAFormat,
  44460. colorSpace: LinearSRGBColorSpace,
  44461. depthBuffer: false
  44462. };
  44463. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44464. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44465. if ( this._pingPongRenderTarget !== null ) {
  44466. this._dispose();
  44467. }
  44468. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44469. const { _lodMax } = this;
  44470. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44471. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44472. }
  44473. return cubeUVRenderTarget;
  44474. }
  44475. _compileMaterial( material ) {
  44476. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  44477. this._renderer.compile( tmpMesh, _flatCamera );
  44478. }
  44479. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44480. const fov = 90;
  44481. const aspect = 1;
  44482. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44483. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44484. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44485. const renderer = this._renderer;
  44486. const originalAutoClear = renderer.autoClear;
  44487. const toneMapping = renderer.toneMapping;
  44488. renderer.getClearColor( _clearColor );
  44489. renderer.toneMapping = NoToneMapping;
  44490. renderer.autoClear = false;
  44491. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44492. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44493. if ( reversedDepthBuffer ) {
  44494. renderer.setRenderTarget( cubeUVRenderTarget );
  44495. renderer.clearDepth();
  44496. renderer.setRenderTarget( null );
  44497. }
  44498. const backgroundMaterial = new MeshBasicMaterial( {
  44499. name: 'PMREM.Background',
  44500. side: BackSide,
  44501. depthWrite: false,
  44502. depthTest: false,
  44503. } );
  44504. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  44505. let useSolidColor = false;
  44506. const background = scene.background;
  44507. if ( background ) {
  44508. if ( background.isColor ) {
  44509. backgroundMaterial.color.copy( background );
  44510. scene.background = null;
  44511. useSolidColor = true;
  44512. }
  44513. } else {
  44514. backgroundMaterial.color.copy( _clearColor );
  44515. useSolidColor = true;
  44516. }
  44517. for ( let i = 0; i < 6; i ++ ) {
  44518. const col = i % 3;
  44519. if ( col === 0 ) {
  44520. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44521. cubeCamera.position.set( position.x, position.y, position.z );
  44522. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44523. } else if ( col === 1 ) {
  44524. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44525. cubeCamera.position.set( position.x, position.y, position.z );
  44526. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44527. } else {
  44528. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44529. cubeCamera.position.set( position.x, position.y, position.z );
  44530. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44531. }
  44532. const size = this._cubeSize;
  44533. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44534. renderer.setRenderTarget( cubeUVRenderTarget );
  44535. if ( useSolidColor ) {
  44536. renderer.render( backgroundBox, cubeCamera );
  44537. }
  44538. renderer.render( scene, cubeCamera );
  44539. }
  44540. backgroundBox.geometry.dispose();
  44541. backgroundBox.material.dispose();
  44542. renderer.toneMapping = toneMapping;
  44543. renderer.autoClear = originalAutoClear;
  44544. scene.background = background;
  44545. }
  44546. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44547. const renderer = this._renderer;
  44548. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44549. if ( isCubeTexture ) {
  44550. if ( this._cubemapMaterial === null ) {
  44551. this._cubemapMaterial = _getCubemapMaterial();
  44552. }
  44553. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44554. } else {
  44555. if ( this._equirectMaterial === null ) {
  44556. this._equirectMaterial = _getEquirectMaterial();
  44557. }
  44558. }
  44559. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44560. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  44561. const uniforms = material.uniforms;
  44562. uniforms[ 'envMap' ].value = texture;
  44563. const size = this._cubeSize;
  44564. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44565. renderer.setRenderTarget( cubeUVRenderTarget );
  44566. renderer.render( mesh, _flatCamera );
  44567. }
  44568. _applyPMREM( cubeUVRenderTarget ) {
  44569. const renderer = this._renderer;
  44570. const autoClear = renderer.autoClear;
  44571. renderer.autoClear = false;
  44572. const n = this._lodPlanes.length;
  44573. for ( let i = 1; i < n; i ++ ) {
  44574. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  44575. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  44576. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  44577. }
  44578. renderer.autoClear = autoClear;
  44579. }
  44580. /**
  44581. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44582. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44583. * the blur latitudinally (around the poles), and then longitudinally (towards
  44584. * the poles) to approximate the orthogonally-separable blur. It is least
  44585. * accurate at the poles, but still does a decent job.
  44586. *
  44587. * @private
  44588. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44589. * @param {number} lodIn
  44590. * @param {number} lodOut
  44591. * @param {number} sigma
  44592. * @param {Vector3} [poleAxis]
  44593. */
  44594. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44595. const pingPongRenderTarget = this._pingPongRenderTarget;
  44596. this._halfBlur(
  44597. cubeUVRenderTarget,
  44598. pingPongRenderTarget,
  44599. lodIn,
  44600. lodOut,
  44601. sigma,
  44602. 'latitudinal',
  44603. poleAxis );
  44604. this._halfBlur(
  44605. pingPongRenderTarget,
  44606. cubeUVRenderTarget,
  44607. lodOut,
  44608. lodOut,
  44609. sigma,
  44610. 'longitudinal',
  44611. poleAxis );
  44612. }
  44613. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44614. const renderer = this._renderer;
  44615. const blurMaterial = this._blurMaterial;
  44616. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44617. error(
  44618. 'blur direction must be either latitudinal or longitudinal!' );
  44619. }
  44620. // Number of standard deviations at which to cut off the discrete approximation.
  44621. const STANDARD_DEVIATIONS = 3;
  44622. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  44623. const blurUniforms = blurMaterial.uniforms;
  44624. const pixels = this._sizeLods[ lodIn ] - 1;
  44625. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44626. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44627. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44628. if ( samples > MAX_SAMPLES ) {
  44629. warn( `sigmaRadians, ${
  44630. sigmaRadians}, is too large and will clip, as it requested ${
  44631. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44632. }
  44633. const weights = [];
  44634. let sum = 0;
  44635. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44636. const x = i / sigmaPixels;
  44637. const weight = Math.exp( - x * x / 2 );
  44638. weights.push( weight );
  44639. if ( i === 0 ) {
  44640. sum += weight;
  44641. } else if ( i < samples ) {
  44642. sum += 2 * weight;
  44643. }
  44644. }
  44645. for ( let i = 0; i < weights.length; i ++ ) {
  44646. weights[ i ] = weights[ i ] / sum;
  44647. }
  44648. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44649. blurUniforms[ 'samples' ].value = samples;
  44650. blurUniforms[ 'weights' ].value = weights;
  44651. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44652. if ( poleAxis ) {
  44653. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44654. }
  44655. const { _lodMax } = this;
  44656. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44657. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44658. const outputSize = this._sizeLods[ lodOut ];
  44659. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44660. const y = 4 * ( this._cubeSize - outputSize );
  44661. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44662. renderer.setRenderTarget( targetOut );
  44663. renderer.render( blurMesh, _flatCamera );
  44664. }
  44665. }
  44666. function _createPlanes( lodMax ) {
  44667. const lodPlanes = [];
  44668. const sizeLods = [];
  44669. const sigmas = [];
  44670. let lod = lodMax;
  44671. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44672. for ( let i = 0; i < totalLods; i ++ ) {
  44673. const sizeLod = Math.pow( 2, lod );
  44674. sizeLods.push( sizeLod );
  44675. let sigma = 1.0 / sizeLod;
  44676. if ( i > lodMax - LOD_MIN ) {
  44677. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44678. } else if ( i === 0 ) {
  44679. sigma = 0;
  44680. }
  44681. sigmas.push( sigma );
  44682. const texelSize = 1.0 / ( sizeLod - 2 );
  44683. const min = - texelSize;
  44684. const max = 1 + texelSize;
  44685. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44686. const cubeFaces = 6;
  44687. const vertices = 6;
  44688. const positionSize = 3;
  44689. const uvSize = 2;
  44690. const faceIndexSize = 1;
  44691. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44692. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44693. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44694. for ( let face = 0; face < cubeFaces; face ++ ) {
  44695. const x = ( face % 3 ) * 2 / 3 - 1;
  44696. const y = face > 2 ? 0 : -1;
  44697. const coordinates = [
  44698. x, y, 0,
  44699. x + 2 / 3, y, 0,
  44700. x + 2 / 3, y + 1, 0,
  44701. x, y, 0,
  44702. x + 2 / 3, y + 1, 0,
  44703. x, y + 1, 0
  44704. ];
  44705. position.set( coordinates, positionSize * vertices * face );
  44706. uv.set( uv1, uvSize * vertices * face );
  44707. const fill = [ face, face, face, face, face, face ];
  44708. faceIndex.set( fill, faceIndexSize * vertices * face );
  44709. }
  44710. const planes = new BufferGeometry();
  44711. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44712. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44713. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44714. lodPlanes.push( planes );
  44715. if ( lod > LOD_MIN ) {
  44716. lod --;
  44717. }
  44718. }
  44719. return { lodPlanes, sizeLods, sigmas };
  44720. }
  44721. function _createRenderTarget( width, height, params ) {
  44722. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44723. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44724. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44725. cubeUVRenderTarget.scissorTest = true;
  44726. return cubeUVRenderTarget;
  44727. }
  44728. function _setViewport( target, x, y, width, height ) {
  44729. target.viewport.set( x, y, width, height );
  44730. target.scissor.set( x, y, width, height );
  44731. }
  44732. function _getBlurShader( lodMax, width, height ) {
  44733. const weights = new Float32Array( MAX_SAMPLES );
  44734. const poleAxis = new Vector3( 0, 1, 0 );
  44735. const shaderMaterial = new ShaderMaterial( {
  44736. name: 'SphericalGaussianBlur',
  44737. defines: {
  44738. 'n': MAX_SAMPLES,
  44739. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44740. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44741. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44742. },
  44743. uniforms: {
  44744. 'envMap': { value: null },
  44745. 'samples': { value: 1 },
  44746. 'weights': { value: weights },
  44747. 'latitudinal': { value: false },
  44748. 'dTheta': { value: 0 },
  44749. 'mipInt': { value: 0 },
  44750. 'poleAxis': { value: poleAxis }
  44751. },
  44752. vertexShader: _getCommonVertexShader(),
  44753. fragmentShader: /* glsl */`
  44754. precision mediump float;
  44755. precision mediump int;
  44756. varying vec3 vOutputDirection;
  44757. uniform sampler2D envMap;
  44758. uniform int samples;
  44759. uniform float weights[ n ];
  44760. uniform bool latitudinal;
  44761. uniform float dTheta;
  44762. uniform float mipInt;
  44763. uniform vec3 poleAxis;
  44764. #define ENVMAP_TYPE_CUBE_UV
  44765. #include <cube_uv_reflection_fragment>
  44766. vec3 getSample( float theta, vec3 axis ) {
  44767. float cosTheta = cos( theta );
  44768. // Rodrigues' axis-angle rotation
  44769. vec3 sampleDirection = vOutputDirection * cosTheta
  44770. + cross( axis, vOutputDirection ) * sin( theta )
  44771. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  44772. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  44773. }
  44774. void main() {
  44775. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  44776. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  44777. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  44778. }
  44779. axis = normalize( axis );
  44780. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  44781. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  44782. for ( int i = 1; i < n; i++ ) {
  44783. if ( i >= samples ) {
  44784. break;
  44785. }
  44786. float theta = dTheta * float( i );
  44787. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  44788. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  44789. }
  44790. }
  44791. `,
  44792. blending: NoBlending,
  44793. depthTest: false,
  44794. depthWrite: false
  44795. } );
  44796. return shaderMaterial;
  44797. }
  44798. function _getEquirectMaterial() {
  44799. return new ShaderMaterial( {
  44800. name: 'EquirectangularToCubeUV',
  44801. uniforms: {
  44802. 'envMap': { value: null }
  44803. },
  44804. vertexShader: _getCommonVertexShader(),
  44805. fragmentShader: /* glsl */`
  44806. precision mediump float;
  44807. precision mediump int;
  44808. varying vec3 vOutputDirection;
  44809. uniform sampler2D envMap;
  44810. #include <common>
  44811. void main() {
  44812. vec3 outputDirection = normalize( vOutputDirection );
  44813. vec2 uv = equirectUv( outputDirection );
  44814. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  44815. }
  44816. `,
  44817. blending: NoBlending,
  44818. depthTest: false,
  44819. depthWrite: false
  44820. } );
  44821. }
  44822. function _getCubemapMaterial() {
  44823. return new ShaderMaterial( {
  44824. name: 'CubemapToCubeUV',
  44825. uniforms: {
  44826. 'envMap': { value: null },
  44827. 'flipEnvMap': { value: -1 }
  44828. },
  44829. vertexShader: _getCommonVertexShader(),
  44830. fragmentShader: /* glsl */`
  44831. precision mediump float;
  44832. precision mediump int;
  44833. uniform float flipEnvMap;
  44834. varying vec3 vOutputDirection;
  44835. uniform samplerCube envMap;
  44836. void main() {
  44837. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  44838. }
  44839. `,
  44840. blending: NoBlending,
  44841. depthTest: false,
  44842. depthWrite: false
  44843. } );
  44844. }
  44845. function _getCommonVertexShader() {
  44846. return /* glsl */`
  44847. precision mediump float;
  44848. precision mediump int;
  44849. attribute float faceIndex;
  44850. varying vec3 vOutputDirection;
  44851. // RH coordinate system; PMREM face-indexing convention
  44852. vec3 getDirection( vec2 uv, float face ) {
  44853. uv = 2.0 * uv - 1.0;
  44854. vec3 direction = vec3( uv, 1.0 );
  44855. if ( face == 0.0 ) {
  44856. direction = direction.zyx; // ( 1, v, u ) pos x
  44857. } else if ( face == 1.0 ) {
  44858. direction = direction.xzy;
  44859. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  44860. } else if ( face == 2.0 ) {
  44861. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  44862. } else if ( face == 3.0 ) {
  44863. direction = direction.zyx;
  44864. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  44865. } else if ( face == 4.0 ) {
  44866. direction = direction.xzy;
  44867. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  44868. } else if ( face == 5.0 ) {
  44869. direction.z *= -1.0; // ( u, v, -1 ) neg z
  44870. }
  44871. return direction;
  44872. }
  44873. void main() {
  44874. vOutputDirection = getDirection( uv, faceIndex );
  44875. gl_Position = vec4( position, 1.0 );
  44876. }
  44877. `;
  44878. }
  44879. function WebGLCubeUVMaps( renderer ) {
  44880. let cubeUVmaps = new WeakMap();
  44881. let pmremGenerator = null;
  44882. function get( texture ) {
  44883. if ( texture && texture.isTexture ) {
  44884. const mapping = texture.mapping;
  44885. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  44886. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  44887. // equirect/cube map to cubeUV conversion
  44888. if ( isEquirectMap || isCubeMap ) {
  44889. let renderTarget = cubeUVmaps.get( texture );
  44890. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  44891. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  44892. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44893. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  44894. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44895. cubeUVmaps.set( texture, renderTarget );
  44896. return renderTarget.texture;
  44897. } else {
  44898. if ( renderTarget !== undefined ) {
  44899. return renderTarget.texture;
  44900. } else {
  44901. const image = texture.image;
  44902. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  44903. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  44904. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  44905. renderTarget.texture.pmremVersion = texture.pmremVersion;
  44906. cubeUVmaps.set( texture, renderTarget );
  44907. texture.addEventListener( 'dispose', onTextureDispose );
  44908. return renderTarget.texture;
  44909. } else {
  44910. // image not yet ready. try the conversion next frame
  44911. return null;
  44912. }
  44913. }
  44914. }
  44915. }
  44916. }
  44917. return texture;
  44918. }
  44919. function isCubeTextureComplete( image ) {
  44920. let count = 0;
  44921. const length = 6;
  44922. for ( let i = 0; i < length; i ++ ) {
  44923. if ( image[ i ] !== undefined ) count ++;
  44924. }
  44925. return count === length;
  44926. }
  44927. function onTextureDispose( event ) {
  44928. const texture = event.target;
  44929. texture.removeEventListener( 'dispose', onTextureDispose );
  44930. const cubemapUV = cubeUVmaps.get( texture );
  44931. if ( cubemapUV !== undefined ) {
  44932. cubeUVmaps.delete( texture );
  44933. cubemapUV.dispose();
  44934. }
  44935. }
  44936. function dispose() {
  44937. cubeUVmaps = new WeakMap();
  44938. if ( pmremGenerator !== null ) {
  44939. pmremGenerator.dispose();
  44940. pmremGenerator = null;
  44941. }
  44942. }
  44943. return {
  44944. get: get,
  44945. dispose: dispose
  44946. };
  44947. }
  44948. function WebGLExtensions( gl ) {
  44949. const extensions = {};
  44950. function getExtension( name ) {
  44951. if ( extensions[ name ] !== undefined ) {
  44952. return extensions[ name ];
  44953. }
  44954. let extension;
  44955. switch ( name ) {
  44956. case 'WEBGL_depth_texture':
  44957. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  44958. break;
  44959. case 'EXT_texture_filter_anisotropic':
  44960. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  44961. break;
  44962. case 'WEBGL_compressed_texture_s3tc':
  44963. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  44964. break;
  44965. case 'WEBGL_compressed_texture_pvrtc':
  44966. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  44967. break;
  44968. default:
  44969. extension = gl.getExtension( name );
  44970. }
  44971. extensions[ name ] = extension;
  44972. return extension;
  44973. }
  44974. return {
  44975. has: function ( name ) {
  44976. return getExtension( name ) !== null;
  44977. },
  44978. init: function () {
  44979. getExtension( 'EXT_color_buffer_float' );
  44980. getExtension( 'WEBGL_clip_cull_distance' );
  44981. getExtension( 'OES_texture_float_linear' );
  44982. getExtension( 'EXT_color_buffer_half_float' );
  44983. getExtension( 'WEBGL_multisampled_render_to_texture' );
  44984. getExtension( 'WEBGL_render_shared_exponent' );
  44985. },
  44986. get: function ( name ) {
  44987. const extension = getExtension( name );
  44988. if ( extension === null ) {
  44989. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  44990. }
  44991. return extension;
  44992. }
  44993. };
  44994. }
  44995. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  44996. const geometries = {};
  44997. const wireframeAttributes = new WeakMap();
  44998. function onGeometryDispose( event ) {
  44999. const geometry = event.target;
  45000. if ( geometry.index !== null ) {
  45001. attributes.remove( geometry.index );
  45002. }
  45003. for ( const name in geometry.attributes ) {
  45004. attributes.remove( geometry.attributes[ name ] );
  45005. }
  45006. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45007. delete geometries[ geometry.id ];
  45008. const attribute = wireframeAttributes.get( geometry );
  45009. if ( attribute ) {
  45010. attributes.remove( attribute );
  45011. wireframeAttributes.delete( geometry );
  45012. }
  45013. bindingStates.releaseStatesOfGeometry( geometry );
  45014. if ( geometry.isInstancedBufferGeometry === true ) {
  45015. delete geometry._maxInstanceCount;
  45016. }
  45017. //
  45018. info.memory.geometries --;
  45019. }
  45020. function get( object, geometry ) {
  45021. if ( geometries[ geometry.id ] === true ) return geometry;
  45022. geometry.addEventListener( 'dispose', onGeometryDispose );
  45023. geometries[ geometry.id ] = true;
  45024. info.memory.geometries ++;
  45025. return geometry;
  45026. }
  45027. function update( geometry ) {
  45028. const geometryAttributes = geometry.attributes;
  45029. // Updating index buffer in VAO now. See WebGLBindingStates.
  45030. for ( const name in geometryAttributes ) {
  45031. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45032. }
  45033. }
  45034. function updateWireframeAttribute( geometry ) {
  45035. const indices = [];
  45036. const geometryIndex = geometry.index;
  45037. const geometryPosition = geometry.attributes.position;
  45038. let version = 0;
  45039. if ( geometryIndex !== null ) {
  45040. const array = geometryIndex.array;
  45041. version = geometryIndex.version;
  45042. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45043. const a = array[ i + 0 ];
  45044. const b = array[ i + 1 ];
  45045. const c = array[ i + 2 ];
  45046. indices.push( a, b, b, c, c, a );
  45047. }
  45048. } else if ( geometryPosition !== undefined ) {
  45049. const array = geometryPosition.array;
  45050. version = geometryPosition.version;
  45051. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45052. const a = i + 0;
  45053. const b = i + 1;
  45054. const c = i + 2;
  45055. indices.push( a, b, b, c, c, a );
  45056. }
  45057. } else {
  45058. return;
  45059. }
  45060. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45061. attribute.version = version;
  45062. // Updating index buffer in VAO now. See WebGLBindingStates
  45063. //
  45064. const previousAttribute = wireframeAttributes.get( geometry );
  45065. if ( previousAttribute ) attributes.remove( previousAttribute );
  45066. //
  45067. wireframeAttributes.set( geometry, attribute );
  45068. }
  45069. function getWireframeAttribute( geometry ) {
  45070. const currentAttribute = wireframeAttributes.get( geometry );
  45071. if ( currentAttribute ) {
  45072. const geometryIndex = geometry.index;
  45073. if ( geometryIndex !== null ) {
  45074. // if the attribute is obsolete, create a new one
  45075. if ( currentAttribute.version < geometryIndex.version ) {
  45076. updateWireframeAttribute( geometry );
  45077. }
  45078. }
  45079. } else {
  45080. updateWireframeAttribute( geometry );
  45081. }
  45082. return wireframeAttributes.get( geometry );
  45083. }
  45084. return {
  45085. get: get,
  45086. update: update,
  45087. getWireframeAttribute: getWireframeAttribute
  45088. };
  45089. }
  45090. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45091. let mode;
  45092. function setMode( value ) {
  45093. mode = value;
  45094. }
  45095. let type, bytesPerElement;
  45096. function setIndex( value ) {
  45097. type = value.type;
  45098. bytesPerElement = value.bytesPerElement;
  45099. }
  45100. function render( start, count ) {
  45101. gl.drawElements( mode, count, type, start * bytesPerElement );
  45102. info.update( count, mode, 1 );
  45103. }
  45104. function renderInstances( start, count, primcount ) {
  45105. if ( primcount === 0 ) return;
  45106. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45107. info.update( count, mode, primcount );
  45108. }
  45109. function renderMultiDraw( starts, counts, drawCount ) {
  45110. if ( drawCount === 0 ) return;
  45111. const extension = extensions.get( 'WEBGL_multi_draw' );
  45112. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45113. let elementCount = 0;
  45114. for ( let i = 0; i < drawCount; i ++ ) {
  45115. elementCount += counts[ i ];
  45116. }
  45117. info.update( elementCount, mode, 1 );
  45118. }
  45119. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45120. if ( drawCount === 0 ) return;
  45121. const extension = extensions.get( 'WEBGL_multi_draw' );
  45122. if ( extension === null ) {
  45123. for ( let i = 0; i < starts.length; i ++ ) {
  45124. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45125. }
  45126. } else {
  45127. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45128. let elementCount = 0;
  45129. for ( let i = 0; i < drawCount; i ++ ) {
  45130. elementCount += counts[ i ] * primcount[ i ];
  45131. }
  45132. info.update( elementCount, mode, 1 );
  45133. }
  45134. }
  45135. //
  45136. this.setMode = setMode;
  45137. this.setIndex = setIndex;
  45138. this.render = render;
  45139. this.renderInstances = renderInstances;
  45140. this.renderMultiDraw = renderMultiDraw;
  45141. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45142. }
  45143. function WebGLInfo( gl ) {
  45144. const memory = {
  45145. geometries: 0,
  45146. textures: 0
  45147. };
  45148. const render = {
  45149. frame: 0,
  45150. calls: 0,
  45151. triangles: 0,
  45152. points: 0,
  45153. lines: 0
  45154. };
  45155. function update( count, mode, instanceCount ) {
  45156. render.calls ++;
  45157. switch ( mode ) {
  45158. case gl.TRIANGLES:
  45159. render.triangles += instanceCount * ( count / 3 );
  45160. break;
  45161. case gl.LINES:
  45162. render.lines += instanceCount * ( count / 2 );
  45163. break;
  45164. case gl.LINE_STRIP:
  45165. render.lines += instanceCount * ( count - 1 );
  45166. break;
  45167. case gl.LINE_LOOP:
  45168. render.lines += instanceCount * count;
  45169. break;
  45170. case gl.POINTS:
  45171. render.points += instanceCount * count;
  45172. break;
  45173. default:
  45174. error( 'WebGLInfo: Unknown draw mode:', mode );
  45175. break;
  45176. }
  45177. }
  45178. function reset() {
  45179. render.calls = 0;
  45180. render.triangles = 0;
  45181. render.points = 0;
  45182. render.lines = 0;
  45183. }
  45184. return {
  45185. memory: memory,
  45186. render: render,
  45187. programs: null,
  45188. autoReset: true,
  45189. reset: reset,
  45190. update: update
  45191. };
  45192. }
  45193. function WebGLMorphtargets( gl, capabilities, textures ) {
  45194. const morphTextures = new WeakMap();
  45195. const morph = new Vector4();
  45196. function update( object, geometry, program ) {
  45197. const objectInfluences = object.morphTargetInfluences;
  45198. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45199. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45200. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45201. let entry = morphTextures.get( geometry );
  45202. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45203. if ( entry !== undefined ) entry.texture.dispose();
  45204. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45205. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45206. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45207. const morphTargets = geometry.morphAttributes.position || [];
  45208. const morphNormals = geometry.morphAttributes.normal || [];
  45209. const morphColors = geometry.morphAttributes.color || [];
  45210. let vertexDataCount = 0;
  45211. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45212. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45213. if ( hasMorphColors === true ) vertexDataCount = 3;
  45214. let width = geometry.attributes.position.count * vertexDataCount;
  45215. let height = 1;
  45216. if ( width > capabilities.maxTextureSize ) {
  45217. height = Math.ceil( width / capabilities.maxTextureSize );
  45218. width = capabilities.maxTextureSize;
  45219. }
  45220. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45221. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45222. texture.type = FloatType;
  45223. texture.needsUpdate = true;
  45224. // fill buffer
  45225. const vertexDataStride = vertexDataCount * 4;
  45226. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45227. const morphTarget = morphTargets[ i ];
  45228. const morphNormal = morphNormals[ i ];
  45229. const morphColor = morphColors[ i ];
  45230. const offset = width * height * 4 * i;
  45231. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45232. const stride = j * vertexDataStride;
  45233. if ( hasMorphPosition === true ) {
  45234. morph.fromBufferAttribute( morphTarget, j );
  45235. buffer[ offset + stride + 0 ] = morph.x;
  45236. buffer[ offset + stride + 1 ] = morph.y;
  45237. buffer[ offset + stride + 2 ] = morph.z;
  45238. buffer[ offset + stride + 3 ] = 0;
  45239. }
  45240. if ( hasMorphNormals === true ) {
  45241. morph.fromBufferAttribute( morphNormal, j );
  45242. buffer[ offset + stride + 4 ] = morph.x;
  45243. buffer[ offset + stride + 5 ] = morph.y;
  45244. buffer[ offset + stride + 6 ] = morph.z;
  45245. buffer[ offset + stride + 7 ] = 0;
  45246. }
  45247. if ( hasMorphColors === true ) {
  45248. morph.fromBufferAttribute( morphColor, j );
  45249. buffer[ offset + stride + 8 ] = morph.x;
  45250. buffer[ offset + stride + 9 ] = morph.y;
  45251. buffer[ offset + stride + 10 ] = morph.z;
  45252. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45253. }
  45254. }
  45255. }
  45256. entry = {
  45257. count: morphTargetsCount,
  45258. texture: texture,
  45259. size: new Vector2( width, height )
  45260. };
  45261. morphTextures.set( geometry, entry );
  45262. function disposeTexture() {
  45263. texture.dispose();
  45264. morphTextures.delete( geometry );
  45265. geometry.removeEventListener( 'dispose', disposeTexture );
  45266. }
  45267. geometry.addEventListener( 'dispose', disposeTexture );
  45268. }
  45269. //
  45270. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45271. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45272. } else {
  45273. let morphInfluencesSum = 0;
  45274. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45275. morphInfluencesSum += objectInfluences[ i ];
  45276. }
  45277. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45278. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45279. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45280. }
  45281. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45282. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45283. }
  45284. return {
  45285. update: update
  45286. };
  45287. }
  45288. function WebGLObjects( gl, geometries, attributes, info ) {
  45289. let updateMap = new WeakMap();
  45290. function update( object ) {
  45291. const frame = info.render.frame;
  45292. const geometry = object.geometry;
  45293. const buffergeometry = geometries.get( object, geometry );
  45294. // Update once per frame
  45295. if ( updateMap.get( buffergeometry ) !== frame ) {
  45296. geometries.update( buffergeometry );
  45297. updateMap.set( buffergeometry, frame );
  45298. }
  45299. if ( object.isInstancedMesh ) {
  45300. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45301. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45302. }
  45303. if ( updateMap.get( object ) !== frame ) {
  45304. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45305. if ( object.instanceColor !== null ) {
  45306. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45307. }
  45308. updateMap.set( object, frame );
  45309. }
  45310. }
  45311. if ( object.isSkinnedMesh ) {
  45312. const skeleton = object.skeleton;
  45313. if ( updateMap.get( skeleton ) !== frame ) {
  45314. skeleton.update();
  45315. updateMap.set( skeleton, frame );
  45316. }
  45317. }
  45318. return buffergeometry;
  45319. }
  45320. function dispose() {
  45321. updateMap = new WeakMap();
  45322. }
  45323. function onInstancedMeshDispose( event ) {
  45324. const instancedMesh = event.target;
  45325. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45326. attributes.remove( instancedMesh.instanceMatrix );
  45327. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45328. }
  45329. return {
  45330. update: update,
  45331. dispose: dispose
  45332. };
  45333. }
  45334. /**
  45335. * Uniforms of a program.
  45336. * Those form a tree structure with a special top-level container for the root,
  45337. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45338. *
  45339. *
  45340. * Properties of inner nodes including the top-level container:
  45341. *
  45342. * .seq - array of nested uniforms
  45343. * .map - nested uniforms by name
  45344. *
  45345. *
  45346. * Methods of all nodes except the top-level container:
  45347. *
  45348. * .setValue( gl, value, [textures] )
  45349. *
  45350. * uploads a uniform value(s)
  45351. * the 'textures' parameter is needed for sampler uniforms
  45352. *
  45353. *
  45354. * Static methods of the top-level container (textures factorizations):
  45355. *
  45356. * .upload( gl, seq, values, textures )
  45357. *
  45358. * sets uniforms in 'seq' to 'values[id].value'
  45359. *
  45360. * .seqWithValue( seq, values ) : filteredSeq
  45361. *
  45362. * filters 'seq' entries with corresponding entry in values
  45363. *
  45364. *
  45365. * Methods of the top-level container (textures factorizations):
  45366. *
  45367. * .setValue( gl, name, value, textures )
  45368. *
  45369. * sets uniform with name 'name' to 'value'
  45370. *
  45371. * .setOptional( gl, obj, prop )
  45372. *
  45373. * like .set for an optional property of the object
  45374. *
  45375. */
  45376. const emptyTexture = /*@__PURE__*/ new Texture();
  45377. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45378. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45379. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45380. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45381. // --- Utilities ---
  45382. // Array Caches (provide typed arrays for temporary by size)
  45383. const arrayCacheF32 = [];
  45384. const arrayCacheI32 = [];
  45385. // Float32Array caches used for uploading Matrix uniforms
  45386. const mat4array = new Float32Array( 16 );
  45387. const mat3array = new Float32Array( 9 );
  45388. const mat2array = new Float32Array( 4 );
  45389. // Flattening for arrays of vectors and matrices
  45390. function flatten( array, nBlocks, blockSize ) {
  45391. const firstElem = array[ 0 ];
  45392. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45393. // unoptimized: ! isNaN( firstElem )
  45394. // see http://jacksondunstan.com/articles/983
  45395. const n = nBlocks * blockSize;
  45396. let r = arrayCacheF32[ n ];
  45397. if ( r === undefined ) {
  45398. r = new Float32Array( n );
  45399. arrayCacheF32[ n ] = r;
  45400. }
  45401. if ( nBlocks !== 0 ) {
  45402. firstElem.toArray( r, 0 );
  45403. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45404. offset += blockSize;
  45405. array[ i ].toArray( r, offset );
  45406. }
  45407. }
  45408. return r;
  45409. }
  45410. function arraysEqual( a, b ) {
  45411. if ( a.length !== b.length ) return false;
  45412. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45413. if ( a[ i ] !== b[ i ] ) return false;
  45414. }
  45415. return true;
  45416. }
  45417. function copyArray( a, b ) {
  45418. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45419. a[ i ] = b[ i ];
  45420. }
  45421. }
  45422. // Texture unit allocation
  45423. function allocTexUnits( textures, n ) {
  45424. let r = arrayCacheI32[ n ];
  45425. if ( r === undefined ) {
  45426. r = new Int32Array( n );
  45427. arrayCacheI32[ n ] = r;
  45428. }
  45429. for ( let i = 0; i !== n; ++ i ) {
  45430. r[ i ] = textures.allocateTextureUnit();
  45431. }
  45432. return r;
  45433. }
  45434. // --- Setters ---
  45435. // Note: Defining these methods externally, because they come in a bunch
  45436. // and this way their names minify.
  45437. // Single scalar
  45438. function setValueV1f( gl, v ) {
  45439. const cache = this.cache;
  45440. if ( cache[ 0 ] === v ) return;
  45441. gl.uniform1f( this.addr, v );
  45442. cache[ 0 ] = v;
  45443. }
  45444. // Single float vector (from flat array or THREE.VectorN)
  45445. function setValueV2f( gl, v ) {
  45446. const cache = this.cache;
  45447. if ( v.x !== undefined ) {
  45448. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45449. gl.uniform2f( this.addr, v.x, v.y );
  45450. cache[ 0 ] = v.x;
  45451. cache[ 1 ] = v.y;
  45452. }
  45453. } else {
  45454. if ( arraysEqual( cache, v ) ) return;
  45455. gl.uniform2fv( this.addr, v );
  45456. copyArray( cache, v );
  45457. }
  45458. }
  45459. function setValueV3f( gl, v ) {
  45460. const cache = this.cache;
  45461. if ( v.x !== undefined ) {
  45462. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45463. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45464. cache[ 0 ] = v.x;
  45465. cache[ 1 ] = v.y;
  45466. cache[ 2 ] = v.z;
  45467. }
  45468. } else if ( v.r !== undefined ) {
  45469. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45470. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45471. cache[ 0 ] = v.r;
  45472. cache[ 1 ] = v.g;
  45473. cache[ 2 ] = v.b;
  45474. }
  45475. } else {
  45476. if ( arraysEqual( cache, v ) ) return;
  45477. gl.uniform3fv( this.addr, v );
  45478. copyArray( cache, v );
  45479. }
  45480. }
  45481. function setValueV4f( gl, v ) {
  45482. const cache = this.cache;
  45483. if ( v.x !== undefined ) {
  45484. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45485. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45486. cache[ 0 ] = v.x;
  45487. cache[ 1 ] = v.y;
  45488. cache[ 2 ] = v.z;
  45489. cache[ 3 ] = v.w;
  45490. }
  45491. } else {
  45492. if ( arraysEqual( cache, v ) ) return;
  45493. gl.uniform4fv( this.addr, v );
  45494. copyArray( cache, v );
  45495. }
  45496. }
  45497. // Single matrix (from flat array or THREE.MatrixN)
  45498. function setValueM2( gl, v ) {
  45499. const cache = this.cache;
  45500. const elements = v.elements;
  45501. if ( elements === undefined ) {
  45502. if ( arraysEqual( cache, v ) ) return;
  45503. gl.uniformMatrix2fv( this.addr, false, v );
  45504. copyArray( cache, v );
  45505. } else {
  45506. if ( arraysEqual( cache, elements ) ) return;
  45507. mat2array.set( elements );
  45508. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45509. copyArray( cache, elements );
  45510. }
  45511. }
  45512. function setValueM3( gl, v ) {
  45513. const cache = this.cache;
  45514. const elements = v.elements;
  45515. if ( elements === undefined ) {
  45516. if ( arraysEqual( cache, v ) ) return;
  45517. gl.uniformMatrix3fv( this.addr, false, v );
  45518. copyArray( cache, v );
  45519. } else {
  45520. if ( arraysEqual( cache, elements ) ) return;
  45521. mat3array.set( elements );
  45522. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45523. copyArray( cache, elements );
  45524. }
  45525. }
  45526. function setValueM4( gl, v ) {
  45527. const cache = this.cache;
  45528. const elements = v.elements;
  45529. if ( elements === undefined ) {
  45530. if ( arraysEqual( cache, v ) ) return;
  45531. gl.uniformMatrix4fv( this.addr, false, v );
  45532. copyArray( cache, v );
  45533. } else {
  45534. if ( arraysEqual( cache, elements ) ) return;
  45535. mat4array.set( elements );
  45536. gl.uniformMatrix4fv( this.addr, false, mat4array );
  45537. copyArray( cache, elements );
  45538. }
  45539. }
  45540. // Single integer / boolean
  45541. function setValueV1i( gl, v ) {
  45542. const cache = this.cache;
  45543. if ( cache[ 0 ] === v ) return;
  45544. gl.uniform1i( this.addr, v );
  45545. cache[ 0 ] = v;
  45546. }
  45547. // Single integer / boolean vector (from flat array or THREE.VectorN)
  45548. function setValueV2i( gl, v ) {
  45549. const cache = this.cache;
  45550. if ( v.x !== undefined ) {
  45551. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45552. gl.uniform2i( this.addr, v.x, v.y );
  45553. cache[ 0 ] = v.x;
  45554. cache[ 1 ] = v.y;
  45555. }
  45556. } else {
  45557. if ( arraysEqual( cache, v ) ) return;
  45558. gl.uniform2iv( this.addr, v );
  45559. copyArray( cache, v );
  45560. }
  45561. }
  45562. function setValueV3i( gl, v ) {
  45563. const cache = this.cache;
  45564. if ( v.x !== undefined ) {
  45565. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45566. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45567. cache[ 0 ] = v.x;
  45568. cache[ 1 ] = v.y;
  45569. cache[ 2 ] = v.z;
  45570. }
  45571. } else {
  45572. if ( arraysEqual( cache, v ) ) return;
  45573. gl.uniform3iv( this.addr, v );
  45574. copyArray( cache, v );
  45575. }
  45576. }
  45577. function setValueV4i( gl, v ) {
  45578. const cache = this.cache;
  45579. if ( v.x !== undefined ) {
  45580. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45581. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45582. cache[ 0 ] = v.x;
  45583. cache[ 1 ] = v.y;
  45584. cache[ 2 ] = v.z;
  45585. cache[ 3 ] = v.w;
  45586. }
  45587. } else {
  45588. if ( arraysEqual( cache, v ) ) return;
  45589. gl.uniform4iv( this.addr, v );
  45590. copyArray( cache, v );
  45591. }
  45592. }
  45593. // Single unsigned integer
  45594. function setValueV1ui( gl, v ) {
  45595. const cache = this.cache;
  45596. if ( cache[ 0 ] === v ) return;
  45597. gl.uniform1ui( this.addr, v );
  45598. cache[ 0 ] = v;
  45599. }
  45600. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45601. function setValueV2ui( gl, v ) {
  45602. const cache = this.cache;
  45603. if ( v.x !== undefined ) {
  45604. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45605. gl.uniform2ui( this.addr, v.x, v.y );
  45606. cache[ 0 ] = v.x;
  45607. cache[ 1 ] = v.y;
  45608. }
  45609. } else {
  45610. if ( arraysEqual( cache, v ) ) return;
  45611. gl.uniform2uiv( this.addr, v );
  45612. copyArray( cache, v );
  45613. }
  45614. }
  45615. function setValueV3ui( gl, v ) {
  45616. const cache = this.cache;
  45617. if ( v.x !== undefined ) {
  45618. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45619. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  45620. cache[ 0 ] = v.x;
  45621. cache[ 1 ] = v.y;
  45622. cache[ 2 ] = v.z;
  45623. }
  45624. } else {
  45625. if ( arraysEqual( cache, v ) ) return;
  45626. gl.uniform3uiv( this.addr, v );
  45627. copyArray( cache, v );
  45628. }
  45629. }
  45630. function setValueV4ui( gl, v ) {
  45631. const cache = this.cache;
  45632. if ( v.x !== undefined ) {
  45633. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45634. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45635. cache[ 0 ] = v.x;
  45636. cache[ 1 ] = v.y;
  45637. cache[ 2 ] = v.z;
  45638. cache[ 3 ] = v.w;
  45639. }
  45640. } else {
  45641. if ( arraysEqual( cache, v ) ) return;
  45642. gl.uniform4uiv( this.addr, v );
  45643. copyArray( cache, v );
  45644. }
  45645. }
  45646. // Single texture (2D / Cube)
  45647. function setValueT1( gl, v, textures ) {
  45648. const cache = this.cache;
  45649. const unit = textures.allocateTextureUnit();
  45650. if ( cache[ 0 ] !== unit ) {
  45651. gl.uniform1i( this.addr, unit );
  45652. cache[ 0 ] = unit;
  45653. }
  45654. let emptyTexture2D;
  45655. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45656. emptyShadowTexture.compareFunction = LessEqualCompare; // #28670
  45657. emptyTexture2D = emptyShadowTexture;
  45658. } else {
  45659. emptyTexture2D = emptyTexture;
  45660. }
  45661. textures.setTexture2D( v || emptyTexture2D, unit );
  45662. }
  45663. function setValueT3D1( gl, v, textures ) {
  45664. const cache = this.cache;
  45665. const unit = textures.allocateTextureUnit();
  45666. if ( cache[ 0 ] !== unit ) {
  45667. gl.uniform1i( this.addr, unit );
  45668. cache[ 0 ] = unit;
  45669. }
  45670. textures.setTexture3D( v || empty3dTexture, unit );
  45671. }
  45672. function setValueT6( gl, v, textures ) {
  45673. const cache = this.cache;
  45674. const unit = textures.allocateTextureUnit();
  45675. if ( cache[ 0 ] !== unit ) {
  45676. gl.uniform1i( this.addr, unit );
  45677. cache[ 0 ] = unit;
  45678. }
  45679. textures.setTextureCube( v || emptyCubeTexture, unit );
  45680. }
  45681. function setValueT2DArray1( gl, v, textures ) {
  45682. const cache = this.cache;
  45683. const unit = textures.allocateTextureUnit();
  45684. if ( cache[ 0 ] !== unit ) {
  45685. gl.uniform1i( this.addr, unit );
  45686. cache[ 0 ] = unit;
  45687. }
  45688. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  45689. }
  45690. // Helper to pick the right setter for the singular case
  45691. function getSingularSetter( type ) {
  45692. switch ( type ) {
  45693. case 0x1406: return setValueV1f; // FLOAT
  45694. case 0x8b50: return setValueV2f; // _VEC2
  45695. case 0x8b51: return setValueV3f; // _VEC3
  45696. case 0x8b52: return setValueV4f; // _VEC4
  45697. case 0x8b5a: return setValueM2; // _MAT2
  45698. case 0x8b5b: return setValueM3; // _MAT3
  45699. case 0x8b5c: return setValueM4; // _MAT4
  45700. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  45701. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  45702. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  45703. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  45704. case 0x1405: return setValueV1ui; // UINT
  45705. case 0x8dc6: return setValueV2ui; // _VEC2
  45706. case 0x8dc7: return setValueV3ui; // _VEC3
  45707. case 0x8dc8: return setValueV4ui; // _VEC4
  45708. case 0x8b5e: // SAMPLER_2D
  45709. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45710. case 0x8dca: // INT_SAMPLER_2D
  45711. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45712. case 0x8b62: // SAMPLER_2D_SHADOW
  45713. return setValueT1;
  45714. case 0x8b5f: // SAMPLER_3D
  45715. case 0x8dcb: // INT_SAMPLER_3D
  45716. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45717. return setValueT3D1;
  45718. case 0x8b60: // SAMPLER_CUBE
  45719. case 0x8dcc: // INT_SAMPLER_CUBE
  45720. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45721. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45722. return setValueT6;
  45723. case 0x8dc1: // SAMPLER_2D_ARRAY
  45724. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45725. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45726. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45727. return setValueT2DArray1;
  45728. }
  45729. }
  45730. // Array of scalars
  45731. function setValueV1fArray( gl, v ) {
  45732. gl.uniform1fv( this.addr, v );
  45733. }
  45734. // Array of vectors (from flat array or array of THREE.VectorN)
  45735. function setValueV2fArray( gl, v ) {
  45736. const data = flatten( v, this.size, 2 );
  45737. gl.uniform2fv( this.addr, data );
  45738. }
  45739. function setValueV3fArray( gl, v ) {
  45740. const data = flatten( v, this.size, 3 );
  45741. gl.uniform3fv( this.addr, data );
  45742. }
  45743. function setValueV4fArray( gl, v ) {
  45744. const data = flatten( v, this.size, 4 );
  45745. gl.uniform4fv( this.addr, data );
  45746. }
  45747. // Array of matrices (from flat array or array of THREE.MatrixN)
  45748. function setValueM2Array( gl, v ) {
  45749. const data = flatten( v, this.size, 4 );
  45750. gl.uniformMatrix2fv( this.addr, false, data );
  45751. }
  45752. function setValueM3Array( gl, v ) {
  45753. const data = flatten( v, this.size, 9 );
  45754. gl.uniformMatrix3fv( this.addr, false, data );
  45755. }
  45756. function setValueM4Array( gl, v ) {
  45757. const data = flatten( v, this.size, 16 );
  45758. gl.uniformMatrix4fv( this.addr, false, data );
  45759. }
  45760. // Array of integer / boolean
  45761. function setValueV1iArray( gl, v ) {
  45762. gl.uniform1iv( this.addr, v );
  45763. }
  45764. // Array of integer / boolean vectors (from flat array)
  45765. function setValueV2iArray( gl, v ) {
  45766. gl.uniform2iv( this.addr, v );
  45767. }
  45768. function setValueV3iArray( gl, v ) {
  45769. gl.uniform3iv( this.addr, v );
  45770. }
  45771. function setValueV4iArray( gl, v ) {
  45772. gl.uniform4iv( this.addr, v );
  45773. }
  45774. // Array of unsigned integer
  45775. function setValueV1uiArray( gl, v ) {
  45776. gl.uniform1uiv( this.addr, v );
  45777. }
  45778. // Array of unsigned integer vectors (from flat array)
  45779. function setValueV2uiArray( gl, v ) {
  45780. gl.uniform2uiv( this.addr, v );
  45781. }
  45782. function setValueV3uiArray( gl, v ) {
  45783. gl.uniform3uiv( this.addr, v );
  45784. }
  45785. function setValueV4uiArray( gl, v ) {
  45786. gl.uniform4uiv( this.addr, v );
  45787. }
  45788. // Array of textures (2D / 3D / Cube / 2DArray)
  45789. function setValueT1Array( gl, v, textures ) {
  45790. const cache = this.cache;
  45791. const n = v.length;
  45792. const units = allocTexUnits( textures, n );
  45793. if ( ! arraysEqual( cache, units ) ) {
  45794. gl.uniform1iv( this.addr, units );
  45795. copyArray( cache, units );
  45796. }
  45797. for ( let i = 0; i !== n; ++ i ) {
  45798. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  45799. }
  45800. }
  45801. function setValueT3DArray( gl, v, textures ) {
  45802. const cache = this.cache;
  45803. const n = v.length;
  45804. const units = allocTexUnits( textures, n );
  45805. if ( ! arraysEqual( cache, units ) ) {
  45806. gl.uniform1iv( this.addr, units );
  45807. copyArray( cache, units );
  45808. }
  45809. for ( let i = 0; i !== n; ++ i ) {
  45810. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  45811. }
  45812. }
  45813. function setValueT6Array( gl, v, textures ) {
  45814. const cache = this.cache;
  45815. const n = v.length;
  45816. const units = allocTexUnits( textures, n );
  45817. if ( ! arraysEqual( cache, units ) ) {
  45818. gl.uniform1iv( this.addr, units );
  45819. copyArray( cache, units );
  45820. }
  45821. for ( let i = 0; i !== n; ++ i ) {
  45822. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  45823. }
  45824. }
  45825. function setValueT2DArrayArray( gl, v, textures ) {
  45826. const cache = this.cache;
  45827. const n = v.length;
  45828. const units = allocTexUnits( textures, n );
  45829. if ( ! arraysEqual( cache, units ) ) {
  45830. gl.uniform1iv( this.addr, units );
  45831. copyArray( cache, units );
  45832. }
  45833. for ( let i = 0; i !== n; ++ i ) {
  45834. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  45835. }
  45836. }
  45837. // Helper to pick the right setter for a pure (bottom-level) array
  45838. function getPureArraySetter( type ) {
  45839. switch ( type ) {
  45840. case 0x1406: return setValueV1fArray; // FLOAT
  45841. case 0x8b50: return setValueV2fArray; // _VEC2
  45842. case 0x8b51: return setValueV3fArray; // _VEC3
  45843. case 0x8b52: return setValueV4fArray; // _VEC4
  45844. case 0x8b5a: return setValueM2Array; // _MAT2
  45845. case 0x8b5b: return setValueM3Array; // _MAT3
  45846. case 0x8b5c: return setValueM4Array; // _MAT4
  45847. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  45848. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  45849. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  45850. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  45851. case 0x1405: return setValueV1uiArray; // UINT
  45852. case 0x8dc6: return setValueV2uiArray; // _VEC2
  45853. case 0x8dc7: return setValueV3uiArray; // _VEC3
  45854. case 0x8dc8: return setValueV4uiArray; // _VEC4
  45855. case 0x8b5e: // SAMPLER_2D
  45856. case 0x8d66: // SAMPLER_EXTERNAL_OES
  45857. case 0x8dca: // INT_SAMPLER_2D
  45858. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  45859. case 0x8b62: // SAMPLER_2D_SHADOW
  45860. return setValueT1Array;
  45861. case 0x8b5f: // SAMPLER_3D
  45862. case 0x8dcb: // INT_SAMPLER_3D
  45863. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  45864. return setValueT3DArray;
  45865. case 0x8b60: // SAMPLER_CUBE
  45866. case 0x8dcc: // INT_SAMPLER_CUBE
  45867. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  45868. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  45869. return setValueT6Array;
  45870. case 0x8dc1: // SAMPLER_2D_ARRAY
  45871. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  45872. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  45873. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  45874. return setValueT2DArrayArray;
  45875. }
  45876. }
  45877. // --- Uniform Classes ---
  45878. class SingleUniform {
  45879. constructor( id, activeInfo, addr ) {
  45880. this.id = id;
  45881. this.addr = addr;
  45882. this.cache = [];
  45883. this.type = activeInfo.type;
  45884. this.setValue = getSingularSetter( activeInfo.type );
  45885. // this.path = activeInfo.name; // DEBUG
  45886. }
  45887. }
  45888. class PureArrayUniform {
  45889. constructor( id, activeInfo, addr ) {
  45890. this.id = id;
  45891. this.addr = addr;
  45892. this.cache = [];
  45893. this.type = activeInfo.type;
  45894. this.size = activeInfo.size;
  45895. this.setValue = getPureArraySetter( activeInfo.type );
  45896. // this.path = activeInfo.name; // DEBUG
  45897. }
  45898. }
  45899. class StructuredUniform {
  45900. constructor( id ) {
  45901. this.id = id;
  45902. this.seq = [];
  45903. this.map = {};
  45904. }
  45905. setValue( gl, value, textures ) {
  45906. const seq = this.seq;
  45907. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45908. const u = seq[ i ];
  45909. u.setValue( gl, value[ u.id ], textures );
  45910. }
  45911. }
  45912. }
  45913. // --- Top-level ---
  45914. // Parser - builds up the property tree from the path strings
  45915. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  45916. // extracts
  45917. // - the identifier (member name or array index)
  45918. // - followed by an optional right bracket (found when array index)
  45919. // - followed by an optional left bracket or dot (type of subscript)
  45920. //
  45921. // Note: These portions can be read in a non-overlapping fashion and
  45922. // allow straightforward parsing of the hierarchy that WebGL encodes
  45923. // in the uniform names.
  45924. function addUniform( container, uniformObject ) {
  45925. container.seq.push( uniformObject );
  45926. container.map[ uniformObject.id ] = uniformObject;
  45927. }
  45928. function parseUniform( activeInfo, addr, container ) {
  45929. const path = activeInfo.name,
  45930. pathLength = path.length;
  45931. // reset RegExp object, because of the early exit of a previous run
  45932. RePathPart.lastIndex = 0;
  45933. while ( true ) {
  45934. const match = RePathPart.exec( path ),
  45935. matchEnd = RePathPart.lastIndex;
  45936. let id = match[ 1 ];
  45937. const idIsIndex = match[ 2 ] === ']',
  45938. subscript = match[ 3 ];
  45939. if ( idIsIndex ) id = id | 0; // convert to integer
  45940. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  45941. // bare name or "pure" bottom-level array "[0]" suffix
  45942. addUniform( container, subscript === undefined ?
  45943. new SingleUniform( id, activeInfo, addr ) :
  45944. new PureArrayUniform( id, activeInfo, addr ) );
  45945. break;
  45946. } else {
  45947. // step into inner node / create it in case it doesn't exist
  45948. const map = container.map;
  45949. let next = map[ id ];
  45950. if ( next === undefined ) {
  45951. next = new StructuredUniform( id );
  45952. addUniform( container, next );
  45953. }
  45954. container = next;
  45955. }
  45956. }
  45957. }
  45958. // Root Container
  45959. class WebGLUniforms {
  45960. constructor( gl, program ) {
  45961. this.seq = [];
  45962. this.map = {};
  45963. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  45964. for ( let i = 0; i < n; ++ i ) {
  45965. const info = gl.getActiveUniform( program, i ),
  45966. addr = gl.getUniformLocation( program, info.name );
  45967. parseUniform( info, addr, this );
  45968. }
  45969. }
  45970. setValue( gl, name, value, textures ) {
  45971. const u = this.map[ name ];
  45972. if ( u !== undefined ) u.setValue( gl, value, textures );
  45973. }
  45974. setOptional( gl, object, name ) {
  45975. const v = object[ name ];
  45976. if ( v !== undefined ) this.setValue( gl, name, v );
  45977. }
  45978. static upload( gl, seq, values, textures ) {
  45979. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45980. const u = seq[ i ],
  45981. v = values[ u.id ];
  45982. if ( v.needsUpdate !== false ) {
  45983. // note: always updating when .needsUpdate is undefined
  45984. u.setValue( gl, v.value, textures );
  45985. }
  45986. }
  45987. }
  45988. static seqWithValue( seq, values ) {
  45989. const r = [];
  45990. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  45991. const u = seq[ i ];
  45992. if ( u.id in values ) r.push( u );
  45993. }
  45994. return r;
  45995. }
  45996. }
  45997. function WebGLShader( gl, type, string ) {
  45998. const shader = gl.createShader( type );
  45999. gl.shaderSource( shader, string );
  46000. gl.compileShader( shader );
  46001. return shader;
  46002. }
  46003. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46004. const COMPLETION_STATUS_KHR = 0x91B1;
  46005. let programIdCount = 0;
  46006. function handleSource( string, errorLine ) {
  46007. const lines = string.split( '\n' );
  46008. const lines2 = [];
  46009. const from = Math.max( errorLine - 6, 0 );
  46010. const to = Math.min( errorLine + 6, lines.length );
  46011. for ( let i = from; i < to; i ++ ) {
  46012. const line = i + 1;
  46013. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46014. }
  46015. return lines2.join( '\n' );
  46016. }
  46017. const _m0 = /*@__PURE__*/ new Matrix3();
  46018. function getEncodingComponents( colorSpace ) {
  46019. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46020. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46021. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46022. case LinearTransfer:
  46023. return [ encodingMatrix, 'LinearTransferOETF' ];
  46024. case SRGBTransfer:
  46025. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46026. default:
  46027. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46028. return [ encodingMatrix, 'LinearTransferOETF' ];
  46029. }
  46030. }
  46031. function getShaderErrors( gl, shader, type ) {
  46032. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46033. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46034. const errors = shaderInfoLog.trim();
  46035. if ( status && errors === '' ) return '';
  46036. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46037. if ( errorMatches ) {
  46038. // --enable-privileged-webgl-extension
  46039. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46040. const errorLine = parseInt( errorMatches[ 1 ] );
  46041. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46042. } else {
  46043. return errors;
  46044. }
  46045. }
  46046. function getTexelEncodingFunction( functionName, colorSpace ) {
  46047. const components = getEncodingComponents( colorSpace );
  46048. return [
  46049. `vec4 ${functionName}( vec4 value ) {`,
  46050. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46051. '}',
  46052. ].join( '\n' );
  46053. }
  46054. function getToneMappingFunction( functionName, toneMapping ) {
  46055. let toneMappingName;
  46056. switch ( toneMapping ) {
  46057. case LinearToneMapping:
  46058. toneMappingName = 'Linear';
  46059. break;
  46060. case ReinhardToneMapping:
  46061. toneMappingName = 'Reinhard';
  46062. break;
  46063. case CineonToneMapping:
  46064. toneMappingName = 'Cineon';
  46065. break;
  46066. case ACESFilmicToneMapping:
  46067. toneMappingName = 'ACESFilmic';
  46068. break;
  46069. case AgXToneMapping:
  46070. toneMappingName = 'AgX';
  46071. break;
  46072. case NeutralToneMapping:
  46073. toneMappingName = 'Neutral';
  46074. break;
  46075. case CustomToneMapping:
  46076. toneMappingName = 'Custom';
  46077. break;
  46078. default:
  46079. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46080. toneMappingName = 'Linear';
  46081. }
  46082. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46083. }
  46084. const _v0 = /*@__PURE__*/ new Vector3();
  46085. function getLuminanceFunction() {
  46086. ColorManagement.getLuminanceCoefficients( _v0 );
  46087. const r = _v0.x.toFixed( 4 );
  46088. const g = _v0.y.toFixed( 4 );
  46089. const b = _v0.z.toFixed( 4 );
  46090. return [
  46091. 'float luminance( const in vec3 rgb ) {',
  46092. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46093. ' return dot( weights, rgb );',
  46094. '}'
  46095. ].join( '\n' );
  46096. }
  46097. function generateVertexExtensions( parameters ) {
  46098. const chunks = [
  46099. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46100. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46101. ];
  46102. return chunks.filter( filterEmptyLine ).join( '\n' );
  46103. }
  46104. function generateDefines( defines ) {
  46105. const chunks = [];
  46106. for ( const name in defines ) {
  46107. const value = defines[ name ];
  46108. if ( value === false ) continue;
  46109. chunks.push( '#define ' + name + ' ' + value );
  46110. }
  46111. return chunks.join( '\n' );
  46112. }
  46113. function fetchAttributeLocations( gl, program ) {
  46114. const attributes = {};
  46115. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46116. for ( let i = 0; i < n; i ++ ) {
  46117. const info = gl.getActiveAttrib( program, i );
  46118. const name = info.name;
  46119. let locationSize = 1;
  46120. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46121. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46122. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46123. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46124. attributes[ name ] = {
  46125. type: info.type,
  46126. location: gl.getAttribLocation( program, name ),
  46127. locationSize: locationSize
  46128. };
  46129. }
  46130. return attributes;
  46131. }
  46132. function filterEmptyLine( string ) {
  46133. return string !== '';
  46134. }
  46135. function replaceLightNums( string, parameters ) {
  46136. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46137. return string
  46138. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46139. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46140. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46141. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46142. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46143. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46144. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46145. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46146. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46147. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46148. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46149. }
  46150. function replaceClippingPlaneNums( string, parameters ) {
  46151. return string
  46152. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46153. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46154. }
  46155. // Resolve Includes
  46156. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46157. function resolveIncludes( string ) {
  46158. return string.replace( includePattern, includeReplacer );
  46159. }
  46160. const shaderChunkMap = new Map();
  46161. function includeReplacer( match, include ) {
  46162. let string = ShaderChunk[ include ];
  46163. if ( string === undefined ) {
  46164. const newInclude = shaderChunkMap.get( include );
  46165. if ( newInclude !== undefined ) {
  46166. string = ShaderChunk[ newInclude ];
  46167. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46168. } else {
  46169. throw new Error( 'Can not resolve #include <' + include + '>' );
  46170. }
  46171. }
  46172. return resolveIncludes( string );
  46173. }
  46174. // Unroll Loops
  46175. 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;
  46176. function unrollLoops( string ) {
  46177. return string.replace( unrollLoopPattern, loopReplacer );
  46178. }
  46179. function loopReplacer( match, start, end, snippet ) {
  46180. let string = '';
  46181. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46182. string += snippet
  46183. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46184. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46185. }
  46186. return string;
  46187. }
  46188. //
  46189. function generatePrecision( parameters ) {
  46190. let precisionstring = `precision ${parameters.precision} float;
  46191. precision ${parameters.precision} int;
  46192. precision ${parameters.precision} sampler2D;
  46193. precision ${parameters.precision} samplerCube;
  46194. precision ${parameters.precision} sampler3D;
  46195. precision ${parameters.precision} sampler2DArray;
  46196. precision ${parameters.precision} sampler2DShadow;
  46197. precision ${parameters.precision} samplerCubeShadow;
  46198. precision ${parameters.precision} sampler2DArrayShadow;
  46199. precision ${parameters.precision} isampler2D;
  46200. precision ${parameters.precision} isampler3D;
  46201. precision ${parameters.precision} isamplerCube;
  46202. precision ${parameters.precision} isampler2DArray;
  46203. precision ${parameters.precision} usampler2D;
  46204. precision ${parameters.precision} usampler3D;
  46205. precision ${parameters.precision} usamplerCube;
  46206. precision ${parameters.precision} usampler2DArray;
  46207. `;
  46208. if ( parameters.precision === 'highp' ) {
  46209. precisionstring += '\n#define HIGH_PRECISION';
  46210. } else if ( parameters.precision === 'mediump' ) {
  46211. precisionstring += '\n#define MEDIUM_PRECISION';
  46212. } else if ( parameters.precision === 'lowp' ) {
  46213. precisionstring += '\n#define LOW_PRECISION';
  46214. }
  46215. return precisionstring;
  46216. }
  46217. function generateShadowMapTypeDefine( parameters ) {
  46218. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  46219. if ( parameters.shadowMapType === PCFShadowMap ) {
  46220. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  46221. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  46222. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  46223. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  46224. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  46225. }
  46226. return shadowMapTypeDefine;
  46227. }
  46228. function generateEnvMapTypeDefine( parameters ) {
  46229. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46230. if ( parameters.envMap ) {
  46231. switch ( parameters.envMapMode ) {
  46232. case CubeReflectionMapping:
  46233. case CubeRefractionMapping:
  46234. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46235. break;
  46236. case CubeUVReflectionMapping:
  46237. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  46238. break;
  46239. }
  46240. }
  46241. return envMapTypeDefine;
  46242. }
  46243. function generateEnvMapModeDefine( parameters ) {
  46244. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  46245. if ( parameters.envMap ) {
  46246. switch ( parameters.envMapMode ) {
  46247. case CubeRefractionMapping:
  46248. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  46249. break;
  46250. }
  46251. }
  46252. return envMapModeDefine;
  46253. }
  46254. function generateEnvMapBlendingDefine( parameters ) {
  46255. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  46256. if ( parameters.envMap ) {
  46257. switch ( parameters.combine ) {
  46258. case MultiplyOperation:
  46259. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  46260. break;
  46261. case MixOperation:
  46262. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  46263. break;
  46264. case AddOperation:
  46265. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  46266. break;
  46267. }
  46268. }
  46269. return envMapBlendingDefine;
  46270. }
  46271. function generateCubeUVSize( parameters ) {
  46272. const imageHeight = parameters.envMapCubeUVHeight;
  46273. if ( imageHeight === null ) return null;
  46274. const maxMip = Math.log2( imageHeight ) - 2;
  46275. const texelHeight = 1.0 / imageHeight;
  46276. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46277. return { texelWidth, texelHeight, maxMip };
  46278. }
  46279. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46280. // TODO Send this event to Three.js DevTools
  46281. // log( 'WebGLProgram', cacheKey );
  46282. const gl = renderer.getContext();
  46283. const defines = parameters.defines;
  46284. let vertexShader = parameters.vertexShader;
  46285. let fragmentShader = parameters.fragmentShader;
  46286. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46287. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46288. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46289. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46290. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46291. const customVertexExtensions = generateVertexExtensions( parameters );
  46292. const customDefines = generateDefines( defines );
  46293. const program = gl.createProgram();
  46294. let prefixVertex, prefixFragment;
  46295. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46296. if ( parameters.isRawShaderMaterial ) {
  46297. prefixVertex = [
  46298. '#define SHADER_TYPE ' + parameters.shaderType,
  46299. '#define SHADER_NAME ' + parameters.shaderName,
  46300. customDefines
  46301. ].filter( filterEmptyLine ).join( '\n' );
  46302. if ( prefixVertex.length > 0 ) {
  46303. prefixVertex += '\n';
  46304. }
  46305. prefixFragment = [
  46306. '#define SHADER_TYPE ' + parameters.shaderType,
  46307. '#define SHADER_NAME ' + parameters.shaderName,
  46308. customDefines
  46309. ].filter( filterEmptyLine ).join( '\n' );
  46310. if ( prefixFragment.length > 0 ) {
  46311. prefixFragment += '\n';
  46312. }
  46313. } else {
  46314. prefixVertex = [
  46315. generatePrecision( parameters ),
  46316. '#define SHADER_TYPE ' + parameters.shaderType,
  46317. '#define SHADER_NAME ' + parameters.shaderName,
  46318. customDefines,
  46319. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46320. parameters.batching ? '#define USE_BATCHING' : '',
  46321. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46322. parameters.instancing ? '#define USE_INSTANCING' : '',
  46323. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46324. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46325. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46326. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46327. parameters.map ? '#define USE_MAP' : '',
  46328. parameters.envMap ? '#define USE_ENVMAP' : '',
  46329. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46330. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46331. parameters.aoMap ? '#define USE_AOMAP' : '',
  46332. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46333. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46334. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46335. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46336. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46337. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46338. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46339. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46340. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46341. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46342. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46343. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46344. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46345. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46346. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46347. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46348. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46349. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46350. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46351. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46352. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46353. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46354. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46355. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46356. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46357. //
  46358. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46359. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46360. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46361. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46362. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46363. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46364. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46365. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46366. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46367. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46368. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46369. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46370. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46371. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46372. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46373. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46374. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46375. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46376. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46377. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46378. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46379. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46380. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46381. //
  46382. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46383. parameters.vertexColors ? '#define USE_COLOR' : '',
  46384. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46385. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46386. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46387. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46388. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46389. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46390. parameters.skinning ? '#define USE_SKINNING' : '',
  46391. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46392. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46393. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46394. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46395. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46396. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46397. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46398. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46399. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46400. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46401. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46402. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46403. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46404. 'uniform mat4 modelMatrix;',
  46405. 'uniform mat4 modelViewMatrix;',
  46406. 'uniform mat4 projectionMatrix;',
  46407. 'uniform mat4 viewMatrix;',
  46408. 'uniform mat3 normalMatrix;',
  46409. 'uniform vec3 cameraPosition;',
  46410. 'uniform bool isOrthographic;',
  46411. '#ifdef USE_INSTANCING',
  46412. ' attribute mat4 instanceMatrix;',
  46413. '#endif',
  46414. '#ifdef USE_INSTANCING_COLOR',
  46415. ' attribute vec3 instanceColor;',
  46416. '#endif',
  46417. '#ifdef USE_INSTANCING_MORPH',
  46418. ' uniform sampler2D morphTexture;',
  46419. '#endif',
  46420. 'attribute vec3 position;',
  46421. 'attribute vec3 normal;',
  46422. 'attribute vec2 uv;',
  46423. '#ifdef USE_UV1',
  46424. ' attribute vec2 uv1;',
  46425. '#endif',
  46426. '#ifdef USE_UV2',
  46427. ' attribute vec2 uv2;',
  46428. '#endif',
  46429. '#ifdef USE_UV3',
  46430. ' attribute vec2 uv3;',
  46431. '#endif',
  46432. '#ifdef USE_TANGENT',
  46433. ' attribute vec4 tangent;',
  46434. '#endif',
  46435. '#if defined( USE_COLOR_ALPHA )',
  46436. ' attribute vec4 color;',
  46437. '#elif defined( USE_COLOR )',
  46438. ' attribute vec3 color;',
  46439. '#endif',
  46440. '#ifdef USE_SKINNING',
  46441. ' attribute vec4 skinIndex;',
  46442. ' attribute vec4 skinWeight;',
  46443. '#endif',
  46444. '\n'
  46445. ].filter( filterEmptyLine ).join( '\n' );
  46446. prefixFragment = [
  46447. generatePrecision( parameters ),
  46448. '#define SHADER_TYPE ' + parameters.shaderType,
  46449. '#define SHADER_NAME ' + parameters.shaderName,
  46450. customDefines,
  46451. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46452. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46453. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46454. parameters.map ? '#define USE_MAP' : '',
  46455. parameters.matcap ? '#define USE_MATCAP' : '',
  46456. parameters.envMap ? '#define USE_ENVMAP' : '',
  46457. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46458. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46459. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46460. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46461. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46462. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46463. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46464. parameters.aoMap ? '#define USE_AOMAP' : '',
  46465. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46466. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46467. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46468. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46469. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46470. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46471. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46472. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46473. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46474. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46475. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46476. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46477. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46478. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46479. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46480. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46481. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46482. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46483. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46484. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46485. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46486. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46487. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46488. parameters.sheen ? '#define USE_SHEEN' : '',
  46489. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46490. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46491. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46492. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46493. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46494. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46495. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46496. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46497. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46498. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46499. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46500. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46501. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46502. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46503. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46504. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46505. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46506. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46507. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46508. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46509. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46510. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46511. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46512. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46513. 'uniform mat4 viewMatrix;',
  46514. 'uniform vec3 cameraPosition;',
  46515. 'uniform bool isOrthographic;',
  46516. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46517. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46518. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46519. parameters.dithering ? '#define DITHERING' : '',
  46520. parameters.opaque ? '#define OPAQUE' : '',
  46521. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46522. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46523. getLuminanceFunction(),
  46524. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46525. '\n'
  46526. ].filter( filterEmptyLine ).join( '\n' );
  46527. }
  46528. vertexShader = resolveIncludes( vertexShader );
  46529. vertexShader = replaceLightNums( vertexShader, parameters );
  46530. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46531. fragmentShader = resolveIncludes( fragmentShader );
  46532. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46533. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46534. vertexShader = unrollLoops( vertexShader );
  46535. fragmentShader = unrollLoops( fragmentShader );
  46536. if ( parameters.isRawShaderMaterial !== true ) {
  46537. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46538. versionString = '#version 300 es\n';
  46539. prefixVertex = [
  46540. customVertexExtensions,
  46541. '#define attribute in',
  46542. '#define varying out',
  46543. '#define texture2D texture'
  46544. ].join( '\n' ) + '\n' + prefixVertex;
  46545. prefixFragment = [
  46546. '#define varying in',
  46547. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  46548. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  46549. '#define gl_FragDepthEXT gl_FragDepth',
  46550. '#define texture2D texture',
  46551. '#define textureCube texture',
  46552. '#define texture2DProj textureProj',
  46553. '#define texture2DLodEXT textureLod',
  46554. '#define texture2DProjLodEXT textureProjLod',
  46555. '#define textureCubeLodEXT textureLod',
  46556. '#define texture2DGradEXT textureGrad',
  46557. '#define texture2DProjGradEXT textureProjGrad',
  46558. '#define textureCubeGradEXT textureGrad'
  46559. ].join( '\n' ) + '\n' + prefixFragment;
  46560. }
  46561. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46562. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46563. // log( '*VERTEX*', vertexGlsl );
  46564. // log( '*FRAGMENT*', fragmentGlsl );
  46565. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46566. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46567. gl.attachShader( program, glVertexShader );
  46568. gl.attachShader( program, glFragmentShader );
  46569. // Force a particular attribute to index 0.
  46570. if ( parameters.index0AttributeName !== undefined ) {
  46571. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46572. } else if ( parameters.morphTargets === true ) {
  46573. // programs with morphTargets displace position out of attribute 0
  46574. gl.bindAttribLocation( program, 0, 'position' );
  46575. }
  46576. gl.linkProgram( program );
  46577. function onFirstUse( self ) {
  46578. // check for link errors
  46579. if ( renderer.debug.checkShaderErrors ) {
  46580. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  46581. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  46582. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  46583. const programLog = programInfoLog.trim();
  46584. const vertexLog = vertexShaderInfoLog.trim();
  46585. const fragmentLog = fragmentShaderInfoLog.trim();
  46586. let runnable = true;
  46587. let haveDiagnostics = true;
  46588. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46589. runnable = false;
  46590. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46591. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46592. } else {
  46593. // default error reporting
  46594. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46595. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46596. error(
  46597. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46598. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46599. 'Material Name: ' + self.name + '\n' +
  46600. 'Material Type: ' + self.type + '\n\n' +
  46601. 'Program Info Log: ' + programLog + '\n' +
  46602. vertexErrors + '\n' +
  46603. fragmentErrors
  46604. );
  46605. }
  46606. } else if ( programLog !== '' ) {
  46607. warn( 'WebGLProgram: Program Info Log:', programLog );
  46608. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46609. haveDiagnostics = false;
  46610. }
  46611. if ( haveDiagnostics ) {
  46612. self.diagnostics = {
  46613. runnable: runnable,
  46614. programLog: programLog,
  46615. vertexShader: {
  46616. log: vertexLog,
  46617. prefix: prefixVertex
  46618. },
  46619. fragmentShader: {
  46620. log: fragmentLog,
  46621. prefix: prefixFragment
  46622. }
  46623. };
  46624. }
  46625. }
  46626. // Clean up
  46627. // Crashes in iOS9 and iOS10. #18402
  46628. // gl.detachShader( program, glVertexShader );
  46629. // gl.detachShader( program, glFragmentShader );
  46630. gl.deleteShader( glVertexShader );
  46631. gl.deleteShader( glFragmentShader );
  46632. cachedUniforms = new WebGLUniforms( gl, program );
  46633. cachedAttributes = fetchAttributeLocations( gl, program );
  46634. }
  46635. // set up caching for uniform locations
  46636. let cachedUniforms;
  46637. this.getUniforms = function () {
  46638. if ( cachedUniforms === undefined ) {
  46639. // Populates cachedUniforms and cachedAttributes
  46640. onFirstUse( this );
  46641. }
  46642. return cachedUniforms;
  46643. };
  46644. // set up caching for attribute locations
  46645. let cachedAttributes;
  46646. this.getAttributes = function () {
  46647. if ( cachedAttributes === undefined ) {
  46648. // Populates cachedAttributes and cachedUniforms
  46649. onFirstUse( this );
  46650. }
  46651. return cachedAttributes;
  46652. };
  46653. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46654. // flag the program as ready immediately. It may cause a stall when it's first used.
  46655. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46656. this.isReady = function () {
  46657. if ( programReady === false ) {
  46658. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46659. }
  46660. return programReady;
  46661. };
  46662. // free resource
  46663. this.destroy = function () {
  46664. bindingStates.releaseStatesOfProgram( this );
  46665. gl.deleteProgram( program );
  46666. this.program = undefined;
  46667. };
  46668. //
  46669. this.type = parameters.shaderType;
  46670. this.name = parameters.shaderName;
  46671. this.id = programIdCount ++;
  46672. this.cacheKey = cacheKey;
  46673. this.usedTimes = 1;
  46674. this.program = program;
  46675. this.vertexShader = glVertexShader;
  46676. this.fragmentShader = glFragmentShader;
  46677. return this;
  46678. }
  46679. let _id = 0;
  46680. class WebGLShaderCache {
  46681. constructor() {
  46682. this.shaderCache = new Map();
  46683. this.materialCache = new Map();
  46684. }
  46685. update( material ) {
  46686. const vertexShader = material.vertexShader;
  46687. const fragmentShader = material.fragmentShader;
  46688. const vertexShaderStage = this._getShaderStage( vertexShader );
  46689. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  46690. const materialShaders = this._getShaderCacheForMaterial( material );
  46691. if ( materialShaders.has( vertexShaderStage ) === false ) {
  46692. materialShaders.add( vertexShaderStage );
  46693. vertexShaderStage.usedTimes ++;
  46694. }
  46695. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  46696. materialShaders.add( fragmentShaderStage );
  46697. fragmentShaderStage.usedTimes ++;
  46698. }
  46699. return this;
  46700. }
  46701. remove( material ) {
  46702. const materialShaders = this.materialCache.get( material );
  46703. for ( const shaderStage of materialShaders ) {
  46704. shaderStage.usedTimes --;
  46705. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  46706. }
  46707. this.materialCache.delete( material );
  46708. return this;
  46709. }
  46710. getVertexShaderID( material ) {
  46711. return this._getShaderStage( material.vertexShader ).id;
  46712. }
  46713. getFragmentShaderID( material ) {
  46714. return this._getShaderStage( material.fragmentShader ).id;
  46715. }
  46716. dispose() {
  46717. this.shaderCache.clear();
  46718. this.materialCache.clear();
  46719. }
  46720. _getShaderCacheForMaterial( material ) {
  46721. const cache = this.materialCache;
  46722. let set = cache.get( material );
  46723. if ( set === undefined ) {
  46724. set = new Set();
  46725. cache.set( material, set );
  46726. }
  46727. return set;
  46728. }
  46729. _getShaderStage( code ) {
  46730. const cache = this.shaderCache;
  46731. let stage = cache.get( code );
  46732. if ( stage === undefined ) {
  46733. stage = new WebGLShaderStage( code );
  46734. cache.set( code, stage );
  46735. }
  46736. return stage;
  46737. }
  46738. }
  46739. class WebGLShaderStage {
  46740. constructor( code ) {
  46741. this.id = _id ++;
  46742. this.code = code;
  46743. this.usedTimes = 0;
  46744. }
  46745. }
  46746. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  46747. const _programLayers = new Layers();
  46748. const _customShaders = new WebGLShaderCache();
  46749. const _activeChannels = new Set();
  46750. const programs = [];
  46751. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  46752. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  46753. let precision = capabilities.precision;
  46754. const shaderIDs = {
  46755. MeshDepthMaterial: 'depth',
  46756. MeshDistanceMaterial: 'distanceRGBA',
  46757. MeshNormalMaterial: 'normal',
  46758. MeshBasicMaterial: 'basic',
  46759. MeshLambertMaterial: 'lambert',
  46760. MeshPhongMaterial: 'phong',
  46761. MeshToonMaterial: 'toon',
  46762. MeshStandardMaterial: 'physical',
  46763. MeshPhysicalMaterial: 'physical',
  46764. MeshMatcapMaterial: 'matcap',
  46765. LineBasicMaterial: 'basic',
  46766. LineDashedMaterial: 'dashed',
  46767. PointsMaterial: 'points',
  46768. ShadowMaterial: 'shadow',
  46769. SpriteMaterial: 'sprite'
  46770. };
  46771. function getChannel( value ) {
  46772. _activeChannels.add( value );
  46773. if ( value === 0 ) return 'uv';
  46774. return `uv${ value }`;
  46775. }
  46776. function getParameters( material, lights, shadows, scene, object ) {
  46777. const fog = scene.fog;
  46778. const geometry = object.geometry;
  46779. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  46780. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  46781. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  46782. const shaderID = shaderIDs[ material.type ];
  46783. // heuristics to create shader parameters according to lights in the scene
  46784. // (not to blow over maxLights budget)
  46785. if ( material.precision !== null ) {
  46786. precision = capabilities.getMaxPrecision( material.precision );
  46787. if ( precision !== material.precision ) {
  46788. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  46789. }
  46790. }
  46791. //
  46792. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  46793. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  46794. let morphTextureStride = 0;
  46795. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  46796. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  46797. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  46798. //
  46799. let vertexShader, fragmentShader;
  46800. let customVertexShaderID, customFragmentShaderID;
  46801. if ( shaderID ) {
  46802. const shader = ShaderLib[ shaderID ];
  46803. vertexShader = shader.vertexShader;
  46804. fragmentShader = shader.fragmentShader;
  46805. } else {
  46806. vertexShader = material.vertexShader;
  46807. fragmentShader = material.fragmentShader;
  46808. _customShaders.update( material );
  46809. customVertexShaderID = _customShaders.getVertexShaderID( material );
  46810. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  46811. }
  46812. const currentRenderTarget = renderer.getRenderTarget();
  46813. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  46814. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  46815. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  46816. const HAS_MAP = !! material.map;
  46817. const HAS_MATCAP = !! material.matcap;
  46818. const HAS_ENVMAP = !! envMap;
  46819. const HAS_AOMAP = !! material.aoMap;
  46820. const HAS_LIGHTMAP = !! material.lightMap;
  46821. const HAS_BUMPMAP = !! material.bumpMap;
  46822. const HAS_NORMALMAP = !! material.normalMap;
  46823. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  46824. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  46825. const HAS_METALNESSMAP = !! material.metalnessMap;
  46826. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  46827. const HAS_ANISOTROPY = material.anisotropy > 0;
  46828. const HAS_CLEARCOAT = material.clearcoat > 0;
  46829. const HAS_DISPERSION = material.dispersion > 0;
  46830. const HAS_IRIDESCENCE = material.iridescence > 0;
  46831. const HAS_SHEEN = material.sheen > 0;
  46832. const HAS_TRANSMISSION = material.transmission > 0;
  46833. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  46834. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  46835. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  46836. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  46837. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  46838. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  46839. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  46840. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  46841. const HAS_SPECULARMAP = !! material.specularMap;
  46842. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  46843. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  46844. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  46845. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  46846. const HAS_GRADIENTMAP = !! material.gradientMap;
  46847. const HAS_ALPHAMAP = !! material.alphaMap;
  46848. const HAS_ALPHATEST = material.alphaTest > 0;
  46849. const HAS_ALPHAHASH = !! material.alphaHash;
  46850. const HAS_EXTENSIONS = !! material.extensions;
  46851. let toneMapping = NoToneMapping;
  46852. if ( material.toneMapped ) {
  46853. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  46854. toneMapping = renderer.toneMapping;
  46855. }
  46856. }
  46857. const parameters = {
  46858. shaderID: shaderID,
  46859. shaderType: material.type,
  46860. shaderName: material.name,
  46861. vertexShader: vertexShader,
  46862. fragmentShader: fragmentShader,
  46863. defines: material.defines,
  46864. customVertexShaderID: customVertexShaderID,
  46865. customFragmentShaderID: customFragmentShaderID,
  46866. isRawShaderMaterial: material.isRawShaderMaterial === true,
  46867. glslVersion: material.glslVersion,
  46868. precision: precision,
  46869. batching: IS_BATCHEDMESH,
  46870. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  46871. instancing: IS_INSTANCEDMESH,
  46872. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  46873. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  46874. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  46875. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  46876. alphaToCoverage: !! material.alphaToCoverage,
  46877. map: HAS_MAP,
  46878. matcap: HAS_MATCAP,
  46879. envMap: HAS_ENVMAP,
  46880. envMapMode: HAS_ENVMAP && envMap.mapping,
  46881. envMapCubeUVHeight: envMapCubeUVHeight,
  46882. aoMap: HAS_AOMAP,
  46883. lightMap: HAS_LIGHTMAP,
  46884. bumpMap: HAS_BUMPMAP,
  46885. normalMap: HAS_NORMALMAP,
  46886. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  46887. emissiveMap: HAS_EMISSIVEMAP,
  46888. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  46889. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  46890. metalnessMap: HAS_METALNESSMAP,
  46891. roughnessMap: HAS_ROUGHNESSMAP,
  46892. anisotropy: HAS_ANISOTROPY,
  46893. anisotropyMap: HAS_ANISOTROPYMAP,
  46894. clearcoat: HAS_CLEARCOAT,
  46895. clearcoatMap: HAS_CLEARCOATMAP,
  46896. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  46897. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  46898. dispersion: HAS_DISPERSION,
  46899. iridescence: HAS_IRIDESCENCE,
  46900. iridescenceMap: HAS_IRIDESCENCEMAP,
  46901. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  46902. sheen: HAS_SHEEN,
  46903. sheenColorMap: HAS_SHEEN_COLORMAP,
  46904. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  46905. specularMap: HAS_SPECULARMAP,
  46906. specularColorMap: HAS_SPECULAR_COLORMAP,
  46907. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  46908. transmission: HAS_TRANSMISSION,
  46909. transmissionMap: HAS_TRANSMISSIONMAP,
  46910. thicknessMap: HAS_THICKNESSMAP,
  46911. gradientMap: HAS_GRADIENTMAP,
  46912. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  46913. alphaMap: HAS_ALPHAMAP,
  46914. alphaTest: HAS_ALPHATEST,
  46915. alphaHash: HAS_ALPHAHASH,
  46916. combine: material.combine,
  46917. //
  46918. mapUv: HAS_MAP && getChannel( material.map.channel ),
  46919. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  46920. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  46921. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  46922. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  46923. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  46924. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  46925. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  46926. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  46927. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  46928. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  46929. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  46930. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  46931. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  46932. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  46933. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  46934. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  46935. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  46936. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  46937. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  46938. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  46939. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  46940. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  46941. //
  46942. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  46943. vertexColors: material.vertexColors,
  46944. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  46945. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  46946. fog: !! fog,
  46947. useFog: material.fog === true,
  46948. fogExp2: ( !! fog && fog.isFogExp2 ),
  46949. flatShading: ( material.flatShading === true && material.wireframe === false ),
  46950. sizeAttenuation: material.sizeAttenuation === true,
  46951. logarithmicDepthBuffer: logarithmicDepthBuffer,
  46952. reversedDepthBuffer: reversedDepthBuffer,
  46953. skinning: object.isSkinnedMesh === true,
  46954. morphTargets: geometry.morphAttributes.position !== undefined,
  46955. morphNormals: geometry.morphAttributes.normal !== undefined,
  46956. morphColors: geometry.morphAttributes.color !== undefined,
  46957. morphTargetsCount: morphTargetsCount,
  46958. morphTextureStride: morphTextureStride,
  46959. numDirLights: lights.directional.length,
  46960. numPointLights: lights.point.length,
  46961. numSpotLights: lights.spot.length,
  46962. numSpotLightMaps: lights.spotLightMap.length,
  46963. numRectAreaLights: lights.rectArea.length,
  46964. numHemiLights: lights.hemi.length,
  46965. numDirLightShadows: lights.directionalShadowMap.length,
  46966. numPointLightShadows: lights.pointShadowMap.length,
  46967. numSpotLightShadows: lights.spotShadowMap.length,
  46968. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  46969. numLightProbes: lights.numLightProbes,
  46970. numClippingPlanes: clipping.numPlanes,
  46971. numClipIntersection: clipping.numIntersection,
  46972. dithering: material.dithering,
  46973. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  46974. shadowMapType: renderer.shadowMap.type,
  46975. toneMapping: toneMapping,
  46976. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  46977. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  46978. premultipliedAlpha: material.premultipliedAlpha,
  46979. doubleSided: material.side === DoubleSide,
  46980. flipSided: material.side === BackSide,
  46981. useDepthPacking: material.depthPacking >= 0,
  46982. depthPacking: material.depthPacking || 0,
  46983. index0AttributeName: material.index0AttributeName,
  46984. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  46985. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  46986. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  46987. customProgramCacheKey: material.customProgramCacheKey()
  46988. };
  46989. // the usage of getChannel() determines the active texture channels for this shader
  46990. parameters.vertexUv1s = _activeChannels.has( 1 );
  46991. parameters.vertexUv2s = _activeChannels.has( 2 );
  46992. parameters.vertexUv3s = _activeChannels.has( 3 );
  46993. _activeChannels.clear();
  46994. return parameters;
  46995. }
  46996. function getProgramCacheKey( parameters ) {
  46997. const array = [];
  46998. if ( parameters.shaderID ) {
  46999. array.push( parameters.shaderID );
  47000. } else {
  47001. array.push( parameters.customVertexShaderID );
  47002. array.push( parameters.customFragmentShaderID );
  47003. }
  47004. if ( parameters.defines !== undefined ) {
  47005. for ( const name in parameters.defines ) {
  47006. array.push( name );
  47007. array.push( parameters.defines[ name ] );
  47008. }
  47009. }
  47010. if ( parameters.isRawShaderMaterial === false ) {
  47011. getProgramCacheKeyParameters( array, parameters );
  47012. getProgramCacheKeyBooleans( array, parameters );
  47013. array.push( renderer.outputColorSpace );
  47014. }
  47015. array.push( parameters.customProgramCacheKey );
  47016. return array.join();
  47017. }
  47018. function getProgramCacheKeyParameters( array, parameters ) {
  47019. array.push( parameters.precision );
  47020. array.push( parameters.outputColorSpace );
  47021. array.push( parameters.envMapMode );
  47022. array.push( parameters.envMapCubeUVHeight );
  47023. array.push( parameters.mapUv );
  47024. array.push( parameters.alphaMapUv );
  47025. array.push( parameters.lightMapUv );
  47026. array.push( parameters.aoMapUv );
  47027. array.push( parameters.bumpMapUv );
  47028. array.push( parameters.normalMapUv );
  47029. array.push( parameters.displacementMapUv );
  47030. array.push( parameters.emissiveMapUv );
  47031. array.push( parameters.metalnessMapUv );
  47032. array.push( parameters.roughnessMapUv );
  47033. array.push( parameters.anisotropyMapUv );
  47034. array.push( parameters.clearcoatMapUv );
  47035. array.push( parameters.clearcoatNormalMapUv );
  47036. array.push( parameters.clearcoatRoughnessMapUv );
  47037. array.push( parameters.iridescenceMapUv );
  47038. array.push( parameters.iridescenceThicknessMapUv );
  47039. array.push( parameters.sheenColorMapUv );
  47040. array.push( parameters.sheenRoughnessMapUv );
  47041. array.push( parameters.specularMapUv );
  47042. array.push( parameters.specularColorMapUv );
  47043. array.push( parameters.specularIntensityMapUv );
  47044. array.push( parameters.transmissionMapUv );
  47045. array.push( parameters.thicknessMapUv );
  47046. array.push( parameters.combine );
  47047. array.push( parameters.fogExp2 );
  47048. array.push( parameters.sizeAttenuation );
  47049. array.push( parameters.morphTargetsCount );
  47050. array.push( parameters.morphAttributeCount );
  47051. array.push( parameters.numDirLights );
  47052. array.push( parameters.numPointLights );
  47053. array.push( parameters.numSpotLights );
  47054. array.push( parameters.numSpotLightMaps );
  47055. array.push( parameters.numHemiLights );
  47056. array.push( parameters.numRectAreaLights );
  47057. array.push( parameters.numDirLightShadows );
  47058. array.push( parameters.numPointLightShadows );
  47059. array.push( parameters.numSpotLightShadows );
  47060. array.push( parameters.numSpotLightShadowsWithMaps );
  47061. array.push( parameters.numLightProbes );
  47062. array.push( parameters.shadowMapType );
  47063. array.push( parameters.toneMapping );
  47064. array.push( parameters.numClippingPlanes );
  47065. array.push( parameters.numClipIntersection );
  47066. array.push( parameters.depthPacking );
  47067. }
  47068. function getProgramCacheKeyBooleans( array, parameters ) {
  47069. _programLayers.disableAll();
  47070. if ( parameters.supportsVertexTextures )
  47071. _programLayers.enable( 0 );
  47072. if ( parameters.instancing )
  47073. _programLayers.enable( 1 );
  47074. if ( parameters.instancingColor )
  47075. _programLayers.enable( 2 );
  47076. if ( parameters.instancingMorph )
  47077. _programLayers.enable( 3 );
  47078. if ( parameters.matcap )
  47079. _programLayers.enable( 4 );
  47080. if ( parameters.envMap )
  47081. _programLayers.enable( 5 );
  47082. if ( parameters.normalMapObjectSpace )
  47083. _programLayers.enable( 6 );
  47084. if ( parameters.normalMapTangentSpace )
  47085. _programLayers.enable( 7 );
  47086. if ( parameters.clearcoat )
  47087. _programLayers.enable( 8 );
  47088. if ( parameters.iridescence )
  47089. _programLayers.enable( 9 );
  47090. if ( parameters.alphaTest )
  47091. _programLayers.enable( 10 );
  47092. if ( parameters.vertexColors )
  47093. _programLayers.enable( 11 );
  47094. if ( parameters.vertexAlphas )
  47095. _programLayers.enable( 12 );
  47096. if ( parameters.vertexUv1s )
  47097. _programLayers.enable( 13 );
  47098. if ( parameters.vertexUv2s )
  47099. _programLayers.enable( 14 );
  47100. if ( parameters.vertexUv3s )
  47101. _programLayers.enable( 15 );
  47102. if ( parameters.vertexTangents )
  47103. _programLayers.enable( 16 );
  47104. if ( parameters.anisotropy )
  47105. _programLayers.enable( 17 );
  47106. if ( parameters.alphaHash )
  47107. _programLayers.enable( 18 );
  47108. if ( parameters.batching )
  47109. _programLayers.enable( 19 );
  47110. if ( parameters.dispersion )
  47111. _programLayers.enable( 20 );
  47112. if ( parameters.batchingColor )
  47113. _programLayers.enable( 21 );
  47114. if ( parameters.gradientMap )
  47115. _programLayers.enable( 22 );
  47116. array.push( _programLayers.mask );
  47117. _programLayers.disableAll();
  47118. if ( parameters.fog )
  47119. _programLayers.enable( 0 );
  47120. if ( parameters.useFog )
  47121. _programLayers.enable( 1 );
  47122. if ( parameters.flatShading )
  47123. _programLayers.enable( 2 );
  47124. if ( parameters.logarithmicDepthBuffer )
  47125. _programLayers.enable( 3 );
  47126. if ( parameters.reversedDepthBuffer )
  47127. _programLayers.enable( 4 );
  47128. if ( parameters.skinning )
  47129. _programLayers.enable( 5 );
  47130. if ( parameters.morphTargets )
  47131. _programLayers.enable( 6 );
  47132. if ( parameters.morphNormals )
  47133. _programLayers.enable( 7 );
  47134. if ( parameters.morphColors )
  47135. _programLayers.enable( 8 );
  47136. if ( parameters.premultipliedAlpha )
  47137. _programLayers.enable( 9 );
  47138. if ( parameters.shadowMapEnabled )
  47139. _programLayers.enable( 10 );
  47140. if ( parameters.doubleSided )
  47141. _programLayers.enable( 11 );
  47142. if ( parameters.flipSided )
  47143. _programLayers.enable( 12 );
  47144. if ( parameters.useDepthPacking )
  47145. _programLayers.enable( 13 );
  47146. if ( parameters.dithering )
  47147. _programLayers.enable( 14 );
  47148. if ( parameters.transmission )
  47149. _programLayers.enable( 15 );
  47150. if ( parameters.sheen )
  47151. _programLayers.enable( 16 );
  47152. if ( parameters.opaque )
  47153. _programLayers.enable( 17 );
  47154. if ( parameters.pointsUvs )
  47155. _programLayers.enable( 18 );
  47156. if ( parameters.decodeVideoTexture )
  47157. _programLayers.enable( 19 );
  47158. if ( parameters.decodeVideoTextureEmissive )
  47159. _programLayers.enable( 20 );
  47160. if ( parameters.alphaToCoverage )
  47161. _programLayers.enable( 21 );
  47162. array.push( _programLayers.mask );
  47163. }
  47164. function getUniforms( material ) {
  47165. const shaderID = shaderIDs[ material.type ];
  47166. let uniforms;
  47167. if ( shaderID ) {
  47168. const shader = ShaderLib[ shaderID ];
  47169. uniforms = UniformsUtils.clone( shader.uniforms );
  47170. } else {
  47171. uniforms = material.uniforms;
  47172. }
  47173. return uniforms;
  47174. }
  47175. function acquireProgram( parameters, cacheKey ) {
  47176. let program;
  47177. // Check if code has been already compiled
  47178. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  47179. const preexistingProgram = programs[ p ];
  47180. if ( preexistingProgram.cacheKey === cacheKey ) {
  47181. program = preexistingProgram;
  47182. ++ program.usedTimes;
  47183. break;
  47184. }
  47185. }
  47186. if ( program === undefined ) {
  47187. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47188. programs.push( program );
  47189. }
  47190. return program;
  47191. }
  47192. function releaseProgram( program ) {
  47193. if ( -- program.usedTimes === 0 ) {
  47194. // Remove from unordered set
  47195. const i = programs.indexOf( program );
  47196. programs[ i ] = programs[ programs.length - 1 ];
  47197. programs.pop();
  47198. // Free WebGL resources
  47199. program.destroy();
  47200. }
  47201. }
  47202. function releaseShaderCache( material ) {
  47203. _customShaders.remove( material );
  47204. }
  47205. function dispose() {
  47206. _customShaders.dispose();
  47207. }
  47208. return {
  47209. getParameters: getParameters,
  47210. getProgramCacheKey: getProgramCacheKey,
  47211. getUniforms: getUniforms,
  47212. acquireProgram: acquireProgram,
  47213. releaseProgram: releaseProgram,
  47214. releaseShaderCache: releaseShaderCache,
  47215. // Exposed for resource monitoring & error feedback via renderer.info:
  47216. programs: programs,
  47217. dispose: dispose
  47218. };
  47219. }
  47220. function WebGLProperties() {
  47221. let properties = new WeakMap();
  47222. function has( object ) {
  47223. return properties.has( object );
  47224. }
  47225. function get( object ) {
  47226. let map = properties.get( object );
  47227. if ( map === undefined ) {
  47228. map = {};
  47229. properties.set( object, map );
  47230. }
  47231. return map;
  47232. }
  47233. function remove( object ) {
  47234. properties.delete( object );
  47235. }
  47236. function update( object, key, value ) {
  47237. properties.get( object )[ key ] = value;
  47238. }
  47239. function dispose() {
  47240. properties = new WeakMap();
  47241. }
  47242. return {
  47243. has: has,
  47244. get: get,
  47245. remove: remove,
  47246. update: update,
  47247. dispose: dispose
  47248. };
  47249. }
  47250. function painterSortStable( a, b ) {
  47251. if ( a.groupOrder !== b.groupOrder ) {
  47252. return a.groupOrder - b.groupOrder;
  47253. } else if ( a.renderOrder !== b.renderOrder ) {
  47254. return a.renderOrder - b.renderOrder;
  47255. } else if ( a.material.id !== b.material.id ) {
  47256. return a.material.id - b.material.id;
  47257. } else if ( a.z !== b.z ) {
  47258. return a.z - b.z;
  47259. } else {
  47260. return a.id - b.id;
  47261. }
  47262. }
  47263. function reversePainterSortStable( a, b ) {
  47264. if ( a.groupOrder !== b.groupOrder ) {
  47265. return a.groupOrder - b.groupOrder;
  47266. } else if ( a.renderOrder !== b.renderOrder ) {
  47267. return a.renderOrder - b.renderOrder;
  47268. } else if ( a.z !== b.z ) {
  47269. return b.z - a.z;
  47270. } else {
  47271. return a.id - b.id;
  47272. }
  47273. }
  47274. function WebGLRenderList() {
  47275. const renderItems = [];
  47276. let renderItemsIndex = 0;
  47277. const opaque = [];
  47278. const transmissive = [];
  47279. const transparent = [];
  47280. function init() {
  47281. renderItemsIndex = 0;
  47282. opaque.length = 0;
  47283. transmissive.length = 0;
  47284. transparent.length = 0;
  47285. }
  47286. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47287. let renderItem = renderItems[ renderItemsIndex ];
  47288. if ( renderItem === undefined ) {
  47289. renderItem = {
  47290. id: object.id,
  47291. object: object,
  47292. geometry: geometry,
  47293. material: material,
  47294. groupOrder: groupOrder,
  47295. renderOrder: object.renderOrder,
  47296. z: z,
  47297. group: group
  47298. };
  47299. renderItems[ renderItemsIndex ] = renderItem;
  47300. } else {
  47301. renderItem.id = object.id;
  47302. renderItem.object = object;
  47303. renderItem.geometry = geometry;
  47304. renderItem.material = material;
  47305. renderItem.groupOrder = groupOrder;
  47306. renderItem.renderOrder = object.renderOrder;
  47307. renderItem.z = z;
  47308. renderItem.group = group;
  47309. }
  47310. renderItemsIndex ++;
  47311. return renderItem;
  47312. }
  47313. function push( object, geometry, material, groupOrder, z, group ) {
  47314. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47315. if ( material.transmission > 0.0 ) {
  47316. transmissive.push( renderItem );
  47317. } else if ( material.transparent === true ) {
  47318. transparent.push( renderItem );
  47319. } else {
  47320. opaque.push( renderItem );
  47321. }
  47322. }
  47323. function unshift( object, geometry, material, groupOrder, z, group ) {
  47324. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47325. if ( material.transmission > 0.0 ) {
  47326. transmissive.unshift( renderItem );
  47327. } else if ( material.transparent === true ) {
  47328. transparent.unshift( renderItem );
  47329. } else {
  47330. opaque.unshift( renderItem );
  47331. }
  47332. }
  47333. function sort( customOpaqueSort, customTransparentSort ) {
  47334. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47335. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47336. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47337. }
  47338. function finish() {
  47339. // Clear references from inactive renderItems in the list
  47340. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47341. const renderItem = renderItems[ i ];
  47342. if ( renderItem.id === null ) break;
  47343. renderItem.id = null;
  47344. renderItem.object = null;
  47345. renderItem.geometry = null;
  47346. renderItem.material = null;
  47347. renderItem.group = null;
  47348. }
  47349. }
  47350. return {
  47351. opaque: opaque,
  47352. transmissive: transmissive,
  47353. transparent: transparent,
  47354. init: init,
  47355. push: push,
  47356. unshift: unshift,
  47357. finish: finish,
  47358. sort: sort
  47359. };
  47360. }
  47361. function WebGLRenderLists() {
  47362. let lists = new WeakMap();
  47363. function get( scene, renderCallDepth ) {
  47364. const listArray = lists.get( scene );
  47365. let list;
  47366. if ( listArray === undefined ) {
  47367. list = new WebGLRenderList();
  47368. lists.set( scene, [ list ] );
  47369. } else {
  47370. if ( renderCallDepth >= listArray.length ) {
  47371. list = new WebGLRenderList();
  47372. listArray.push( list );
  47373. } else {
  47374. list = listArray[ renderCallDepth ];
  47375. }
  47376. }
  47377. return list;
  47378. }
  47379. function dispose() {
  47380. lists = new WeakMap();
  47381. }
  47382. return {
  47383. get: get,
  47384. dispose: dispose
  47385. };
  47386. }
  47387. function UniformsCache() {
  47388. const lights = {};
  47389. return {
  47390. get: function ( light ) {
  47391. if ( lights[ light.id ] !== undefined ) {
  47392. return lights[ light.id ];
  47393. }
  47394. let uniforms;
  47395. switch ( light.type ) {
  47396. case 'DirectionalLight':
  47397. uniforms = {
  47398. direction: new Vector3(),
  47399. color: new Color()
  47400. };
  47401. break;
  47402. case 'SpotLight':
  47403. uniforms = {
  47404. position: new Vector3(),
  47405. direction: new Vector3(),
  47406. color: new Color(),
  47407. distance: 0,
  47408. coneCos: 0,
  47409. penumbraCos: 0,
  47410. decay: 0
  47411. };
  47412. break;
  47413. case 'PointLight':
  47414. uniforms = {
  47415. position: new Vector3(),
  47416. color: new Color(),
  47417. distance: 0,
  47418. decay: 0
  47419. };
  47420. break;
  47421. case 'HemisphereLight':
  47422. uniforms = {
  47423. direction: new Vector3(),
  47424. skyColor: new Color(),
  47425. groundColor: new Color()
  47426. };
  47427. break;
  47428. case 'RectAreaLight':
  47429. uniforms = {
  47430. color: new Color(),
  47431. position: new Vector3(),
  47432. halfWidth: new Vector3(),
  47433. halfHeight: new Vector3()
  47434. };
  47435. break;
  47436. }
  47437. lights[ light.id ] = uniforms;
  47438. return uniforms;
  47439. }
  47440. };
  47441. }
  47442. function ShadowUniformsCache() {
  47443. const lights = {};
  47444. return {
  47445. get: function ( light ) {
  47446. if ( lights[ light.id ] !== undefined ) {
  47447. return lights[ light.id ];
  47448. }
  47449. let uniforms;
  47450. switch ( light.type ) {
  47451. case 'DirectionalLight':
  47452. uniforms = {
  47453. shadowIntensity: 1,
  47454. shadowBias: 0,
  47455. shadowNormalBias: 0,
  47456. shadowRadius: 1,
  47457. shadowMapSize: new Vector2()
  47458. };
  47459. break;
  47460. case 'SpotLight':
  47461. uniforms = {
  47462. shadowIntensity: 1,
  47463. shadowBias: 0,
  47464. shadowNormalBias: 0,
  47465. shadowRadius: 1,
  47466. shadowMapSize: new Vector2()
  47467. };
  47468. break;
  47469. case 'PointLight':
  47470. uniforms = {
  47471. shadowIntensity: 1,
  47472. shadowBias: 0,
  47473. shadowNormalBias: 0,
  47474. shadowRadius: 1,
  47475. shadowMapSize: new Vector2(),
  47476. shadowCameraNear: 1,
  47477. shadowCameraFar: 1000
  47478. };
  47479. break;
  47480. // TODO (abelnation): set RectAreaLight shadow uniforms
  47481. }
  47482. lights[ light.id ] = uniforms;
  47483. return uniforms;
  47484. }
  47485. };
  47486. }
  47487. let nextVersion = 0;
  47488. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47489. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47490. }
  47491. function WebGLLights( extensions ) {
  47492. const cache = new UniformsCache();
  47493. const shadowCache = ShadowUniformsCache();
  47494. const state = {
  47495. version: 0,
  47496. hash: {
  47497. directionalLength: -1,
  47498. pointLength: -1,
  47499. spotLength: -1,
  47500. rectAreaLength: -1,
  47501. hemiLength: -1,
  47502. numDirectionalShadows: -1,
  47503. numPointShadows: -1,
  47504. numSpotShadows: -1,
  47505. numSpotMaps: -1,
  47506. numLightProbes: -1
  47507. },
  47508. ambient: [ 0, 0, 0 ],
  47509. probe: [],
  47510. directional: [],
  47511. directionalShadow: [],
  47512. directionalShadowMap: [],
  47513. directionalShadowMatrix: [],
  47514. spot: [],
  47515. spotLightMap: [],
  47516. spotShadow: [],
  47517. spotShadowMap: [],
  47518. spotLightMatrix: [],
  47519. rectArea: [],
  47520. rectAreaLTC1: null,
  47521. rectAreaLTC2: null,
  47522. point: [],
  47523. pointShadow: [],
  47524. pointShadowMap: [],
  47525. pointShadowMatrix: [],
  47526. hemi: [],
  47527. numSpotLightShadowsWithMaps: 0,
  47528. numLightProbes: 0
  47529. };
  47530. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47531. const vector3 = new Vector3();
  47532. const matrix4 = new Matrix4();
  47533. const matrix42 = new Matrix4();
  47534. function setup( lights ) {
  47535. let r = 0, g = 0, b = 0;
  47536. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47537. let directionalLength = 0;
  47538. let pointLength = 0;
  47539. let spotLength = 0;
  47540. let rectAreaLength = 0;
  47541. let hemiLength = 0;
  47542. let numDirectionalShadows = 0;
  47543. let numPointShadows = 0;
  47544. let numSpotShadows = 0;
  47545. let numSpotMaps = 0;
  47546. let numSpotShadowsWithMaps = 0;
  47547. let numLightProbes = 0;
  47548. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47549. lights.sort( shadowCastingAndTexturingLightsFirst );
  47550. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47551. const light = lights[ i ];
  47552. const color = light.color;
  47553. const intensity = light.intensity;
  47554. const distance = light.distance;
  47555. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  47556. if ( light.isAmbientLight ) {
  47557. r += color.r * intensity;
  47558. g += color.g * intensity;
  47559. b += color.b * intensity;
  47560. } else if ( light.isLightProbe ) {
  47561. for ( let j = 0; j < 9; j ++ ) {
  47562. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47563. }
  47564. numLightProbes ++;
  47565. } else if ( light.isDirectionalLight ) {
  47566. const uniforms = cache.get( light );
  47567. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47568. if ( light.castShadow ) {
  47569. const shadow = light.shadow;
  47570. const shadowUniforms = shadowCache.get( light );
  47571. shadowUniforms.shadowIntensity = shadow.intensity;
  47572. shadowUniforms.shadowBias = shadow.bias;
  47573. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47574. shadowUniforms.shadowRadius = shadow.radius;
  47575. shadowUniforms.shadowMapSize = shadow.mapSize;
  47576. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47577. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47578. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47579. numDirectionalShadows ++;
  47580. }
  47581. state.directional[ directionalLength ] = uniforms;
  47582. directionalLength ++;
  47583. } else if ( light.isSpotLight ) {
  47584. const uniforms = cache.get( light );
  47585. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47586. uniforms.color.copy( color ).multiplyScalar( intensity );
  47587. uniforms.distance = distance;
  47588. uniforms.coneCos = Math.cos( light.angle );
  47589. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47590. uniforms.decay = light.decay;
  47591. state.spot[ spotLength ] = uniforms;
  47592. const shadow = light.shadow;
  47593. if ( light.map ) {
  47594. state.spotLightMap[ numSpotMaps ] = light.map;
  47595. numSpotMaps ++;
  47596. // make sure the lightMatrix is up to date
  47597. // TODO : do it if required only
  47598. shadow.updateMatrices( light );
  47599. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47600. }
  47601. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47602. if ( light.castShadow ) {
  47603. const shadowUniforms = shadowCache.get( light );
  47604. shadowUniforms.shadowIntensity = shadow.intensity;
  47605. shadowUniforms.shadowBias = shadow.bias;
  47606. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47607. shadowUniforms.shadowRadius = shadow.radius;
  47608. shadowUniforms.shadowMapSize = shadow.mapSize;
  47609. state.spotShadow[ spotLength ] = shadowUniforms;
  47610. state.spotShadowMap[ spotLength ] = shadowMap;
  47611. numSpotShadows ++;
  47612. }
  47613. spotLength ++;
  47614. } else if ( light.isRectAreaLight ) {
  47615. const uniforms = cache.get( light );
  47616. uniforms.color.copy( color ).multiplyScalar( intensity );
  47617. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47618. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47619. state.rectArea[ rectAreaLength ] = uniforms;
  47620. rectAreaLength ++;
  47621. } else if ( light.isPointLight ) {
  47622. const uniforms = cache.get( light );
  47623. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47624. uniforms.distance = light.distance;
  47625. uniforms.decay = light.decay;
  47626. if ( light.castShadow ) {
  47627. const shadow = light.shadow;
  47628. const shadowUniforms = shadowCache.get( light );
  47629. shadowUniforms.shadowIntensity = shadow.intensity;
  47630. shadowUniforms.shadowBias = shadow.bias;
  47631. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47632. shadowUniforms.shadowRadius = shadow.radius;
  47633. shadowUniforms.shadowMapSize = shadow.mapSize;
  47634. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47635. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47636. state.pointShadow[ pointLength ] = shadowUniforms;
  47637. state.pointShadowMap[ pointLength ] = shadowMap;
  47638. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47639. numPointShadows ++;
  47640. }
  47641. state.point[ pointLength ] = uniforms;
  47642. pointLength ++;
  47643. } else if ( light.isHemisphereLight ) {
  47644. const uniforms = cache.get( light );
  47645. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47646. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47647. state.hemi[ hemiLength ] = uniforms;
  47648. hemiLength ++;
  47649. }
  47650. }
  47651. if ( rectAreaLength > 0 ) {
  47652. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47653. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47654. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47655. } else {
  47656. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47657. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47658. }
  47659. }
  47660. state.ambient[ 0 ] = r;
  47661. state.ambient[ 1 ] = g;
  47662. state.ambient[ 2 ] = b;
  47663. const hash = state.hash;
  47664. if ( hash.directionalLength !== directionalLength ||
  47665. hash.pointLength !== pointLength ||
  47666. hash.spotLength !== spotLength ||
  47667. hash.rectAreaLength !== rectAreaLength ||
  47668. hash.hemiLength !== hemiLength ||
  47669. hash.numDirectionalShadows !== numDirectionalShadows ||
  47670. hash.numPointShadows !== numPointShadows ||
  47671. hash.numSpotShadows !== numSpotShadows ||
  47672. hash.numSpotMaps !== numSpotMaps ||
  47673. hash.numLightProbes !== numLightProbes ) {
  47674. state.directional.length = directionalLength;
  47675. state.spot.length = spotLength;
  47676. state.rectArea.length = rectAreaLength;
  47677. state.point.length = pointLength;
  47678. state.hemi.length = hemiLength;
  47679. state.directionalShadow.length = numDirectionalShadows;
  47680. state.directionalShadowMap.length = numDirectionalShadows;
  47681. state.pointShadow.length = numPointShadows;
  47682. state.pointShadowMap.length = numPointShadows;
  47683. state.spotShadow.length = numSpotShadows;
  47684. state.spotShadowMap.length = numSpotShadows;
  47685. state.directionalShadowMatrix.length = numDirectionalShadows;
  47686. state.pointShadowMatrix.length = numPointShadows;
  47687. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  47688. state.spotLightMap.length = numSpotMaps;
  47689. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  47690. state.numLightProbes = numLightProbes;
  47691. hash.directionalLength = directionalLength;
  47692. hash.pointLength = pointLength;
  47693. hash.spotLength = spotLength;
  47694. hash.rectAreaLength = rectAreaLength;
  47695. hash.hemiLength = hemiLength;
  47696. hash.numDirectionalShadows = numDirectionalShadows;
  47697. hash.numPointShadows = numPointShadows;
  47698. hash.numSpotShadows = numSpotShadows;
  47699. hash.numSpotMaps = numSpotMaps;
  47700. hash.numLightProbes = numLightProbes;
  47701. state.version = nextVersion ++;
  47702. }
  47703. }
  47704. function setupView( lights, camera ) {
  47705. let directionalLength = 0;
  47706. let pointLength = 0;
  47707. let spotLength = 0;
  47708. let rectAreaLength = 0;
  47709. let hemiLength = 0;
  47710. const viewMatrix = camera.matrixWorldInverse;
  47711. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47712. const light = lights[ i ];
  47713. if ( light.isDirectionalLight ) {
  47714. const uniforms = state.directional[ directionalLength ];
  47715. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47716. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47717. uniforms.direction.sub( vector3 );
  47718. uniforms.direction.transformDirection( viewMatrix );
  47719. directionalLength ++;
  47720. } else if ( light.isSpotLight ) {
  47721. const uniforms = state.spot[ spotLength ];
  47722. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47723. uniforms.position.applyMatrix4( viewMatrix );
  47724. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47725. vector3.setFromMatrixPosition( light.target.matrixWorld );
  47726. uniforms.direction.sub( vector3 );
  47727. uniforms.direction.transformDirection( viewMatrix );
  47728. spotLength ++;
  47729. } else if ( light.isRectAreaLight ) {
  47730. const uniforms = state.rectArea[ rectAreaLength ];
  47731. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47732. uniforms.position.applyMatrix4( viewMatrix );
  47733. // extract local rotation of light to derive width/height half vectors
  47734. matrix42.identity();
  47735. matrix4.copy( light.matrixWorld );
  47736. matrix4.premultiply( viewMatrix );
  47737. matrix42.extractRotation( matrix4 );
  47738. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47739. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47740. uniforms.halfWidth.applyMatrix4( matrix42 );
  47741. uniforms.halfHeight.applyMatrix4( matrix42 );
  47742. rectAreaLength ++;
  47743. } else if ( light.isPointLight ) {
  47744. const uniforms = state.point[ pointLength ];
  47745. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47746. uniforms.position.applyMatrix4( viewMatrix );
  47747. pointLength ++;
  47748. } else if ( light.isHemisphereLight ) {
  47749. const uniforms = state.hemi[ hemiLength ];
  47750. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  47751. uniforms.direction.transformDirection( viewMatrix );
  47752. hemiLength ++;
  47753. }
  47754. }
  47755. }
  47756. return {
  47757. setup: setup,
  47758. setupView: setupView,
  47759. state: state
  47760. };
  47761. }
  47762. function WebGLRenderState( extensions ) {
  47763. const lights = new WebGLLights( extensions );
  47764. const lightsArray = [];
  47765. const shadowsArray = [];
  47766. function init( camera ) {
  47767. state.camera = camera;
  47768. lightsArray.length = 0;
  47769. shadowsArray.length = 0;
  47770. }
  47771. function pushLight( light ) {
  47772. lightsArray.push( light );
  47773. }
  47774. function pushShadow( shadowLight ) {
  47775. shadowsArray.push( shadowLight );
  47776. }
  47777. function setupLights() {
  47778. lights.setup( lightsArray );
  47779. }
  47780. function setupLightsView( camera ) {
  47781. lights.setupView( lightsArray, camera );
  47782. }
  47783. const state = {
  47784. lightsArray: lightsArray,
  47785. shadowsArray: shadowsArray,
  47786. camera: null,
  47787. lights: lights,
  47788. transmissionRenderTarget: {}
  47789. };
  47790. return {
  47791. init: init,
  47792. state: state,
  47793. setupLights: setupLights,
  47794. setupLightsView: setupLightsView,
  47795. pushLight: pushLight,
  47796. pushShadow: pushShadow
  47797. };
  47798. }
  47799. function WebGLRenderStates( extensions ) {
  47800. let renderStates = new WeakMap();
  47801. function get( scene, renderCallDepth = 0 ) {
  47802. const renderStateArray = renderStates.get( scene );
  47803. let renderState;
  47804. if ( renderStateArray === undefined ) {
  47805. renderState = new WebGLRenderState( extensions );
  47806. renderStates.set( scene, [ renderState ] );
  47807. } else {
  47808. if ( renderCallDepth >= renderStateArray.length ) {
  47809. renderState = new WebGLRenderState( extensions );
  47810. renderStateArray.push( renderState );
  47811. } else {
  47812. renderState = renderStateArray[ renderCallDepth ];
  47813. }
  47814. }
  47815. return renderState;
  47816. }
  47817. function dispose() {
  47818. renderStates = new WeakMap();
  47819. }
  47820. return {
  47821. get: get,
  47822. dispose: dispose
  47823. };
  47824. }
  47825. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  47826. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tconst float samples = float( VSM_SAMPLES );\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );\n\tfloat uvStart = samples <= 1.0 ? 0.0 : - 1.0;\n\tfor ( float i = 0.0; i < samples; i ++ ) {\n\t\tfloat uvOffset = uvStart + i * uvStride;\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean / samples;\n\tsquared_mean = squared_mean / samples;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";
  47827. function WebGLShadowMap( renderer, objects, capabilities ) {
  47828. let _frustum = new Frustum();
  47829. const _shadowMapSize = new Vector2(),
  47830. _viewportSize = new Vector2(),
  47831. _viewport = new Vector4(),
  47832. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  47833. _distanceMaterial = new MeshDistanceMaterial(),
  47834. _materialCache = {},
  47835. _maxTextureSize = capabilities.maxTextureSize;
  47836. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  47837. const shadowMaterialVertical = new ShaderMaterial( {
  47838. defines: {
  47839. VSM_SAMPLES: 8
  47840. },
  47841. uniforms: {
  47842. shadow_pass: { value: null },
  47843. resolution: { value: new Vector2() },
  47844. radius: { value: 4.0 }
  47845. },
  47846. vertexShader: vertex,
  47847. fragmentShader: fragment
  47848. } );
  47849. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  47850. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  47851. const fullScreenTri = new BufferGeometry();
  47852. fullScreenTri.setAttribute(
  47853. 'position',
  47854. new BufferAttribute(
  47855. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  47856. 3
  47857. )
  47858. );
  47859. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  47860. const scope = this;
  47861. this.enabled = false;
  47862. this.autoUpdate = true;
  47863. this.needsUpdate = false;
  47864. this.type = PCFShadowMap;
  47865. let _previousType = this.type;
  47866. this.render = function ( lights, scene, camera ) {
  47867. if ( scope.enabled === false ) return;
  47868. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  47869. if ( lights.length === 0 ) return;
  47870. const currentRenderTarget = renderer.getRenderTarget();
  47871. const activeCubeFace = renderer.getActiveCubeFace();
  47872. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  47873. const _state = renderer.state;
  47874. // Set GL state for depth map.
  47875. _state.setBlending( NoBlending );
  47876. if ( _state.buffers.depth.getReversed() === true ) {
  47877. _state.buffers.color.setClear( 0, 0, 0, 0 );
  47878. } else {
  47879. _state.buffers.color.setClear( 1, 1, 1, 1 );
  47880. }
  47881. _state.buffers.depth.setTest( true );
  47882. _state.setScissorTest( false );
  47883. // check for shadow map type changes
  47884. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  47885. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  47886. // render depth map
  47887. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  47888. const light = lights[ i ];
  47889. const shadow = light.shadow;
  47890. if ( shadow === undefined ) {
  47891. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  47892. continue;
  47893. }
  47894. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  47895. _shadowMapSize.copy( shadow.mapSize );
  47896. const shadowFrameExtents = shadow.getFrameExtents();
  47897. _shadowMapSize.multiply( shadowFrameExtents );
  47898. _viewportSize.copy( shadow.mapSize );
  47899. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  47900. if ( _shadowMapSize.x > _maxTextureSize ) {
  47901. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  47902. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  47903. shadow.mapSize.x = _viewportSize.x;
  47904. }
  47905. if ( _shadowMapSize.y > _maxTextureSize ) {
  47906. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  47907. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  47908. shadow.mapSize.y = _viewportSize.y;
  47909. }
  47910. }
  47911. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  47912. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  47913. if ( shadow.map !== null ) {
  47914. shadow.map.dispose();
  47915. }
  47916. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  47917. shadow.map.texture.name = light.name + '.shadowMap';
  47918. shadow.camera.updateProjectionMatrix();
  47919. }
  47920. renderer.setRenderTarget( shadow.map );
  47921. renderer.clear();
  47922. const viewportCount = shadow.getViewportCount();
  47923. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  47924. const viewport = shadow.getViewport( vp );
  47925. _viewport.set(
  47926. _viewportSize.x * viewport.x,
  47927. _viewportSize.y * viewport.y,
  47928. _viewportSize.x * viewport.z,
  47929. _viewportSize.y * viewport.w
  47930. );
  47931. _state.viewport( _viewport );
  47932. shadow.updateMatrices( light, vp );
  47933. _frustum = shadow.getFrustum();
  47934. renderObject( scene, camera, shadow.camera, light, this.type );
  47935. }
  47936. // do blur pass for VSM
  47937. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  47938. VSMPass( shadow, camera );
  47939. }
  47940. shadow.needsUpdate = false;
  47941. }
  47942. _previousType = this.type;
  47943. scope.needsUpdate = false;
  47944. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  47945. };
  47946. function VSMPass( shadow, camera ) {
  47947. const geometry = objects.update( fullScreenMesh );
  47948. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  47949. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  47950. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  47951. shadowMaterialVertical.needsUpdate = true;
  47952. shadowMaterialHorizontal.needsUpdate = true;
  47953. }
  47954. if ( shadow.mapPass === null ) {
  47955. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  47956. }
  47957. // vertical pass
  47958. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  47959. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  47960. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  47961. renderer.setRenderTarget( shadow.mapPass );
  47962. renderer.clear();
  47963. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  47964. // horizontal pass
  47965. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  47966. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  47967. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  47968. renderer.setRenderTarget( shadow.map );
  47969. renderer.clear();
  47970. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  47971. }
  47972. function getDepthMaterial( object, material, light, type ) {
  47973. let result = null;
  47974. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  47975. if ( customMaterial !== undefined ) {
  47976. result = customMaterial;
  47977. } else {
  47978. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  47979. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  47980. ( material.displacementMap && material.displacementScale !== 0 ) ||
  47981. ( material.alphaMap && material.alphaTest > 0 ) ||
  47982. ( material.map && material.alphaTest > 0 ) ||
  47983. ( material.alphaToCoverage === true ) ) {
  47984. // in this case we need a unique material instance reflecting the
  47985. // appropriate state
  47986. const keyA = result.uuid, keyB = material.uuid;
  47987. let materialsForVariant = _materialCache[ keyA ];
  47988. if ( materialsForVariant === undefined ) {
  47989. materialsForVariant = {};
  47990. _materialCache[ keyA ] = materialsForVariant;
  47991. }
  47992. let cachedMaterial = materialsForVariant[ keyB ];
  47993. if ( cachedMaterial === undefined ) {
  47994. cachedMaterial = result.clone();
  47995. materialsForVariant[ keyB ] = cachedMaterial;
  47996. material.addEventListener( 'dispose', onMaterialDispose );
  47997. }
  47998. result = cachedMaterial;
  47999. }
  48000. }
  48001. result.visible = material.visible;
  48002. result.wireframe = material.wireframe;
  48003. if ( type === VSMShadowMap ) {
  48004. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48005. } else {
  48006. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48007. }
  48008. result.alphaMap = material.alphaMap;
  48009. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48010. result.map = material.map;
  48011. result.clipShadows = material.clipShadows;
  48012. result.clippingPlanes = material.clippingPlanes;
  48013. result.clipIntersection = material.clipIntersection;
  48014. result.displacementMap = material.displacementMap;
  48015. result.displacementScale = material.displacementScale;
  48016. result.displacementBias = material.displacementBias;
  48017. result.wireframeLinewidth = material.wireframeLinewidth;
  48018. result.linewidth = material.linewidth;
  48019. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48020. const materialProperties = renderer.properties.get( result );
  48021. materialProperties.light = light;
  48022. }
  48023. return result;
  48024. }
  48025. function renderObject( object, camera, shadowCamera, light, type ) {
  48026. if ( object.visible === false ) return;
  48027. const visible = object.layers.test( camera.layers );
  48028. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48029. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48030. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48031. const geometry = objects.update( object );
  48032. const material = object.material;
  48033. if ( Array.isArray( material ) ) {
  48034. const groups = geometry.groups;
  48035. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48036. const group = groups[ k ];
  48037. const groupMaterial = material[ group.materialIndex ];
  48038. if ( groupMaterial && groupMaterial.visible ) {
  48039. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48040. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48041. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48042. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48043. }
  48044. }
  48045. } else if ( material.visible ) {
  48046. const depthMaterial = getDepthMaterial( object, material, light, type );
  48047. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48048. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48049. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48050. }
  48051. }
  48052. }
  48053. const children = object.children;
  48054. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48055. renderObject( children[ i ], camera, shadowCamera, light, type );
  48056. }
  48057. }
  48058. function onMaterialDispose( event ) {
  48059. const material = event.target;
  48060. material.removeEventListener( 'dispose', onMaterialDispose );
  48061. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48062. for ( const id in _materialCache ) {
  48063. const cache = _materialCache[ id ];
  48064. const uuid = event.target.uuid;
  48065. if ( uuid in cache ) {
  48066. const shadowMaterial = cache[ uuid ];
  48067. shadowMaterial.dispose();
  48068. delete cache[ uuid ];
  48069. }
  48070. }
  48071. }
  48072. }
  48073. const reversedFuncs = {
  48074. [ NeverDepth ]: AlwaysDepth,
  48075. [ LessDepth ]: GreaterDepth,
  48076. [ EqualDepth ]: NotEqualDepth,
  48077. [ LessEqualDepth ]: GreaterEqualDepth,
  48078. [ AlwaysDepth ]: NeverDepth,
  48079. [ GreaterDepth ]: LessDepth,
  48080. [ NotEqualDepth ]: EqualDepth,
  48081. [ GreaterEqualDepth ]: LessEqualDepth,
  48082. };
  48083. function WebGLState( gl, extensions ) {
  48084. function ColorBuffer() {
  48085. let locked = false;
  48086. const color = new Vector4();
  48087. let currentColorMask = null;
  48088. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48089. return {
  48090. setMask: function ( colorMask ) {
  48091. if ( currentColorMask !== colorMask && ! locked ) {
  48092. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48093. currentColorMask = colorMask;
  48094. }
  48095. },
  48096. setLocked: function ( lock ) {
  48097. locked = lock;
  48098. },
  48099. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48100. if ( premultipliedAlpha === true ) {
  48101. r *= a; g *= a; b *= a;
  48102. }
  48103. color.set( r, g, b, a );
  48104. if ( currentColorClear.equals( color ) === false ) {
  48105. gl.clearColor( r, g, b, a );
  48106. currentColorClear.copy( color );
  48107. }
  48108. },
  48109. reset: function () {
  48110. locked = false;
  48111. currentColorMask = null;
  48112. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48113. }
  48114. };
  48115. }
  48116. function DepthBuffer() {
  48117. let locked = false;
  48118. let currentReversed = false;
  48119. let currentDepthMask = null;
  48120. let currentDepthFunc = null;
  48121. let currentDepthClear = null;
  48122. return {
  48123. setReversed: function ( reversed ) {
  48124. if ( currentReversed !== reversed ) {
  48125. const ext = extensions.get( 'EXT_clip_control' );
  48126. if ( reversed ) {
  48127. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48128. } else {
  48129. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48130. }
  48131. currentReversed = reversed;
  48132. const oldDepth = currentDepthClear;
  48133. currentDepthClear = null;
  48134. this.setClear( oldDepth );
  48135. }
  48136. },
  48137. getReversed: function () {
  48138. return currentReversed;
  48139. },
  48140. setTest: function ( depthTest ) {
  48141. if ( depthTest ) {
  48142. enable( gl.DEPTH_TEST );
  48143. } else {
  48144. disable( gl.DEPTH_TEST );
  48145. }
  48146. },
  48147. setMask: function ( depthMask ) {
  48148. if ( currentDepthMask !== depthMask && ! locked ) {
  48149. gl.depthMask( depthMask );
  48150. currentDepthMask = depthMask;
  48151. }
  48152. },
  48153. setFunc: function ( depthFunc ) {
  48154. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48155. if ( currentDepthFunc !== depthFunc ) {
  48156. switch ( depthFunc ) {
  48157. case NeverDepth:
  48158. gl.depthFunc( gl.NEVER );
  48159. break;
  48160. case AlwaysDepth:
  48161. gl.depthFunc( gl.ALWAYS );
  48162. break;
  48163. case LessDepth:
  48164. gl.depthFunc( gl.LESS );
  48165. break;
  48166. case LessEqualDepth:
  48167. gl.depthFunc( gl.LEQUAL );
  48168. break;
  48169. case EqualDepth:
  48170. gl.depthFunc( gl.EQUAL );
  48171. break;
  48172. case GreaterEqualDepth:
  48173. gl.depthFunc( gl.GEQUAL );
  48174. break;
  48175. case GreaterDepth:
  48176. gl.depthFunc( gl.GREATER );
  48177. break;
  48178. case NotEqualDepth:
  48179. gl.depthFunc( gl.NOTEQUAL );
  48180. break;
  48181. default:
  48182. gl.depthFunc( gl.LEQUAL );
  48183. }
  48184. currentDepthFunc = depthFunc;
  48185. }
  48186. },
  48187. setLocked: function ( lock ) {
  48188. locked = lock;
  48189. },
  48190. setClear: function ( depth ) {
  48191. if ( currentDepthClear !== depth ) {
  48192. if ( currentReversed ) {
  48193. depth = 1 - depth;
  48194. }
  48195. gl.clearDepth( depth );
  48196. currentDepthClear = depth;
  48197. }
  48198. },
  48199. reset: function () {
  48200. locked = false;
  48201. currentDepthMask = null;
  48202. currentDepthFunc = null;
  48203. currentDepthClear = null;
  48204. currentReversed = false;
  48205. }
  48206. };
  48207. }
  48208. function StencilBuffer() {
  48209. let locked = false;
  48210. let currentStencilMask = null;
  48211. let currentStencilFunc = null;
  48212. let currentStencilRef = null;
  48213. let currentStencilFuncMask = null;
  48214. let currentStencilFail = null;
  48215. let currentStencilZFail = null;
  48216. let currentStencilZPass = null;
  48217. let currentStencilClear = null;
  48218. return {
  48219. setTest: function ( stencilTest ) {
  48220. if ( ! locked ) {
  48221. if ( stencilTest ) {
  48222. enable( gl.STENCIL_TEST );
  48223. } else {
  48224. disable( gl.STENCIL_TEST );
  48225. }
  48226. }
  48227. },
  48228. setMask: function ( stencilMask ) {
  48229. if ( currentStencilMask !== stencilMask && ! locked ) {
  48230. gl.stencilMask( stencilMask );
  48231. currentStencilMask = stencilMask;
  48232. }
  48233. },
  48234. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48235. if ( currentStencilFunc !== stencilFunc ||
  48236. currentStencilRef !== stencilRef ||
  48237. currentStencilFuncMask !== stencilMask ) {
  48238. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48239. currentStencilFunc = stencilFunc;
  48240. currentStencilRef = stencilRef;
  48241. currentStencilFuncMask = stencilMask;
  48242. }
  48243. },
  48244. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48245. if ( currentStencilFail !== stencilFail ||
  48246. currentStencilZFail !== stencilZFail ||
  48247. currentStencilZPass !== stencilZPass ) {
  48248. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48249. currentStencilFail = stencilFail;
  48250. currentStencilZFail = stencilZFail;
  48251. currentStencilZPass = stencilZPass;
  48252. }
  48253. },
  48254. setLocked: function ( lock ) {
  48255. locked = lock;
  48256. },
  48257. setClear: function ( stencil ) {
  48258. if ( currentStencilClear !== stencil ) {
  48259. gl.clearStencil( stencil );
  48260. currentStencilClear = stencil;
  48261. }
  48262. },
  48263. reset: function () {
  48264. locked = false;
  48265. currentStencilMask = null;
  48266. currentStencilFunc = null;
  48267. currentStencilRef = null;
  48268. currentStencilFuncMask = null;
  48269. currentStencilFail = null;
  48270. currentStencilZFail = null;
  48271. currentStencilZPass = null;
  48272. currentStencilClear = null;
  48273. }
  48274. };
  48275. }
  48276. //
  48277. const colorBuffer = new ColorBuffer();
  48278. const depthBuffer = new DepthBuffer();
  48279. const stencilBuffer = new StencilBuffer();
  48280. const uboBindings = new WeakMap();
  48281. const uboProgramMap = new WeakMap();
  48282. let enabledCapabilities = {};
  48283. let currentBoundFramebuffers = {};
  48284. let currentDrawbuffers = new WeakMap();
  48285. let defaultDrawbuffers = [];
  48286. let currentProgram = null;
  48287. let currentBlendingEnabled = false;
  48288. let currentBlending = null;
  48289. let currentBlendEquation = null;
  48290. let currentBlendSrc = null;
  48291. let currentBlendDst = null;
  48292. let currentBlendEquationAlpha = null;
  48293. let currentBlendSrcAlpha = null;
  48294. let currentBlendDstAlpha = null;
  48295. let currentBlendColor = new Color( 0, 0, 0 );
  48296. let currentBlendAlpha = 0;
  48297. let currentPremultipledAlpha = false;
  48298. let currentFlipSided = null;
  48299. let currentCullFace = null;
  48300. let currentLineWidth = null;
  48301. let currentPolygonOffsetFactor = null;
  48302. let currentPolygonOffsetUnits = null;
  48303. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48304. let lineWidthAvailable = false;
  48305. let version = 0;
  48306. const glVersion = gl.getParameter( gl.VERSION );
  48307. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48308. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48309. lineWidthAvailable = ( version >= 1.0 );
  48310. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48311. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48312. lineWidthAvailable = ( version >= 2.0 );
  48313. }
  48314. let currentTextureSlot = null;
  48315. let currentBoundTextures = {};
  48316. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48317. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48318. const currentScissor = new Vector4().fromArray( scissorParam );
  48319. const currentViewport = new Vector4().fromArray( viewportParam );
  48320. function createTexture( type, target, count, dimensions ) {
  48321. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48322. const texture = gl.createTexture();
  48323. gl.bindTexture( type, texture );
  48324. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48325. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48326. for ( let i = 0; i < count; i ++ ) {
  48327. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48328. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48329. } else {
  48330. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48331. }
  48332. }
  48333. return texture;
  48334. }
  48335. const emptyTextures = {};
  48336. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48337. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48338. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48339. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48340. // init
  48341. colorBuffer.setClear( 0, 0, 0, 1 );
  48342. depthBuffer.setClear( 1 );
  48343. stencilBuffer.setClear( 0 );
  48344. enable( gl.DEPTH_TEST );
  48345. depthBuffer.setFunc( LessEqualDepth );
  48346. setFlipSided( false );
  48347. setCullFace( CullFaceBack );
  48348. enable( gl.CULL_FACE );
  48349. setBlending( NoBlending );
  48350. //
  48351. function enable( id ) {
  48352. if ( enabledCapabilities[ id ] !== true ) {
  48353. gl.enable( id );
  48354. enabledCapabilities[ id ] = true;
  48355. }
  48356. }
  48357. function disable( id ) {
  48358. if ( enabledCapabilities[ id ] !== false ) {
  48359. gl.disable( id );
  48360. enabledCapabilities[ id ] = false;
  48361. }
  48362. }
  48363. function bindFramebuffer( target, framebuffer ) {
  48364. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48365. gl.bindFramebuffer( target, framebuffer );
  48366. currentBoundFramebuffers[ target ] = framebuffer;
  48367. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48368. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48369. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48370. }
  48371. if ( target === gl.FRAMEBUFFER ) {
  48372. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48373. }
  48374. return true;
  48375. }
  48376. return false;
  48377. }
  48378. function drawBuffers( renderTarget, framebuffer ) {
  48379. let drawBuffers = defaultDrawbuffers;
  48380. let needsUpdate = false;
  48381. if ( renderTarget ) {
  48382. drawBuffers = currentDrawbuffers.get( framebuffer );
  48383. if ( drawBuffers === undefined ) {
  48384. drawBuffers = [];
  48385. currentDrawbuffers.set( framebuffer, drawBuffers );
  48386. }
  48387. const textures = renderTarget.textures;
  48388. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48389. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48390. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48391. }
  48392. drawBuffers.length = textures.length;
  48393. needsUpdate = true;
  48394. }
  48395. } else {
  48396. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48397. drawBuffers[ 0 ] = gl.BACK;
  48398. needsUpdate = true;
  48399. }
  48400. }
  48401. if ( needsUpdate ) {
  48402. gl.drawBuffers( drawBuffers );
  48403. }
  48404. }
  48405. function useProgram( program ) {
  48406. if ( currentProgram !== program ) {
  48407. gl.useProgram( program );
  48408. currentProgram = program;
  48409. return true;
  48410. }
  48411. return false;
  48412. }
  48413. const equationToGL = {
  48414. [ AddEquation ]: gl.FUNC_ADD,
  48415. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48416. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48417. };
  48418. equationToGL[ MinEquation ] = gl.MIN;
  48419. equationToGL[ MaxEquation ] = gl.MAX;
  48420. const factorToGL = {
  48421. [ ZeroFactor ]: gl.ZERO,
  48422. [ OneFactor ]: gl.ONE,
  48423. [ SrcColorFactor ]: gl.SRC_COLOR,
  48424. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48425. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48426. [ DstColorFactor ]: gl.DST_COLOR,
  48427. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48428. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48429. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48430. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48431. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48432. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48433. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48434. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48435. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48436. };
  48437. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48438. if ( blending === NoBlending ) {
  48439. if ( currentBlendingEnabled === true ) {
  48440. disable( gl.BLEND );
  48441. currentBlendingEnabled = false;
  48442. }
  48443. return;
  48444. }
  48445. if ( currentBlendingEnabled === false ) {
  48446. enable( gl.BLEND );
  48447. currentBlendingEnabled = true;
  48448. }
  48449. if ( blending !== CustomBlending ) {
  48450. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  48451. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  48452. gl.blendEquation( gl.FUNC_ADD );
  48453. currentBlendEquation = AddEquation;
  48454. currentBlendEquationAlpha = AddEquation;
  48455. }
  48456. if ( premultipliedAlpha ) {
  48457. switch ( blending ) {
  48458. case NormalBlending:
  48459. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48460. break;
  48461. case AdditiveBlending:
  48462. gl.blendFunc( gl.ONE, gl.ONE );
  48463. break;
  48464. case SubtractiveBlending:
  48465. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48466. break;
  48467. case MultiplyBlending:
  48468. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48469. break;
  48470. default:
  48471. error( 'WebGLState: Invalid blending: ', blending );
  48472. break;
  48473. }
  48474. } else {
  48475. switch ( blending ) {
  48476. case NormalBlending:
  48477. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48478. break;
  48479. case AdditiveBlending:
  48480. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48481. break;
  48482. case SubtractiveBlending:
  48483. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48484. break;
  48485. case MultiplyBlending:
  48486. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48487. break;
  48488. default:
  48489. error( 'WebGLState: Invalid blending: ', blending );
  48490. break;
  48491. }
  48492. }
  48493. currentBlendSrc = null;
  48494. currentBlendDst = null;
  48495. currentBlendSrcAlpha = null;
  48496. currentBlendDstAlpha = null;
  48497. currentBlendColor.set( 0, 0, 0 );
  48498. currentBlendAlpha = 0;
  48499. currentBlending = blending;
  48500. currentPremultipledAlpha = premultipliedAlpha;
  48501. }
  48502. return;
  48503. }
  48504. // custom blending
  48505. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48506. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48507. blendDstAlpha = blendDstAlpha || blendDst;
  48508. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  48509. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48510. currentBlendEquation = blendEquation;
  48511. currentBlendEquationAlpha = blendEquationAlpha;
  48512. }
  48513. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  48514. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48515. currentBlendSrc = blendSrc;
  48516. currentBlendDst = blendDst;
  48517. currentBlendSrcAlpha = blendSrcAlpha;
  48518. currentBlendDstAlpha = blendDstAlpha;
  48519. }
  48520. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  48521. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  48522. currentBlendColor.copy( blendColor );
  48523. currentBlendAlpha = blendAlpha;
  48524. }
  48525. currentBlending = blending;
  48526. currentPremultipledAlpha = false;
  48527. }
  48528. function setMaterial( material, frontFaceCW ) {
  48529. material.side === DoubleSide
  48530. ? disable( gl.CULL_FACE )
  48531. : enable( gl.CULL_FACE );
  48532. let flipSided = ( material.side === BackSide );
  48533. if ( frontFaceCW ) flipSided = ! flipSided;
  48534. setFlipSided( flipSided );
  48535. ( material.blending === NormalBlending && material.transparent === false )
  48536. ? setBlending( NoBlending )
  48537. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  48538. depthBuffer.setFunc( material.depthFunc );
  48539. depthBuffer.setTest( material.depthTest );
  48540. depthBuffer.setMask( material.depthWrite );
  48541. colorBuffer.setMask( material.colorWrite );
  48542. const stencilWrite = material.stencilWrite;
  48543. stencilBuffer.setTest( stencilWrite );
  48544. if ( stencilWrite ) {
  48545. stencilBuffer.setMask( material.stencilWriteMask );
  48546. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48547. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48548. }
  48549. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48550. material.alphaToCoverage === true
  48551. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48552. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48553. }
  48554. //
  48555. function setFlipSided( flipSided ) {
  48556. if ( currentFlipSided !== flipSided ) {
  48557. if ( flipSided ) {
  48558. gl.frontFace( gl.CW );
  48559. } else {
  48560. gl.frontFace( gl.CCW );
  48561. }
  48562. currentFlipSided = flipSided;
  48563. }
  48564. }
  48565. function setCullFace( cullFace ) {
  48566. if ( cullFace !== CullFaceNone ) {
  48567. enable( gl.CULL_FACE );
  48568. if ( cullFace !== currentCullFace ) {
  48569. if ( cullFace === CullFaceBack ) {
  48570. gl.cullFace( gl.BACK );
  48571. } else if ( cullFace === CullFaceFront ) {
  48572. gl.cullFace( gl.FRONT );
  48573. } else {
  48574. gl.cullFace( gl.FRONT_AND_BACK );
  48575. }
  48576. }
  48577. } else {
  48578. disable( gl.CULL_FACE );
  48579. }
  48580. currentCullFace = cullFace;
  48581. }
  48582. function setLineWidth( width ) {
  48583. if ( width !== currentLineWidth ) {
  48584. if ( lineWidthAvailable ) gl.lineWidth( width );
  48585. currentLineWidth = width;
  48586. }
  48587. }
  48588. function setPolygonOffset( polygonOffset, factor, units ) {
  48589. if ( polygonOffset ) {
  48590. enable( gl.POLYGON_OFFSET_FILL );
  48591. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48592. gl.polygonOffset( factor, units );
  48593. currentPolygonOffsetFactor = factor;
  48594. currentPolygonOffsetUnits = units;
  48595. }
  48596. } else {
  48597. disable( gl.POLYGON_OFFSET_FILL );
  48598. }
  48599. }
  48600. function setScissorTest( scissorTest ) {
  48601. if ( scissorTest ) {
  48602. enable( gl.SCISSOR_TEST );
  48603. } else {
  48604. disable( gl.SCISSOR_TEST );
  48605. }
  48606. }
  48607. // texture
  48608. function activeTexture( webglSlot ) {
  48609. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48610. if ( currentTextureSlot !== webglSlot ) {
  48611. gl.activeTexture( webglSlot );
  48612. currentTextureSlot = webglSlot;
  48613. }
  48614. }
  48615. function bindTexture( webglType, webglTexture, webglSlot ) {
  48616. if ( webglSlot === undefined ) {
  48617. if ( currentTextureSlot === null ) {
  48618. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  48619. } else {
  48620. webglSlot = currentTextureSlot;
  48621. }
  48622. }
  48623. let boundTexture = currentBoundTextures[ webglSlot ];
  48624. if ( boundTexture === undefined ) {
  48625. boundTexture = { type: undefined, texture: undefined };
  48626. currentBoundTextures[ webglSlot ] = boundTexture;
  48627. }
  48628. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  48629. if ( currentTextureSlot !== webglSlot ) {
  48630. gl.activeTexture( webglSlot );
  48631. currentTextureSlot = webglSlot;
  48632. }
  48633. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  48634. boundTexture.type = webglType;
  48635. boundTexture.texture = webglTexture;
  48636. }
  48637. }
  48638. function unbindTexture() {
  48639. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  48640. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  48641. gl.bindTexture( boundTexture.type, null );
  48642. boundTexture.type = undefined;
  48643. boundTexture.texture = undefined;
  48644. }
  48645. }
  48646. function compressedTexImage2D() {
  48647. try {
  48648. gl.compressedTexImage2D( ...arguments );
  48649. } catch ( error ) {
  48650. error( 'WebGLState:', error );
  48651. }
  48652. }
  48653. function compressedTexImage3D() {
  48654. try {
  48655. gl.compressedTexImage3D( ...arguments );
  48656. } catch ( error ) {
  48657. error( 'WebGLState:', error );
  48658. }
  48659. }
  48660. function texSubImage2D() {
  48661. try {
  48662. gl.texSubImage2D( ...arguments );
  48663. } catch ( error ) {
  48664. error( 'WebGLState:', error );
  48665. }
  48666. }
  48667. function texSubImage3D() {
  48668. try {
  48669. gl.texSubImage3D( ...arguments );
  48670. } catch ( error ) {
  48671. error( 'WebGLState:', error );
  48672. }
  48673. }
  48674. function compressedTexSubImage2D() {
  48675. try {
  48676. gl.compressedTexSubImage2D( ...arguments );
  48677. } catch ( error ) {
  48678. error( 'WebGLState:', error );
  48679. }
  48680. }
  48681. function compressedTexSubImage3D() {
  48682. try {
  48683. gl.compressedTexSubImage3D( ...arguments );
  48684. } catch ( error ) {
  48685. error( 'WebGLState:', error );
  48686. }
  48687. }
  48688. function texStorage2D() {
  48689. try {
  48690. gl.texStorage2D( ...arguments );
  48691. } catch ( error ) {
  48692. error( 'WebGLState:', error );
  48693. }
  48694. }
  48695. function texStorage3D() {
  48696. try {
  48697. gl.texStorage3D( ...arguments );
  48698. } catch ( error ) {
  48699. error( 'WebGLState:', error );
  48700. }
  48701. }
  48702. function texImage2D() {
  48703. try {
  48704. gl.texImage2D( ...arguments );
  48705. } catch ( error ) {
  48706. error( 'WebGLState:', error );
  48707. }
  48708. }
  48709. function texImage3D() {
  48710. try {
  48711. gl.texImage3D( ...arguments );
  48712. } catch ( error ) {
  48713. error( 'WebGLState:', error );
  48714. }
  48715. }
  48716. //
  48717. function scissor( scissor ) {
  48718. if ( currentScissor.equals( scissor ) === false ) {
  48719. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  48720. currentScissor.copy( scissor );
  48721. }
  48722. }
  48723. function viewport( viewport ) {
  48724. if ( currentViewport.equals( viewport ) === false ) {
  48725. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  48726. currentViewport.copy( viewport );
  48727. }
  48728. }
  48729. function updateUBOMapping( uniformsGroup, program ) {
  48730. let mapping = uboProgramMap.get( program );
  48731. if ( mapping === undefined ) {
  48732. mapping = new WeakMap();
  48733. uboProgramMap.set( program, mapping );
  48734. }
  48735. let blockIndex = mapping.get( uniformsGroup );
  48736. if ( blockIndex === undefined ) {
  48737. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  48738. mapping.set( uniformsGroup, blockIndex );
  48739. }
  48740. }
  48741. function uniformBlockBinding( uniformsGroup, program ) {
  48742. const mapping = uboProgramMap.get( program );
  48743. const blockIndex = mapping.get( uniformsGroup );
  48744. if ( uboBindings.get( program ) !== blockIndex ) {
  48745. // bind shader specific block index to global block point
  48746. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  48747. uboBindings.set( program, blockIndex );
  48748. }
  48749. }
  48750. //
  48751. function reset() {
  48752. // reset state
  48753. gl.disable( gl.BLEND );
  48754. gl.disable( gl.CULL_FACE );
  48755. gl.disable( gl.DEPTH_TEST );
  48756. gl.disable( gl.POLYGON_OFFSET_FILL );
  48757. gl.disable( gl.SCISSOR_TEST );
  48758. gl.disable( gl.STENCIL_TEST );
  48759. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48760. gl.blendEquation( gl.FUNC_ADD );
  48761. gl.blendFunc( gl.ONE, gl.ZERO );
  48762. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  48763. gl.blendColor( 0, 0, 0, 0 );
  48764. gl.colorMask( true, true, true, true );
  48765. gl.clearColor( 0, 0, 0, 0 );
  48766. gl.depthMask( true );
  48767. gl.depthFunc( gl.LESS );
  48768. depthBuffer.setReversed( false );
  48769. gl.clearDepth( 1 );
  48770. gl.stencilMask( 0xffffffff );
  48771. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  48772. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  48773. gl.clearStencil( 0 );
  48774. gl.cullFace( gl.BACK );
  48775. gl.frontFace( gl.CCW );
  48776. gl.polygonOffset( 0, 0 );
  48777. gl.activeTexture( gl.TEXTURE0 );
  48778. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  48779. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  48780. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  48781. gl.useProgram( null );
  48782. gl.lineWidth( 1 );
  48783. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  48784. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  48785. // reset internals
  48786. enabledCapabilities = {};
  48787. currentTextureSlot = null;
  48788. currentBoundTextures = {};
  48789. currentBoundFramebuffers = {};
  48790. currentDrawbuffers = new WeakMap();
  48791. defaultDrawbuffers = [];
  48792. currentProgram = null;
  48793. currentBlendingEnabled = false;
  48794. currentBlending = null;
  48795. currentBlendEquation = null;
  48796. currentBlendSrc = null;
  48797. currentBlendDst = null;
  48798. currentBlendEquationAlpha = null;
  48799. currentBlendSrcAlpha = null;
  48800. currentBlendDstAlpha = null;
  48801. currentBlendColor = new Color( 0, 0, 0 );
  48802. currentBlendAlpha = 0;
  48803. currentPremultipledAlpha = false;
  48804. currentFlipSided = null;
  48805. currentCullFace = null;
  48806. currentLineWidth = null;
  48807. currentPolygonOffsetFactor = null;
  48808. currentPolygonOffsetUnits = null;
  48809. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48810. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  48811. colorBuffer.reset();
  48812. depthBuffer.reset();
  48813. stencilBuffer.reset();
  48814. }
  48815. return {
  48816. buffers: {
  48817. color: colorBuffer,
  48818. depth: depthBuffer,
  48819. stencil: stencilBuffer
  48820. },
  48821. enable: enable,
  48822. disable: disable,
  48823. bindFramebuffer: bindFramebuffer,
  48824. drawBuffers: drawBuffers,
  48825. useProgram: useProgram,
  48826. setBlending: setBlending,
  48827. setMaterial: setMaterial,
  48828. setFlipSided: setFlipSided,
  48829. setCullFace: setCullFace,
  48830. setLineWidth: setLineWidth,
  48831. setPolygonOffset: setPolygonOffset,
  48832. setScissorTest: setScissorTest,
  48833. activeTexture: activeTexture,
  48834. bindTexture: bindTexture,
  48835. unbindTexture: unbindTexture,
  48836. compressedTexImage2D: compressedTexImage2D,
  48837. compressedTexImage3D: compressedTexImage3D,
  48838. texImage2D: texImage2D,
  48839. texImage3D: texImage3D,
  48840. updateUBOMapping: updateUBOMapping,
  48841. uniformBlockBinding: uniformBlockBinding,
  48842. texStorage2D: texStorage2D,
  48843. texStorage3D: texStorage3D,
  48844. texSubImage2D: texSubImage2D,
  48845. texSubImage3D: texSubImage3D,
  48846. compressedTexSubImage2D: compressedTexSubImage2D,
  48847. compressedTexSubImage3D: compressedTexSubImage3D,
  48848. scissor: scissor,
  48849. viewport: viewport,
  48850. reset: reset
  48851. };
  48852. }
  48853. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  48854. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  48855. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  48856. const _imageDimensions = new Vector2();
  48857. const _videoTextures = new WeakMap();
  48858. let _canvas;
  48859. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  48860. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  48861. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  48862. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  48863. let useOffscreenCanvas = false;
  48864. try {
  48865. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  48866. // eslint-disable-next-line compat/compat
  48867. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  48868. } catch ( err ) {
  48869. // Ignore any errors
  48870. }
  48871. function createCanvas( width, height ) {
  48872. // Use OffscreenCanvas when available. Specially needed in web workers
  48873. return useOffscreenCanvas ?
  48874. // eslint-disable-next-line compat/compat
  48875. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  48876. }
  48877. function resizeImage( image, needsNewCanvas, maxSize ) {
  48878. let scale = 1;
  48879. const dimensions = getDimensions( image );
  48880. // handle case if texture exceeds max size
  48881. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  48882. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  48883. }
  48884. // only perform resize if necessary
  48885. if ( scale < 1 ) {
  48886. // only perform resize for certain image types
  48887. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48888. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  48889. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  48890. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  48891. const width = Math.floor( scale * dimensions.width );
  48892. const height = Math.floor( scale * dimensions.height );
  48893. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  48894. // cube textures can't reuse the same canvas
  48895. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  48896. canvas.width = width;
  48897. canvas.height = height;
  48898. const context = canvas.getContext( '2d' );
  48899. context.drawImage( image, 0, 0, width, height );
  48900. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  48901. return canvas;
  48902. } else {
  48903. if ( 'data' in image ) {
  48904. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  48905. }
  48906. return image;
  48907. }
  48908. }
  48909. return image;
  48910. }
  48911. function textureNeedsGenerateMipmaps( texture ) {
  48912. return texture.generateMipmaps;
  48913. }
  48914. function generateMipmap( target ) {
  48915. _gl.generateMipmap( target );
  48916. }
  48917. function getTargetType( texture ) {
  48918. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  48919. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  48920. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  48921. return _gl.TEXTURE_2D;
  48922. }
  48923. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  48924. if ( internalFormatName !== null ) {
  48925. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  48926. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  48927. }
  48928. let internalFormat = glFormat;
  48929. if ( glFormat === _gl.RED ) {
  48930. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  48931. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  48932. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  48933. }
  48934. if ( glFormat === _gl.RED_INTEGER ) {
  48935. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  48936. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  48937. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  48938. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  48939. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  48940. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  48941. }
  48942. if ( glFormat === _gl.RG ) {
  48943. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  48944. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  48945. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  48946. }
  48947. if ( glFormat === _gl.RG_INTEGER ) {
  48948. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  48949. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  48950. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  48951. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  48952. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  48953. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  48954. }
  48955. if ( glFormat === _gl.RGB_INTEGER ) {
  48956. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  48957. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  48958. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  48959. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  48960. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  48961. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  48962. }
  48963. if ( glFormat === _gl.RGBA_INTEGER ) {
  48964. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  48965. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  48966. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  48967. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  48968. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  48969. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  48970. }
  48971. if ( glFormat === _gl.RGB ) {
  48972. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  48973. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  48974. }
  48975. if ( glFormat === _gl.RGBA ) {
  48976. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  48977. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  48978. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  48979. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  48980. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  48981. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  48982. }
  48983. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  48984. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  48985. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  48986. extensions.get( 'EXT_color_buffer_float' );
  48987. }
  48988. return internalFormat;
  48989. }
  48990. function getInternalDepthFormat( useStencil, depthType ) {
  48991. let glInternalFormat;
  48992. if ( useStencil ) {
  48993. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  48994. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48995. } else if ( depthType === FloatType ) {
  48996. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  48997. } else if ( depthType === UnsignedShortType ) {
  48998. glInternalFormat = _gl.DEPTH24_STENCIL8;
  48999. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49000. }
  49001. } else {
  49002. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49003. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49004. } else if ( depthType === FloatType ) {
  49005. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49006. } else if ( depthType === UnsignedShortType ) {
  49007. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49008. }
  49009. }
  49010. return glInternalFormat;
  49011. }
  49012. function getMipLevels( texture, image ) {
  49013. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49014. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49015. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49016. // user-defined mipmaps
  49017. return texture.mipmaps.length;
  49018. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49019. return image.mipmaps.length;
  49020. } else {
  49021. // texture without mipmaps (only base level)
  49022. return 1;
  49023. }
  49024. }
  49025. //
  49026. function onTextureDispose( event ) {
  49027. const texture = event.target;
  49028. texture.removeEventListener( 'dispose', onTextureDispose );
  49029. deallocateTexture( texture );
  49030. if ( texture.isVideoTexture ) {
  49031. _videoTextures.delete( texture );
  49032. }
  49033. }
  49034. function onRenderTargetDispose( event ) {
  49035. const renderTarget = event.target;
  49036. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49037. deallocateRenderTarget( renderTarget );
  49038. }
  49039. //
  49040. function deallocateTexture( texture ) {
  49041. const textureProperties = properties.get( texture );
  49042. if ( textureProperties.__webglInit === undefined ) return;
  49043. // check if it's necessary to remove the WebGLTexture object
  49044. const source = texture.source;
  49045. const webglTextures = _sources.get( source );
  49046. if ( webglTextures ) {
  49047. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49048. webglTexture.usedTimes --;
  49049. // the WebGLTexture object is not used anymore, remove it
  49050. if ( webglTexture.usedTimes === 0 ) {
  49051. deleteTexture( texture );
  49052. }
  49053. // remove the weak map entry if no WebGLTexture uses the source anymore
  49054. if ( Object.keys( webglTextures ).length === 0 ) {
  49055. _sources.delete( source );
  49056. }
  49057. }
  49058. properties.remove( texture );
  49059. }
  49060. function deleteTexture( texture ) {
  49061. const textureProperties = properties.get( texture );
  49062. _gl.deleteTexture( textureProperties.__webglTexture );
  49063. const source = texture.source;
  49064. const webglTextures = _sources.get( source );
  49065. delete webglTextures[ textureProperties.__cacheKey ];
  49066. info.memory.textures --;
  49067. }
  49068. function deallocateRenderTarget( renderTarget ) {
  49069. const renderTargetProperties = properties.get( renderTarget );
  49070. if ( renderTarget.depthTexture ) {
  49071. renderTarget.depthTexture.dispose();
  49072. properties.remove( renderTarget.depthTexture );
  49073. }
  49074. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49075. for ( let i = 0; i < 6; i ++ ) {
  49076. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49077. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49078. } else {
  49079. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49080. }
  49081. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49082. }
  49083. } else {
  49084. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49085. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49086. } else {
  49087. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49088. }
  49089. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49090. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49091. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49092. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49093. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49094. }
  49095. }
  49096. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49097. }
  49098. const textures = renderTarget.textures;
  49099. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49100. const attachmentProperties = properties.get( textures[ i ] );
  49101. if ( attachmentProperties.__webglTexture ) {
  49102. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49103. info.memory.textures --;
  49104. }
  49105. properties.remove( textures[ i ] );
  49106. }
  49107. properties.remove( renderTarget );
  49108. }
  49109. //
  49110. let textureUnits = 0;
  49111. function resetTextureUnits() {
  49112. textureUnits = 0;
  49113. }
  49114. function allocateTextureUnit() {
  49115. const textureUnit = textureUnits;
  49116. if ( textureUnit >= capabilities.maxTextures ) {
  49117. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49118. }
  49119. textureUnits += 1;
  49120. return textureUnit;
  49121. }
  49122. function getTextureCacheKey( texture ) {
  49123. const array = [];
  49124. array.push( texture.wrapS );
  49125. array.push( texture.wrapT );
  49126. array.push( texture.wrapR || 0 );
  49127. array.push( texture.magFilter );
  49128. array.push( texture.minFilter );
  49129. array.push( texture.anisotropy );
  49130. array.push( texture.internalFormat );
  49131. array.push( texture.format );
  49132. array.push( texture.type );
  49133. array.push( texture.generateMipmaps );
  49134. array.push( texture.premultiplyAlpha );
  49135. array.push( texture.flipY );
  49136. array.push( texture.unpackAlignment );
  49137. array.push( texture.colorSpace );
  49138. return array.join();
  49139. }
  49140. //
  49141. function setTexture2D( texture, slot ) {
  49142. const textureProperties = properties.get( texture );
  49143. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49144. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49145. const image = texture.image;
  49146. if ( image === null ) {
  49147. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49148. } else if ( image.complete === false ) {
  49149. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49150. } else {
  49151. uploadTexture( textureProperties, texture, slot );
  49152. return;
  49153. }
  49154. } else if ( texture.isExternalTexture ) {
  49155. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49156. }
  49157. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49158. }
  49159. function setTexture2DArray( texture, slot ) {
  49160. const textureProperties = properties.get( texture );
  49161. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49162. uploadTexture( textureProperties, texture, slot );
  49163. return;
  49164. } else if ( texture.isExternalTexture ) {
  49165. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49166. }
  49167. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49168. }
  49169. function setTexture3D( texture, slot ) {
  49170. const textureProperties = properties.get( texture );
  49171. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49172. uploadTexture( textureProperties, texture, slot );
  49173. return;
  49174. }
  49175. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49176. }
  49177. function setTextureCube( texture, slot ) {
  49178. const textureProperties = properties.get( texture );
  49179. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  49180. uploadCubeTexture( textureProperties, texture, slot );
  49181. return;
  49182. }
  49183. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49184. }
  49185. const wrappingToGL = {
  49186. [ RepeatWrapping ]: _gl.REPEAT,
  49187. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49188. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49189. };
  49190. const filterToGL = {
  49191. [ NearestFilter ]: _gl.NEAREST,
  49192. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49193. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49194. [ LinearFilter ]: _gl.LINEAR,
  49195. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49196. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49197. };
  49198. const compareToGL = {
  49199. [ NeverCompare ]: _gl.NEVER,
  49200. [ AlwaysCompare ]: _gl.ALWAYS,
  49201. [ LessCompare ]: _gl.LESS,
  49202. [ LessEqualCompare ]: _gl.LEQUAL,
  49203. [ EqualCompare ]: _gl.EQUAL,
  49204. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49205. [ GreaterCompare ]: _gl.GREATER,
  49206. [ NotEqualCompare ]: _gl.NOTEQUAL
  49207. };
  49208. function setTextureParameters( textureType, texture ) {
  49209. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49210. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49211. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49212. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49213. }
  49214. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49215. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49216. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49217. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49218. }
  49219. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49220. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49221. if ( texture.compareFunction ) {
  49222. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49223. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49224. }
  49225. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49226. if ( texture.magFilter === NearestFilter ) return;
  49227. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49228. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49229. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49230. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49231. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49232. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49233. }
  49234. }
  49235. }
  49236. function initTexture( textureProperties, texture ) {
  49237. let forceUpload = false;
  49238. if ( textureProperties.__webglInit === undefined ) {
  49239. textureProperties.__webglInit = true;
  49240. texture.addEventListener( 'dispose', onTextureDispose );
  49241. }
  49242. // create Source <-> WebGLTextures mapping if necessary
  49243. const source = texture.source;
  49244. let webglTextures = _sources.get( source );
  49245. if ( webglTextures === undefined ) {
  49246. webglTextures = {};
  49247. _sources.set( source, webglTextures );
  49248. }
  49249. // check if there is already a WebGLTexture object for the given texture parameters
  49250. const textureCacheKey = getTextureCacheKey( texture );
  49251. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49252. // if not, create a new instance of WebGLTexture
  49253. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49254. // create new entry
  49255. webglTextures[ textureCacheKey ] = {
  49256. texture: _gl.createTexture(),
  49257. usedTimes: 0
  49258. };
  49259. info.memory.textures ++;
  49260. // when a new instance of WebGLTexture was created, a texture upload is required
  49261. // even if the image contents are identical
  49262. forceUpload = true;
  49263. }
  49264. webglTextures[ textureCacheKey ].usedTimes ++;
  49265. // every time the texture cache key changes, it's necessary to check if an instance of
  49266. // WebGLTexture can be deleted in order to avoid a memory leak.
  49267. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49268. if ( webglTexture !== undefined ) {
  49269. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49270. if ( webglTexture.usedTimes === 0 ) {
  49271. deleteTexture( texture );
  49272. }
  49273. }
  49274. // store references to cache key and WebGLTexture object
  49275. textureProperties.__cacheKey = textureCacheKey;
  49276. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49277. }
  49278. return forceUpload;
  49279. }
  49280. function getRow( index, rowLength, componentStride ) {
  49281. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49282. }
  49283. function updateTexture( texture, image, glFormat, glType ) {
  49284. const componentStride = 4; // only RGBA supported
  49285. const updateRanges = texture.updateRanges;
  49286. if ( updateRanges.length === 0 ) {
  49287. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49288. } else {
  49289. // Before applying update ranges, we merge any adjacent / overlapping
  49290. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49291. // to performance improvements for applications which make heavy use of
  49292. // update ranges. Likely due to GPU command overhead.
  49293. //
  49294. // Note that to reduce garbage collection between frames, we merge the
  49295. // update ranges in-place. This is safe because this method will clear the
  49296. // update ranges once updated.
  49297. updateRanges.sort( ( a, b ) => a.start - b.start );
  49298. // To merge the update ranges in-place, we work from left to right in the
  49299. // existing updateRanges array, merging ranges. This may result in a final
  49300. // array which is smaller than the original. This index tracks the last
  49301. // index representing a merged range, any data after this index can be
  49302. // trimmed once the merge algorithm is completed.
  49303. let mergeIndex = 0;
  49304. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49305. const previousRange = updateRanges[ mergeIndex ];
  49306. const range = updateRanges[ i ];
  49307. // Only merge if in the same row and overlapping/adjacent
  49308. const previousEnd = previousRange.start + previousRange.count;
  49309. const currentRow = getRow( range.start, image.width, componentStride );
  49310. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49311. // We add one here to merge adjacent ranges. This is safe because ranges
  49312. // operate over positive integers.
  49313. if (
  49314. range.start <= previousEnd + 1 &&
  49315. currentRow === previousRow &&
  49316. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49317. ) {
  49318. previousRange.count = Math.max(
  49319. previousRange.count,
  49320. range.start + range.count - previousRange.start
  49321. );
  49322. } else {
  49323. ++ mergeIndex;
  49324. updateRanges[ mergeIndex ] = range;
  49325. }
  49326. }
  49327. // Trim the array to only contain the merged ranges.
  49328. updateRanges.length = mergeIndex + 1;
  49329. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49330. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49331. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49332. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49333. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49334. const range = updateRanges[ i ];
  49335. const pixelStart = Math.floor( range.start / componentStride );
  49336. const pixelCount = Math.ceil( range.count / componentStride );
  49337. const x = pixelStart % image.width;
  49338. const y = Math.floor( pixelStart / image.width );
  49339. // Assumes update ranges refer to contiguous memory
  49340. const width = pixelCount;
  49341. const height = 1;
  49342. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49343. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49344. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49345. }
  49346. texture.clearUpdateRanges();
  49347. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49348. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49349. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49350. }
  49351. }
  49352. function uploadTexture( textureProperties, texture, slot ) {
  49353. let textureType = _gl.TEXTURE_2D;
  49354. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49355. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49356. const forceUpload = initTexture( textureProperties, texture );
  49357. const source = texture.source;
  49358. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49359. const sourceProperties = properties.get( source );
  49360. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49361. state.activeTexture( _gl.TEXTURE0 + slot );
  49362. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49363. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49364. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49365. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49366. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49367. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49368. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49369. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49370. image = verifyColorSpace( texture, image );
  49371. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49372. const glType = utils.convert( texture.type );
  49373. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49374. setTextureParameters( textureType, texture );
  49375. let mipmap;
  49376. const mipmaps = texture.mipmaps;
  49377. const useTexStorage = ( texture.isVideoTexture !== true );
  49378. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49379. const dataReady = source.dataReady;
  49380. const levels = getMipLevels( texture, image );
  49381. if ( texture.isDepthTexture ) {
  49382. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49383. //
  49384. if ( allocateMemory ) {
  49385. if ( useTexStorage ) {
  49386. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49387. } else {
  49388. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49389. }
  49390. }
  49391. } else if ( texture.isDataTexture ) {
  49392. // use manually created mipmaps if available
  49393. // if there are no manual mipmaps
  49394. // set 0 level mipmap and then use GL to generate other mipmap levels
  49395. if ( mipmaps.length > 0 ) {
  49396. if ( useTexStorage && allocateMemory ) {
  49397. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49398. }
  49399. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49400. mipmap = mipmaps[ i ];
  49401. if ( useTexStorage ) {
  49402. if ( dataReady ) {
  49403. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49404. }
  49405. } else {
  49406. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49407. }
  49408. }
  49409. texture.generateMipmaps = false;
  49410. } else {
  49411. if ( useTexStorage ) {
  49412. if ( allocateMemory ) {
  49413. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49414. }
  49415. if ( dataReady ) {
  49416. updateTexture( texture, image, glFormat, glType );
  49417. }
  49418. } else {
  49419. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49420. }
  49421. }
  49422. } else if ( texture.isCompressedTexture ) {
  49423. if ( texture.isCompressedArrayTexture ) {
  49424. if ( useTexStorage && allocateMemory ) {
  49425. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49426. }
  49427. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49428. mipmap = mipmaps[ i ];
  49429. if ( texture.format !== RGBAFormat ) {
  49430. if ( glFormat !== null ) {
  49431. if ( useTexStorage ) {
  49432. if ( dataReady ) {
  49433. if ( texture.layerUpdates.size > 0 ) {
  49434. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49435. for ( const layerIndex of texture.layerUpdates ) {
  49436. const layerData = mipmap.data.subarray(
  49437. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49438. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49439. );
  49440. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49441. }
  49442. texture.clearLayerUpdates();
  49443. } else {
  49444. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49445. }
  49446. }
  49447. } else {
  49448. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  49449. }
  49450. } else {
  49451. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49452. }
  49453. } else {
  49454. if ( useTexStorage ) {
  49455. if ( dataReady ) {
  49456. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49457. }
  49458. } else {
  49459. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  49460. }
  49461. }
  49462. }
  49463. } else {
  49464. if ( useTexStorage && allocateMemory ) {
  49465. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49466. }
  49467. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49468. mipmap = mipmaps[ i ];
  49469. if ( texture.format !== RGBAFormat ) {
  49470. if ( glFormat !== null ) {
  49471. if ( useTexStorage ) {
  49472. if ( dataReady ) {
  49473. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49474. }
  49475. } else {
  49476. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49477. }
  49478. } else {
  49479. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49480. }
  49481. } else {
  49482. if ( useTexStorage ) {
  49483. if ( dataReady ) {
  49484. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49485. }
  49486. } else {
  49487. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49488. }
  49489. }
  49490. }
  49491. }
  49492. } else if ( texture.isDataArrayTexture ) {
  49493. if ( useTexStorage ) {
  49494. if ( allocateMemory ) {
  49495. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  49496. }
  49497. if ( dataReady ) {
  49498. if ( texture.layerUpdates.size > 0 ) {
  49499. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49500. for ( const layerIndex of texture.layerUpdates ) {
  49501. const layerData = image.data.subarray(
  49502. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49503. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49504. );
  49505. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49506. }
  49507. texture.clearLayerUpdates();
  49508. } else {
  49509. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49510. }
  49511. }
  49512. } else {
  49513. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49514. }
  49515. } else if ( texture.isData3DTexture ) {
  49516. if ( useTexStorage ) {
  49517. if ( allocateMemory ) {
  49518. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  49519. }
  49520. if ( dataReady ) {
  49521. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49522. }
  49523. } else {
  49524. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49525. }
  49526. } else if ( texture.isFramebufferTexture ) {
  49527. if ( allocateMemory ) {
  49528. if ( useTexStorage ) {
  49529. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49530. } else {
  49531. let width = image.width, height = image.height;
  49532. for ( let i = 0; i < levels; i ++ ) {
  49533. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  49534. width >>= 1;
  49535. height >>= 1;
  49536. }
  49537. }
  49538. }
  49539. } else {
  49540. // regular Texture (image, video, canvas)
  49541. // use manually created mipmaps if available
  49542. // if there are no manual mipmaps
  49543. // set 0 level mipmap and then use GL to generate other mipmap levels
  49544. if ( mipmaps.length > 0 ) {
  49545. if ( useTexStorage && allocateMemory ) {
  49546. const dimensions = getDimensions( mipmaps[ 0 ] );
  49547. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49548. }
  49549. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49550. mipmap = mipmaps[ i ];
  49551. if ( useTexStorage ) {
  49552. if ( dataReady ) {
  49553. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  49554. }
  49555. } else {
  49556. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  49557. }
  49558. }
  49559. texture.generateMipmaps = false;
  49560. } else {
  49561. if ( useTexStorage ) {
  49562. if ( allocateMemory ) {
  49563. const dimensions = getDimensions( image );
  49564. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49565. }
  49566. if ( dataReady ) {
  49567. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  49568. }
  49569. } else {
  49570. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  49571. }
  49572. }
  49573. }
  49574. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49575. generateMipmap( textureType );
  49576. }
  49577. sourceProperties.__version = source.version;
  49578. if ( texture.onUpdate ) texture.onUpdate( texture );
  49579. }
  49580. textureProperties.__version = texture.version;
  49581. }
  49582. function uploadCubeTexture( textureProperties, texture, slot ) {
  49583. if ( texture.image.length !== 6 ) return;
  49584. const forceUpload = initTexture( textureProperties, texture );
  49585. const source = texture.source;
  49586. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49587. const sourceProperties = properties.get( source );
  49588. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49589. state.activeTexture( _gl.TEXTURE0 + slot );
  49590. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49591. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49592. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49593. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49594. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49595. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49596. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49597. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  49598. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  49599. const cubeImage = [];
  49600. for ( let i = 0; i < 6; i ++ ) {
  49601. if ( ! isCompressed && ! isDataTexture ) {
  49602. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  49603. } else {
  49604. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  49605. }
  49606. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  49607. }
  49608. const image = cubeImage[ 0 ],
  49609. glFormat = utils.convert( texture.format, texture.colorSpace ),
  49610. glType = utils.convert( texture.type ),
  49611. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49612. const useTexStorage = ( texture.isVideoTexture !== true );
  49613. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49614. const dataReady = source.dataReady;
  49615. let levels = getMipLevels( texture, image );
  49616. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49617. let mipmaps;
  49618. if ( isCompressed ) {
  49619. if ( useTexStorage && allocateMemory ) {
  49620. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  49621. }
  49622. for ( let i = 0; i < 6; i ++ ) {
  49623. mipmaps = cubeImage[ i ].mipmaps;
  49624. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49625. const mipmap = mipmaps[ j ];
  49626. if ( texture.format !== RGBAFormat ) {
  49627. if ( glFormat !== null ) {
  49628. if ( useTexStorage ) {
  49629. if ( dataReady ) {
  49630. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49631. }
  49632. } else {
  49633. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49634. }
  49635. } else {
  49636. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  49637. }
  49638. } else {
  49639. if ( useTexStorage ) {
  49640. if ( dataReady ) {
  49641. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49642. }
  49643. } else {
  49644. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49645. }
  49646. }
  49647. }
  49648. }
  49649. } else {
  49650. mipmaps = texture.mipmaps;
  49651. if ( useTexStorage && allocateMemory ) {
  49652. // TODO: Uniformly handle mipmap definitions
  49653. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  49654. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  49655. if ( mipmaps.length > 0 ) levels ++;
  49656. const dimensions = getDimensions( cubeImage[ 0 ] );
  49657. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  49658. }
  49659. for ( let i = 0; i < 6; i ++ ) {
  49660. if ( isDataTexture ) {
  49661. if ( useTexStorage ) {
  49662. if ( dataReady ) {
  49663. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  49664. }
  49665. } else {
  49666. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  49667. }
  49668. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49669. const mipmap = mipmaps[ j ];
  49670. const mipmapImage = mipmap.image[ i ].image;
  49671. if ( useTexStorage ) {
  49672. if ( dataReady ) {
  49673. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  49674. }
  49675. } else {
  49676. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  49677. }
  49678. }
  49679. } else {
  49680. if ( useTexStorage ) {
  49681. if ( dataReady ) {
  49682. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  49683. }
  49684. } else {
  49685. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  49686. }
  49687. for ( let j = 0; j < mipmaps.length; j ++ ) {
  49688. const mipmap = mipmaps[ j ];
  49689. if ( useTexStorage ) {
  49690. if ( dataReady ) {
  49691. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  49692. }
  49693. } else {
  49694. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  49695. }
  49696. }
  49697. }
  49698. }
  49699. }
  49700. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49701. // We assume images for cube map have the same size.
  49702. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49703. }
  49704. sourceProperties.__version = source.version;
  49705. if ( texture.onUpdate ) texture.onUpdate( texture );
  49706. }
  49707. textureProperties.__version = texture.version;
  49708. }
  49709. // Render targets
  49710. // Setup storage for target texture and bind it to correct framebuffer
  49711. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  49712. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49713. const glType = utils.convert( texture.type );
  49714. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49715. const renderTargetProperties = properties.get( renderTarget );
  49716. const textureProperties = properties.get( texture );
  49717. textureProperties.__renderTarget = renderTarget;
  49718. if ( ! renderTargetProperties.__hasExternalTextures ) {
  49719. const width = Math.max( 1, renderTarget.width >> level );
  49720. const height = Math.max( 1, renderTarget.height >> level );
  49721. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  49722. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  49723. } else {
  49724. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  49725. }
  49726. }
  49727. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49728. if ( useMultisampledRTT( renderTarget ) ) {
  49729. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  49730. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  49731. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  49732. }
  49733. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49734. }
  49735. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  49736. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  49737. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49738. if ( renderTarget.depthBuffer ) {
  49739. // retrieve the depth attachment types
  49740. const depthTexture = renderTarget.depthTexture;
  49741. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  49742. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  49743. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49744. // set up the attachment
  49745. const samples = getRenderTargetSamples( renderTarget );
  49746. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  49747. if ( isUseMultisampledRTT ) {
  49748. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49749. } else if ( isMultisample ) {
  49750. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49751. } else {
  49752. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49753. }
  49754. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49755. } else {
  49756. const textures = renderTarget.textures;
  49757. for ( let i = 0; i < textures.length; i ++ ) {
  49758. const texture = textures[ i ];
  49759. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49760. const glType = utils.convert( texture.type );
  49761. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  49762. const samples = getRenderTargetSamples( renderTarget );
  49763. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  49764. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49765. } else if ( useMultisampledRTT( renderTarget ) ) {
  49766. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49767. } else {
  49768. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  49769. }
  49770. }
  49771. }
  49772. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49773. }
  49774. // Setup resources for a Depth Texture for a FBO (needs an extension)
  49775. function setupDepthTexture( framebuffer, renderTarget ) {
  49776. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  49777. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  49778. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  49779. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  49780. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  49781. }
  49782. const textureProperties = properties.get( renderTarget.depthTexture );
  49783. textureProperties.__renderTarget = renderTarget;
  49784. // upload an empty depth texture with framebuffer size
  49785. if ( ! textureProperties.__webglTexture ||
  49786. renderTarget.depthTexture.image.width !== renderTarget.width ||
  49787. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  49788. renderTarget.depthTexture.image.width = renderTarget.width;
  49789. renderTarget.depthTexture.image.height = renderTarget.height;
  49790. renderTarget.depthTexture.needsUpdate = true;
  49791. }
  49792. setTexture2D( renderTarget.depthTexture, 0 );
  49793. const webglDepthTexture = textureProperties.__webglTexture;
  49794. const samples = getRenderTargetSamples( renderTarget );
  49795. if ( renderTarget.depthTexture.format === DepthFormat ) {
  49796. if ( useMultisampledRTT( renderTarget ) ) {
  49797. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49798. } else {
  49799. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49800. }
  49801. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  49802. if ( useMultisampledRTT( renderTarget ) ) {
  49803. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  49804. } else {
  49805. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  49806. }
  49807. } else {
  49808. throw new Error( 'Unknown depthTexture format' );
  49809. }
  49810. }
  49811. // Setup GL resources for a non-texture depth buffer
  49812. function setupDepthRenderbuffer( renderTarget ) {
  49813. const renderTargetProperties = properties.get( renderTarget );
  49814. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49815. // if the bound depth texture has changed
  49816. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  49817. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  49818. const depthTexture = renderTarget.depthTexture;
  49819. if ( renderTargetProperties.__depthDisposeCallback ) {
  49820. renderTargetProperties.__depthDisposeCallback();
  49821. }
  49822. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  49823. if ( depthTexture ) {
  49824. const disposeEvent = () => {
  49825. delete renderTargetProperties.__boundDepthTexture;
  49826. delete renderTargetProperties.__depthDisposeCallback;
  49827. depthTexture.removeEventListener( 'dispose', disposeEvent );
  49828. };
  49829. depthTexture.addEventListener( 'dispose', disposeEvent );
  49830. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  49831. }
  49832. renderTargetProperties.__boundDepthTexture = depthTexture;
  49833. }
  49834. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  49835. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  49836. const mipmaps = renderTarget.texture.mipmaps;
  49837. if ( mipmaps && mipmaps.length > 0 ) {
  49838. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget );
  49839. } else {
  49840. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  49841. }
  49842. } else {
  49843. if ( isCube ) {
  49844. renderTargetProperties.__webglDepthbuffer = [];
  49845. for ( let i = 0; i < 6; i ++ ) {
  49846. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  49847. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  49848. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  49849. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  49850. } else {
  49851. // attach buffer if it's been created already
  49852. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49853. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  49854. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49855. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49856. }
  49857. }
  49858. } else {
  49859. const mipmaps = renderTarget.texture.mipmaps;
  49860. if ( mipmaps && mipmaps.length > 0 ) {
  49861. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  49862. } else {
  49863. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  49864. }
  49865. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  49866. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  49867. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  49868. } else {
  49869. // attach buffer if it's been created already
  49870. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  49871. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  49872. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  49873. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  49874. }
  49875. }
  49876. }
  49877. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49878. }
  49879. // rebind framebuffer with external textures
  49880. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  49881. const renderTargetProperties = properties.get( renderTarget );
  49882. if ( colorTexture !== undefined ) {
  49883. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  49884. }
  49885. if ( depthTexture !== undefined ) {
  49886. setupDepthRenderbuffer( renderTarget );
  49887. }
  49888. }
  49889. // Set up GL resources for the render target
  49890. function setupRenderTarget( renderTarget ) {
  49891. const texture = renderTarget.texture;
  49892. const renderTargetProperties = properties.get( renderTarget );
  49893. const textureProperties = properties.get( texture );
  49894. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  49895. const textures = renderTarget.textures;
  49896. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  49897. const isMultipleRenderTargets = ( textures.length > 1 );
  49898. if ( ! isMultipleRenderTargets ) {
  49899. if ( textureProperties.__webglTexture === undefined ) {
  49900. textureProperties.__webglTexture = _gl.createTexture();
  49901. }
  49902. textureProperties.__version = texture.version;
  49903. info.memory.textures ++;
  49904. }
  49905. // Setup framebuffer
  49906. if ( isCube ) {
  49907. renderTargetProperties.__webglFramebuffer = [];
  49908. for ( let i = 0; i < 6; i ++ ) {
  49909. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49910. renderTargetProperties.__webglFramebuffer[ i ] = [];
  49911. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49912. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  49913. }
  49914. } else {
  49915. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  49916. }
  49917. }
  49918. } else {
  49919. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49920. renderTargetProperties.__webglFramebuffer = [];
  49921. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49922. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  49923. }
  49924. } else {
  49925. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  49926. }
  49927. if ( isMultipleRenderTargets ) {
  49928. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49929. const attachmentProperties = properties.get( textures[ i ] );
  49930. if ( attachmentProperties.__webglTexture === undefined ) {
  49931. attachmentProperties.__webglTexture = _gl.createTexture();
  49932. info.memory.textures ++;
  49933. }
  49934. }
  49935. }
  49936. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  49937. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  49938. renderTargetProperties.__webglColorRenderbuffer = [];
  49939. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  49940. for ( let i = 0; i < textures.length; i ++ ) {
  49941. const texture = textures[ i ];
  49942. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  49943. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49944. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49945. const glType = utils.convert( texture.type );
  49946. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  49947. const samples = getRenderTargetSamples( renderTarget );
  49948. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  49949. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49950. }
  49951. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  49952. if ( renderTarget.depthBuffer ) {
  49953. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  49954. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  49955. }
  49956. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  49957. }
  49958. }
  49959. // Setup color buffer
  49960. if ( isCube ) {
  49961. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  49962. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  49963. for ( let i = 0; i < 6; i ++ ) {
  49964. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  49965. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  49966. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  49967. }
  49968. } else {
  49969. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  49970. }
  49971. }
  49972. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49973. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  49974. }
  49975. state.unbindTexture();
  49976. } else if ( isMultipleRenderTargets ) {
  49977. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49978. const attachment = textures[ i ];
  49979. const attachmentProperties = properties.get( attachment );
  49980. let glTextureType = _gl.TEXTURE_2D;
  49981. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49982. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49983. }
  49984. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  49985. setTextureParameters( glTextureType, attachment );
  49986. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  49987. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  49988. generateMipmap( glTextureType );
  49989. }
  49990. }
  49991. state.unbindTexture();
  49992. } else {
  49993. let glTextureType = _gl.TEXTURE_2D;
  49994. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  49995. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  49996. }
  49997. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  49998. setTextureParameters( glTextureType, texture );
  49999. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50000. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50001. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50002. }
  50003. } else {
  50004. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50005. }
  50006. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50007. generateMipmap( glTextureType );
  50008. }
  50009. state.unbindTexture();
  50010. }
  50011. // Setup depth and stencil buffers
  50012. if ( renderTarget.depthBuffer ) {
  50013. setupDepthRenderbuffer( renderTarget );
  50014. }
  50015. }
  50016. function updateRenderTargetMipmap( renderTarget ) {
  50017. const textures = renderTarget.textures;
  50018. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50019. const texture = textures[ i ];
  50020. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50021. const targetType = getTargetType( renderTarget );
  50022. const webglTexture = properties.get( texture ).__webglTexture;
  50023. state.bindTexture( targetType, webglTexture );
  50024. generateMipmap( targetType );
  50025. state.unbindTexture();
  50026. }
  50027. }
  50028. }
  50029. const invalidationArrayRead = [];
  50030. const invalidationArrayDraw = [];
  50031. function updateMultisampleRenderTarget( renderTarget ) {
  50032. if ( renderTarget.samples > 0 ) {
  50033. if ( useMultisampledRTT( renderTarget ) === false ) {
  50034. const textures = renderTarget.textures;
  50035. const width = renderTarget.width;
  50036. const height = renderTarget.height;
  50037. let mask = _gl.COLOR_BUFFER_BIT;
  50038. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50039. const renderTargetProperties = properties.get( renderTarget );
  50040. const isMultipleRenderTargets = ( textures.length > 1 );
  50041. // If MRT we need to remove FBO attachments
  50042. if ( isMultipleRenderTargets ) {
  50043. for ( let i = 0; i < textures.length; i ++ ) {
  50044. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50045. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50046. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50047. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50048. }
  50049. }
  50050. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50051. const mipmaps = renderTarget.texture.mipmaps;
  50052. if ( mipmaps && mipmaps.length > 0 ) {
  50053. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50054. } else {
  50055. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50056. }
  50057. for ( let i = 0; i < textures.length; i ++ ) {
  50058. if ( renderTarget.resolveDepthBuffer ) {
  50059. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50060. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50061. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50062. }
  50063. if ( isMultipleRenderTargets ) {
  50064. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50065. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50066. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50067. }
  50068. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50069. if ( supportsInvalidateFramebuffer === true ) {
  50070. invalidationArrayRead.length = 0;
  50071. invalidationArrayDraw.length = 0;
  50072. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50073. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50074. invalidationArrayRead.push( depthStyle );
  50075. invalidationArrayDraw.push( depthStyle );
  50076. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50077. }
  50078. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50079. }
  50080. }
  50081. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50082. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50083. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50084. if ( isMultipleRenderTargets ) {
  50085. for ( let i = 0; i < textures.length; i ++ ) {
  50086. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50087. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50088. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50089. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50090. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50091. }
  50092. }
  50093. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50094. } else {
  50095. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50096. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50097. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50098. }
  50099. }
  50100. }
  50101. }
  50102. function getRenderTargetSamples( renderTarget ) {
  50103. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50104. }
  50105. function useMultisampledRTT( renderTarget ) {
  50106. const renderTargetProperties = properties.get( renderTarget );
  50107. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50108. }
  50109. function updateVideoTexture( texture ) {
  50110. const frame = info.render.frame;
  50111. // Check the last frame we updated the VideoTexture
  50112. if ( _videoTextures.get( texture ) !== frame ) {
  50113. _videoTextures.set( texture, frame );
  50114. texture.update();
  50115. }
  50116. }
  50117. function verifyColorSpace( texture, image ) {
  50118. const colorSpace = texture.colorSpace;
  50119. const format = texture.format;
  50120. const type = texture.type;
  50121. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50122. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50123. // sRGB
  50124. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50125. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50126. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50127. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50128. }
  50129. } else {
  50130. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50131. }
  50132. }
  50133. return image;
  50134. }
  50135. function getDimensions( image ) {
  50136. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50137. // if intrinsic data are not available, fallback to width/height
  50138. _imageDimensions.width = image.naturalWidth || image.width;
  50139. _imageDimensions.height = image.naturalHeight || image.height;
  50140. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50141. _imageDimensions.width = image.displayWidth;
  50142. _imageDimensions.height = image.displayHeight;
  50143. } else {
  50144. _imageDimensions.width = image.width;
  50145. _imageDimensions.height = image.height;
  50146. }
  50147. return _imageDimensions;
  50148. }
  50149. //
  50150. this.allocateTextureUnit = allocateTextureUnit;
  50151. this.resetTextureUnits = resetTextureUnits;
  50152. this.setTexture2D = setTexture2D;
  50153. this.setTexture2DArray = setTexture2DArray;
  50154. this.setTexture3D = setTexture3D;
  50155. this.setTextureCube = setTextureCube;
  50156. this.rebindTextures = rebindTextures;
  50157. this.setupRenderTarget = setupRenderTarget;
  50158. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50159. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50160. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50161. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50162. this.useMultisampledRTT = useMultisampledRTT;
  50163. }
  50164. function WebGLUtils( gl, extensions ) {
  50165. function convert( p, colorSpace = NoColorSpace ) {
  50166. let extension;
  50167. const transfer = ColorManagement.getTransfer( colorSpace );
  50168. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50169. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50170. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50171. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50172. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50173. if ( p === ByteType ) return gl.BYTE;
  50174. if ( p === ShortType ) return gl.SHORT;
  50175. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50176. if ( p === IntType ) return gl.INT;
  50177. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50178. if ( p === FloatType ) return gl.FLOAT;
  50179. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50180. if ( p === AlphaFormat ) return gl.ALPHA;
  50181. if ( p === RGBFormat ) return gl.RGB;
  50182. if ( p === RGBAFormat ) return gl.RGBA;
  50183. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50184. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50185. // WebGL2 formats.
  50186. if ( p === RedFormat ) return gl.RED;
  50187. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50188. if ( p === RGFormat ) return gl.RG;
  50189. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50190. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50191. // S3TC
  50192. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50193. if ( transfer === SRGBTransfer ) {
  50194. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50195. if ( extension !== null ) {
  50196. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50197. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50198. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50199. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50200. } else {
  50201. return null;
  50202. }
  50203. } else {
  50204. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50205. if ( extension !== null ) {
  50206. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50207. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50208. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50209. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50210. } else {
  50211. return null;
  50212. }
  50213. }
  50214. }
  50215. // PVRTC
  50216. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50217. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50218. if ( extension !== null ) {
  50219. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50220. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50221. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50222. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50223. } else {
  50224. return null;
  50225. }
  50226. }
  50227. // ETC
  50228. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  50229. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50230. if ( extension !== null ) {
  50231. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50232. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50233. } else {
  50234. return null;
  50235. }
  50236. }
  50237. // ASTC
  50238. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50239. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50240. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50241. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50242. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50243. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50244. if ( extension !== null ) {
  50245. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50246. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50247. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50248. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50249. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50250. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50251. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50252. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50253. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50254. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50255. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50256. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50257. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50258. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50259. } else {
  50260. return null;
  50261. }
  50262. }
  50263. // BPTC
  50264. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50265. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50266. if ( extension !== null ) {
  50267. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50268. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50269. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50270. } else {
  50271. return null;
  50272. }
  50273. }
  50274. // RGTC
  50275. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50276. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50277. if ( extension !== null ) {
  50278. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50279. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50280. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50281. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50282. } else {
  50283. return null;
  50284. }
  50285. }
  50286. //
  50287. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50288. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50289. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50290. }
  50291. return { convert: convert };
  50292. }
  50293. const _occlusion_vertex = `
  50294. void main() {
  50295. gl_Position = vec4( position, 1.0 );
  50296. }`;
  50297. const _occlusion_fragment = `
  50298. uniform sampler2DArray depthColor;
  50299. uniform float depthWidth;
  50300. uniform float depthHeight;
  50301. void main() {
  50302. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50303. if ( coord.x >= 1.0 ) {
  50304. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50305. } else {
  50306. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50307. }
  50308. }`;
  50309. /**
  50310. * A XR module that manages the access to the Depth Sensing API.
  50311. */
  50312. class WebXRDepthSensing {
  50313. /**
  50314. * Constructs a new depth sensing module.
  50315. */
  50316. constructor() {
  50317. /**
  50318. * An opaque texture representing the depth of the user's environment.
  50319. *
  50320. * @type {?ExternalTexture}
  50321. */
  50322. this.texture = null;
  50323. /**
  50324. * A plane mesh for visualizing the depth texture.
  50325. *
  50326. * @type {?Mesh}
  50327. */
  50328. this.mesh = null;
  50329. /**
  50330. * The depth near value.
  50331. *
  50332. * @type {number}
  50333. */
  50334. this.depthNear = 0;
  50335. /**
  50336. * The depth near far.
  50337. *
  50338. * @type {number}
  50339. */
  50340. this.depthFar = 0;
  50341. }
  50342. /**
  50343. * Inits the depth sensing module
  50344. *
  50345. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50346. * @param {XRRenderState} renderState - The XR render state.
  50347. */
  50348. init( depthData, renderState ) {
  50349. if ( this.texture === null ) {
  50350. const texture = new ExternalTexture( depthData.texture );
  50351. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50352. this.depthNear = depthData.depthNear;
  50353. this.depthFar = depthData.depthFar;
  50354. }
  50355. this.texture = texture;
  50356. }
  50357. }
  50358. /**
  50359. * Returns a plane mesh that visualizes the depth texture.
  50360. *
  50361. * @param {ArrayCamera} cameraXR - The XR camera.
  50362. * @return {?Mesh} The plane mesh.
  50363. */
  50364. getMesh( cameraXR ) {
  50365. if ( this.texture !== null ) {
  50366. if ( this.mesh === null ) {
  50367. const viewport = cameraXR.cameras[ 0 ].viewport;
  50368. const material = new ShaderMaterial( {
  50369. vertexShader: _occlusion_vertex,
  50370. fragmentShader: _occlusion_fragment,
  50371. uniforms: {
  50372. depthColor: { value: this.texture },
  50373. depthWidth: { value: viewport.z },
  50374. depthHeight: { value: viewport.w }
  50375. }
  50376. } );
  50377. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50378. }
  50379. }
  50380. return this.mesh;
  50381. }
  50382. /**
  50383. * Resets the module
  50384. */
  50385. reset() {
  50386. this.texture = null;
  50387. this.mesh = null;
  50388. }
  50389. /**
  50390. * Returns a texture representing the depth of the user's environment.
  50391. *
  50392. * @return {?ExternalTexture} The depth texture.
  50393. */
  50394. getDepthTexture() {
  50395. return this.texture;
  50396. }
  50397. }
  50398. /**
  50399. * This class represents an abstraction of the WebXR Device API and is
  50400. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50401. * interface that allows users to enable/disable XR and perform XR related
  50402. * tasks like for instance retrieving controllers.
  50403. *
  50404. * @augments EventDispatcher
  50405. * @hideconstructor
  50406. */
  50407. class WebXRManager extends EventDispatcher {
  50408. /**
  50409. * Constructs a new WebGL renderer.
  50410. *
  50411. * @param {WebGLRenderer} renderer - The renderer.
  50412. * @param {WebGL2RenderingContext} gl - The rendering context.
  50413. */
  50414. constructor( renderer, gl ) {
  50415. super();
  50416. const scope = this;
  50417. let session = null;
  50418. let framebufferScaleFactor = 1.0;
  50419. let referenceSpace = null;
  50420. let referenceSpaceType = 'local-floor';
  50421. // Set default foveation to maximum.
  50422. let foveation = 1.0;
  50423. let customReferenceSpace = null;
  50424. let pose = null;
  50425. let glBinding = null;
  50426. let glProjLayer = null;
  50427. let glBaseLayer = null;
  50428. let xrFrame = null;
  50429. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  50430. const depthSensing = new WebXRDepthSensing();
  50431. const cameraAccessTextures = {};
  50432. const attributes = gl.getContextAttributes();
  50433. let initialRenderTarget = null;
  50434. let newRenderTarget = null;
  50435. const controllers = [];
  50436. const controllerInputSources = [];
  50437. const currentSize = new Vector2();
  50438. let currentPixelRatio = null;
  50439. //
  50440. const cameraL = new PerspectiveCamera();
  50441. cameraL.viewport = new Vector4();
  50442. const cameraR = new PerspectiveCamera();
  50443. cameraR.viewport = new Vector4();
  50444. const cameras = [ cameraL, cameraR ];
  50445. const cameraXR = new ArrayCamera();
  50446. let _currentDepthNear = null;
  50447. let _currentDepthFar = null;
  50448. //
  50449. /**
  50450. * Whether the manager's XR camera should be automatically updated or not.
  50451. *
  50452. * @type {boolean}
  50453. * @default true
  50454. */
  50455. this.cameraAutoUpdate = true;
  50456. /**
  50457. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  50458. * if you are going to use XR in your app.
  50459. *
  50460. * @type {boolean}
  50461. * @default false
  50462. */
  50463. this.enabled = false;
  50464. /**
  50465. * Whether XR presentation is active or not.
  50466. *
  50467. * @type {boolean}
  50468. * @readonly
  50469. * @default false
  50470. */
  50471. this.isPresenting = false;
  50472. /**
  50473. * Returns a group representing the `target ray` space of the XR controller.
  50474. * Use this space for visualizing 3D objects that support the user in pointing
  50475. * tasks like UI interaction.
  50476. *
  50477. * @param {number} index - The index of the controller.
  50478. * @return {Group} A group representing the `target ray` space.
  50479. */
  50480. this.getController = function ( index ) {
  50481. let controller = controllers[ index ];
  50482. if ( controller === undefined ) {
  50483. controller = new WebXRController();
  50484. controllers[ index ] = controller;
  50485. }
  50486. return controller.getTargetRaySpace();
  50487. };
  50488. /**
  50489. * Returns a group representing the `grip` space of the XR controller.
  50490. * Use this space for visualizing 3D objects that support the user in pointing
  50491. * tasks like UI interaction.
  50492. *
  50493. * Note: If you want to show something in the user's hand AND offer a
  50494. * pointing ray at the same time, you'll want to attached the handheld object
  50495. * to the group returned by `getControllerGrip()` and the ray to the
  50496. * group returned by `getController()`. The idea is to have two
  50497. * different groups in two different coordinate spaces for the same WebXR
  50498. * controller.
  50499. *
  50500. * @param {number} index - The index of the controller.
  50501. * @return {Group} A group representing the `grip` space.
  50502. */
  50503. this.getControllerGrip = function ( index ) {
  50504. let controller = controllers[ index ];
  50505. if ( controller === undefined ) {
  50506. controller = new WebXRController();
  50507. controllers[ index ] = controller;
  50508. }
  50509. return controller.getGripSpace();
  50510. };
  50511. /**
  50512. * Returns a group representing the `hand` space of the XR controller.
  50513. * Use this space for visualizing 3D objects that support the user in pointing
  50514. * tasks like UI interaction.
  50515. *
  50516. * @param {number} index - The index of the controller.
  50517. * @return {Group} A group representing the `hand` space.
  50518. */
  50519. this.getHand = function ( index ) {
  50520. let controller = controllers[ index ];
  50521. if ( controller === undefined ) {
  50522. controller = new WebXRController();
  50523. controllers[ index ] = controller;
  50524. }
  50525. return controller.getHandSpace();
  50526. };
  50527. //
  50528. function onSessionEvent( event ) {
  50529. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  50530. if ( controllerIndex === -1 ) {
  50531. return;
  50532. }
  50533. const controller = controllers[ controllerIndex ];
  50534. if ( controller !== undefined ) {
  50535. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  50536. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  50537. }
  50538. }
  50539. function onSessionEnd() {
  50540. session.removeEventListener( 'select', onSessionEvent );
  50541. session.removeEventListener( 'selectstart', onSessionEvent );
  50542. session.removeEventListener( 'selectend', onSessionEvent );
  50543. session.removeEventListener( 'squeeze', onSessionEvent );
  50544. session.removeEventListener( 'squeezestart', onSessionEvent );
  50545. session.removeEventListener( 'squeezeend', onSessionEvent );
  50546. session.removeEventListener( 'end', onSessionEnd );
  50547. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  50548. for ( let i = 0; i < controllers.length; i ++ ) {
  50549. const inputSource = controllerInputSources[ i ];
  50550. if ( inputSource === null ) continue;
  50551. controllerInputSources[ i ] = null;
  50552. controllers[ i ].disconnect( inputSource );
  50553. }
  50554. _currentDepthNear = null;
  50555. _currentDepthFar = null;
  50556. depthSensing.reset();
  50557. for ( const key in cameraAccessTextures ) {
  50558. delete cameraAccessTextures[ key ];
  50559. }
  50560. // restore framebuffer/rendering state
  50561. renderer.setRenderTarget( initialRenderTarget );
  50562. glBaseLayer = null;
  50563. glProjLayer = null;
  50564. glBinding = null;
  50565. session = null;
  50566. newRenderTarget = null;
  50567. //
  50568. animation.stop();
  50569. scope.isPresenting = false;
  50570. renderer.setPixelRatio( currentPixelRatio );
  50571. renderer.setSize( currentSize.width, currentSize.height, false );
  50572. scope.dispatchEvent( { type: 'sessionend' } );
  50573. }
  50574. /**
  50575. * Sets the framebuffer scale factor.
  50576. *
  50577. * This method can not be used during a XR session.
  50578. *
  50579. * @param {number} value - The framebuffer scale factor.
  50580. */
  50581. this.setFramebufferScaleFactor = function ( value ) {
  50582. framebufferScaleFactor = value;
  50583. if ( scope.isPresenting === true ) {
  50584. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  50585. }
  50586. };
  50587. /**
  50588. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  50589. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  50590. * improve tracking. Default is `local-floor`. Valid values can be found here
  50591. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  50592. *
  50593. * This method can not be used during a XR session.
  50594. *
  50595. * @param {string} value - The reference space type.
  50596. */
  50597. this.setReferenceSpaceType = function ( value ) {
  50598. referenceSpaceType = value;
  50599. if ( scope.isPresenting === true ) {
  50600. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  50601. }
  50602. };
  50603. /**
  50604. * Returns the XR reference space.
  50605. *
  50606. * @return {XRReferenceSpace} The XR reference space.
  50607. */
  50608. this.getReferenceSpace = function () {
  50609. return customReferenceSpace || referenceSpace;
  50610. };
  50611. /**
  50612. * Sets a custom XR reference space.
  50613. *
  50614. * @param {XRReferenceSpace} space - The XR reference space.
  50615. */
  50616. this.setReferenceSpace = function ( space ) {
  50617. customReferenceSpace = space;
  50618. };
  50619. /**
  50620. * Returns the current base layer.
  50621. *
  50622. * This is an `XRProjectionLayer` when the targeted XR device supports the
  50623. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  50624. *
  50625. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  50626. */
  50627. this.getBaseLayer = function () {
  50628. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  50629. };
  50630. /**
  50631. * Returns the current XR binding.
  50632. *
  50633. * Creates a new binding if needed and the browser is
  50634. * capable of doing so.
  50635. *
  50636. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  50637. */
  50638. this.getBinding = function () {
  50639. if ( glBinding === null && supportsGlBinding ) {
  50640. glBinding = new XRWebGLBinding( session, gl );
  50641. }
  50642. return glBinding;
  50643. };
  50644. /**
  50645. * Returns the current XR frame.
  50646. *
  50647. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  50648. */
  50649. this.getFrame = function () {
  50650. return xrFrame;
  50651. };
  50652. /**
  50653. * Returns the current XR session.
  50654. *
  50655. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  50656. */
  50657. this.getSession = function () {
  50658. return session;
  50659. };
  50660. /**
  50661. * After a XR session has been requested usually with one of the `*Button` modules, it
  50662. * is injected into the renderer with this method. This method triggers the start of
  50663. * the actual XR rendering.
  50664. *
  50665. * @async
  50666. * @param {XRSession} value - The XR session to set.
  50667. * @return {Promise} A Promise that resolves when the session has been set.
  50668. */
  50669. this.setSession = async function ( value ) {
  50670. session = value;
  50671. if ( session !== null ) {
  50672. initialRenderTarget = renderer.getRenderTarget();
  50673. session.addEventListener( 'select', onSessionEvent );
  50674. session.addEventListener( 'selectstart', onSessionEvent );
  50675. session.addEventListener( 'selectend', onSessionEvent );
  50676. session.addEventListener( 'squeeze', onSessionEvent );
  50677. session.addEventListener( 'squeezestart', onSessionEvent );
  50678. session.addEventListener( 'squeezeend', onSessionEvent );
  50679. session.addEventListener( 'end', onSessionEnd );
  50680. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  50681. if ( attributes.xrCompatible !== true ) {
  50682. await gl.makeXRCompatible();
  50683. }
  50684. currentPixelRatio = renderer.getPixelRatio();
  50685. renderer.getSize( currentSize );
  50686. // Check that the browser implements the necessary APIs to use an
  50687. // XRProjectionLayer rather than an XRWebGLLayer
  50688. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  50689. if ( ! supportsLayers ) {
  50690. const layerInit = {
  50691. antialias: attributes.antialias,
  50692. alpha: true,
  50693. depth: attributes.depth,
  50694. stencil: attributes.stencil,
  50695. framebufferScaleFactor: framebufferScaleFactor
  50696. };
  50697. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  50698. session.updateRenderState( { baseLayer: glBaseLayer } );
  50699. renderer.setPixelRatio( 1 );
  50700. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  50701. newRenderTarget = new WebGLRenderTarget(
  50702. glBaseLayer.framebufferWidth,
  50703. glBaseLayer.framebufferHeight,
  50704. {
  50705. format: RGBAFormat,
  50706. type: UnsignedByteType,
  50707. colorSpace: renderer.outputColorSpace,
  50708. stencilBuffer: attributes.stencil,
  50709. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  50710. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  50711. }
  50712. );
  50713. } else {
  50714. let depthFormat = null;
  50715. let depthType = null;
  50716. let glDepthFormat = null;
  50717. if ( attributes.depth ) {
  50718. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  50719. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  50720. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  50721. }
  50722. const projectionlayerInit = {
  50723. colorFormat: gl.RGBA8,
  50724. depthFormat: glDepthFormat,
  50725. scaleFactor: framebufferScaleFactor
  50726. };
  50727. glBinding = this.getBinding();
  50728. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  50729. session.updateRenderState( { layers: [ glProjLayer ] } );
  50730. renderer.setPixelRatio( 1 );
  50731. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  50732. newRenderTarget = new WebGLRenderTarget(
  50733. glProjLayer.textureWidth,
  50734. glProjLayer.textureHeight,
  50735. {
  50736. format: RGBAFormat,
  50737. type: UnsignedByteType,
  50738. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  50739. stencilBuffer: attributes.stencil,
  50740. colorSpace: renderer.outputColorSpace,
  50741. samples: attributes.antialias ? 4 : 0,
  50742. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  50743. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  50744. } );
  50745. }
  50746. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  50747. this.setFoveation( foveation );
  50748. customReferenceSpace = null;
  50749. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  50750. animation.setContext( session );
  50751. animation.start();
  50752. scope.isPresenting = true;
  50753. scope.dispatchEvent( { type: 'sessionstart' } );
  50754. }
  50755. };
  50756. /**
  50757. * Returns the environment blend mode from the current XR session.
  50758. *
  50759. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  50760. */
  50761. this.getEnvironmentBlendMode = function () {
  50762. if ( session !== null ) {
  50763. return session.environmentBlendMode;
  50764. }
  50765. };
  50766. /**
  50767. * Returns the current depth texture computed via depth sensing.
  50768. *
  50769. * See {@link WebXRDepthSensing#getDepthTexture}.
  50770. *
  50771. * @return {?Texture} The depth texture.
  50772. */
  50773. this.getDepthTexture = function () {
  50774. return depthSensing.getDepthTexture();
  50775. };
  50776. function onInputSourcesChange( event ) {
  50777. // Notify disconnected
  50778. for ( let i = 0; i < event.removed.length; i ++ ) {
  50779. const inputSource = event.removed[ i ];
  50780. const index = controllerInputSources.indexOf( inputSource );
  50781. if ( index >= 0 ) {
  50782. controllerInputSources[ index ] = null;
  50783. controllers[ index ].disconnect( inputSource );
  50784. }
  50785. }
  50786. // Notify connected
  50787. for ( let i = 0; i < event.added.length; i ++ ) {
  50788. const inputSource = event.added[ i ];
  50789. let controllerIndex = controllerInputSources.indexOf( inputSource );
  50790. if ( controllerIndex === -1 ) {
  50791. // Assign input source a controller that currently has no input source
  50792. for ( let i = 0; i < controllers.length; i ++ ) {
  50793. if ( i >= controllerInputSources.length ) {
  50794. controllerInputSources.push( inputSource );
  50795. controllerIndex = i;
  50796. break;
  50797. } else if ( controllerInputSources[ i ] === null ) {
  50798. controllerInputSources[ i ] = inputSource;
  50799. controllerIndex = i;
  50800. break;
  50801. }
  50802. }
  50803. // If all controllers do currently receive input we ignore new ones
  50804. if ( controllerIndex === -1 ) break;
  50805. }
  50806. const controller = controllers[ controllerIndex ];
  50807. if ( controller ) {
  50808. controller.connect( inputSource );
  50809. }
  50810. }
  50811. }
  50812. //
  50813. const cameraLPos = new Vector3();
  50814. const cameraRPos = new Vector3();
  50815. /**
  50816. * Assumes 2 cameras that are parallel and share an X-axis, and that
  50817. * the cameras' projection and world matrices have already been set.
  50818. * And that near and far planes are identical for both cameras.
  50819. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  50820. *
  50821. * @param {ArrayCamera} camera - The camera to update.
  50822. * @param {PerspectiveCamera} cameraL - The left camera.
  50823. * @param {PerspectiveCamera} cameraR - The right camera.
  50824. */
  50825. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  50826. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  50827. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  50828. const ipd = cameraLPos.distanceTo( cameraRPos );
  50829. const projL = cameraL.projectionMatrix.elements;
  50830. const projR = cameraR.projectionMatrix.elements;
  50831. // VR systems will have identical far and near planes, and
  50832. // most likely identical top and bottom frustum extents.
  50833. // Use the left camera for these values.
  50834. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  50835. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  50836. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  50837. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  50838. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  50839. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  50840. const left = near * leftFov;
  50841. const right = near * rightFov;
  50842. // Calculate the new camera's position offset from the
  50843. // left camera. xOffset should be roughly half `ipd`.
  50844. const zOffset = ipd / ( - leftFov + rightFov );
  50845. const xOffset = zOffset * - leftFov;
  50846. // TODO: Better way to apply this offset?
  50847. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  50848. camera.translateX( xOffset );
  50849. camera.translateZ( zOffset );
  50850. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  50851. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50852. // Check if the projection uses an infinite far plane.
  50853. if ( projL[ 10 ] === -1 ) {
  50854. // Use the projection matrix from the left eye.
  50855. // The camera offset is sufficient to include the view volumes
  50856. // of both eyes (assuming symmetric projections).
  50857. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  50858. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  50859. } else {
  50860. // Find the union of the frustum values of the cameras and scale
  50861. // the values so that the near plane's position does not change in world space,
  50862. // although must now be relative to the new union camera.
  50863. const near2 = near + zOffset;
  50864. const far2 = far + zOffset;
  50865. const left2 = left - xOffset;
  50866. const right2 = right + ( ipd - xOffset );
  50867. const top2 = topFov * far / far2 * near2;
  50868. const bottom2 = bottomFov * far / far2 * near2;
  50869. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  50870. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  50871. }
  50872. }
  50873. function updateCamera( camera, parent ) {
  50874. if ( parent === null ) {
  50875. camera.matrixWorld.copy( camera.matrix );
  50876. } else {
  50877. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  50878. }
  50879. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  50880. }
  50881. /**
  50882. * Updates the state of the XR camera. Use this method on app level if you
  50883. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  50884. * camera of the scene as a parameter. The passed in camera's transformation
  50885. * is automatically adjusted to the position of the XR camera when calling
  50886. * this method.
  50887. *
  50888. * @param {Camera} camera - The camera.
  50889. */
  50890. this.updateCamera = function ( camera ) {
  50891. if ( session === null ) return;
  50892. let depthNear = camera.near;
  50893. let depthFar = camera.far;
  50894. if ( depthSensing.texture !== null ) {
  50895. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  50896. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  50897. }
  50898. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  50899. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  50900. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  50901. // Note that the new renderState won't apply until the next frame. See #18320
  50902. session.updateRenderState( {
  50903. depthNear: cameraXR.near,
  50904. depthFar: cameraXR.far
  50905. } );
  50906. _currentDepthNear = cameraXR.near;
  50907. _currentDepthFar = cameraXR.far;
  50908. }
  50909. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  50910. cameraXR.layers.mask = camera.layers.mask | 0b110;
  50911. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  50912. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  50913. const parent = camera.parent;
  50914. const cameras = cameraXR.cameras;
  50915. updateCamera( cameraXR, parent );
  50916. for ( let i = 0; i < cameras.length; i ++ ) {
  50917. updateCamera( cameras[ i ], parent );
  50918. }
  50919. // update projection matrix for proper view frustum culling
  50920. if ( cameras.length === 2 ) {
  50921. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  50922. } else {
  50923. // assume single camera setup (AR)
  50924. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  50925. }
  50926. // update user camera and its children
  50927. updateUserCamera( camera, cameraXR, parent );
  50928. };
  50929. function updateUserCamera( camera, cameraXR, parent ) {
  50930. if ( parent === null ) {
  50931. camera.matrix.copy( cameraXR.matrixWorld );
  50932. } else {
  50933. camera.matrix.copy( parent.matrixWorld );
  50934. camera.matrix.invert();
  50935. camera.matrix.multiply( cameraXR.matrixWorld );
  50936. }
  50937. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  50938. camera.updateMatrixWorld( true );
  50939. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  50940. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  50941. if ( camera.isPerspectiveCamera ) {
  50942. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  50943. camera.zoom = 1;
  50944. }
  50945. }
  50946. /**
  50947. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  50948. * of the active XR session. For each view it holds a separate camera object.
  50949. *
  50950. * The camera's `fov` is currently not used and does not reflect the fov of
  50951. * the XR camera. If you need the fov on app level, you have to compute in
  50952. * manually from the XR camera's projection matrices.
  50953. *
  50954. * @return {ArrayCamera} The XR camera.
  50955. */
  50956. this.getCamera = function () {
  50957. return cameraXR;
  50958. };
  50959. /**
  50960. * Returns the amount of foveation used by the XR compositor for the projection layer.
  50961. *
  50962. * @return {number|undefined} The amount of foveation.
  50963. */
  50964. this.getFoveation = function () {
  50965. if ( glProjLayer === null && glBaseLayer === null ) {
  50966. return undefined;
  50967. }
  50968. return foveation;
  50969. };
  50970. /**
  50971. * Sets the foveation value.
  50972. *
  50973. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  50974. * and `1` means maximum foveation (the edges render at lower resolution).
  50975. */
  50976. this.setFoveation = function ( value ) {
  50977. // 0 = no foveation = full resolution
  50978. // 1 = maximum foveation = the edges render at lower resolution
  50979. foveation = value;
  50980. if ( glProjLayer !== null ) {
  50981. glProjLayer.fixedFoveation = value;
  50982. }
  50983. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  50984. glBaseLayer.fixedFoveation = value;
  50985. }
  50986. };
  50987. /**
  50988. * Returns `true` if depth sensing is supported.
  50989. *
  50990. * @return {boolean} Whether depth sensing is supported or not.
  50991. */
  50992. this.hasDepthSensing = function () {
  50993. return depthSensing.texture !== null;
  50994. };
  50995. /**
  50996. * Returns the depth sensing mesh.
  50997. *
  50998. * See {@link WebXRDepthSensing#getMesh}.
  50999. *
  51000. * @return {Mesh} The depth sensing mesh.
  51001. */
  51002. this.getDepthSensingMesh = function () {
  51003. return depthSensing.getMesh( cameraXR );
  51004. };
  51005. /**
  51006. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51007. * Only available during the current animation loop.
  51008. *
  51009. * @param {XRCamera} xrCamera - The camera to query.
  51010. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51011. */
  51012. this.getCameraTexture = function ( xrCamera ) {
  51013. return cameraAccessTextures[ xrCamera ];
  51014. };
  51015. // Animation Loop
  51016. let onAnimationFrameCallback = null;
  51017. function onAnimationFrame( time, frame ) {
  51018. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51019. xrFrame = frame;
  51020. if ( pose !== null ) {
  51021. const views = pose.views;
  51022. if ( glBaseLayer !== null ) {
  51023. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51024. renderer.setRenderTarget( newRenderTarget );
  51025. }
  51026. let cameraXRNeedsUpdate = false;
  51027. // check if it's necessary to rebuild cameraXR's camera list
  51028. if ( views.length !== cameraXR.cameras.length ) {
  51029. cameraXR.cameras.length = 0;
  51030. cameraXRNeedsUpdate = true;
  51031. }
  51032. for ( let i = 0; i < views.length; i ++ ) {
  51033. const view = views[ i ];
  51034. let viewport = null;
  51035. if ( glBaseLayer !== null ) {
  51036. viewport = glBaseLayer.getViewport( view );
  51037. } else {
  51038. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51039. viewport = glSubImage.viewport;
  51040. // For side-by-side projection, we only produce a single texture for both eyes.
  51041. if ( i === 0 ) {
  51042. renderer.setRenderTargetTextures(
  51043. newRenderTarget,
  51044. glSubImage.colorTexture,
  51045. glSubImage.depthStencilTexture );
  51046. renderer.setRenderTarget( newRenderTarget );
  51047. }
  51048. }
  51049. let camera = cameras[ i ];
  51050. if ( camera === undefined ) {
  51051. camera = new PerspectiveCamera();
  51052. camera.layers.enable( i );
  51053. camera.viewport = new Vector4();
  51054. cameras[ i ] = camera;
  51055. }
  51056. camera.matrix.fromArray( view.transform.matrix );
  51057. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51058. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51059. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51060. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51061. if ( i === 0 ) {
  51062. cameraXR.matrix.copy( camera.matrix );
  51063. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51064. }
  51065. if ( cameraXRNeedsUpdate === true ) {
  51066. cameraXR.cameras.push( camera );
  51067. }
  51068. }
  51069. //
  51070. const enabledFeatures = session.enabledFeatures;
  51071. const gpuDepthSensingEnabled = enabledFeatures &&
  51072. enabledFeatures.includes( 'depth-sensing' ) &&
  51073. session.depthUsage == 'gpu-optimized';
  51074. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51075. glBinding = scope.getBinding();
  51076. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51077. if ( depthData && depthData.isValid && depthData.texture ) {
  51078. depthSensing.init( depthData, session.renderState );
  51079. }
  51080. }
  51081. const cameraAccessEnabled = enabledFeatures &&
  51082. enabledFeatures.includes( 'camera-access' );
  51083. if ( cameraAccessEnabled && supportsGlBinding ) {
  51084. renderer.state.unbindTexture();
  51085. glBinding = scope.getBinding();
  51086. for ( let i = 0; i < views.length; i ++ ) {
  51087. const camera = views[ i ].camera;
  51088. if ( camera ) {
  51089. let cameraTex = cameraAccessTextures[ camera ];
  51090. if ( ! cameraTex ) {
  51091. cameraTex = new ExternalTexture();
  51092. cameraAccessTextures[ camera ] = cameraTex;
  51093. }
  51094. const glTexture = glBinding.getCameraImage( camera );
  51095. cameraTex.sourceTexture = glTexture;
  51096. }
  51097. }
  51098. }
  51099. }
  51100. //
  51101. for ( let i = 0; i < controllers.length; i ++ ) {
  51102. const inputSource = controllerInputSources[ i ];
  51103. const controller = controllers[ i ];
  51104. if ( inputSource !== null && controller !== undefined ) {
  51105. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51106. }
  51107. }
  51108. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51109. if ( frame.detectedPlanes ) {
  51110. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51111. }
  51112. xrFrame = null;
  51113. }
  51114. const animation = new WebGLAnimation();
  51115. animation.setAnimationLoop( onAnimationFrame );
  51116. this.setAnimationLoop = function ( callback ) {
  51117. onAnimationFrameCallback = callback;
  51118. };
  51119. this.dispose = function () {};
  51120. }
  51121. }
  51122. const _e1 = /*@__PURE__*/ new Euler();
  51123. const _m1 = /*@__PURE__*/ new Matrix4();
  51124. function WebGLMaterials( renderer, properties ) {
  51125. function refreshTransformUniform( map, uniform ) {
  51126. if ( map.matrixAutoUpdate === true ) {
  51127. map.updateMatrix();
  51128. }
  51129. uniform.value.copy( map.matrix );
  51130. }
  51131. function refreshFogUniforms( uniforms, fog ) {
  51132. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51133. if ( fog.isFog ) {
  51134. uniforms.fogNear.value = fog.near;
  51135. uniforms.fogFar.value = fog.far;
  51136. } else if ( fog.isFogExp2 ) {
  51137. uniforms.fogDensity.value = fog.density;
  51138. }
  51139. }
  51140. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51141. if ( material.isMeshBasicMaterial ) {
  51142. refreshUniformsCommon( uniforms, material );
  51143. } else if ( material.isMeshLambertMaterial ) {
  51144. refreshUniformsCommon( uniforms, material );
  51145. } else if ( material.isMeshToonMaterial ) {
  51146. refreshUniformsCommon( uniforms, material );
  51147. refreshUniformsToon( uniforms, material );
  51148. } else if ( material.isMeshPhongMaterial ) {
  51149. refreshUniformsCommon( uniforms, material );
  51150. refreshUniformsPhong( uniforms, material );
  51151. } else if ( material.isMeshStandardMaterial ) {
  51152. refreshUniformsCommon( uniforms, material );
  51153. refreshUniformsStandard( uniforms, material );
  51154. if ( material.isMeshPhysicalMaterial ) {
  51155. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51156. }
  51157. } else if ( material.isMeshMatcapMaterial ) {
  51158. refreshUniformsCommon( uniforms, material );
  51159. refreshUniformsMatcap( uniforms, material );
  51160. } else if ( material.isMeshDepthMaterial ) {
  51161. refreshUniformsCommon( uniforms, material );
  51162. } else if ( material.isMeshDistanceMaterial ) {
  51163. refreshUniformsCommon( uniforms, material );
  51164. refreshUniformsDistance( uniforms, material );
  51165. } else if ( material.isMeshNormalMaterial ) {
  51166. refreshUniformsCommon( uniforms, material );
  51167. } else if ( material.isLineBasicMaterial ) {
  51168. refreshUniformsLine( uniforms, material );
  51169. if ( material.isLineDashedMaterial ) {
  51170. refreshUniformsDash( uniforms, material );
  51171. }
  51172. } else if ( material.isPointsMaterial ) {
  51173. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51174. } else if ( material.isSpriteMaterial ) {
  51175. refreshUniformsSprites( uniforms, material );
  51176. } else if ( material.isShadowMaterial ) {
  51177. uniforms.color.value.copy( material.color );
  51178. uniforms.opacity.value = material.opacity;
  51179. } else if ( material.isShaderMaterial ) {
  51180. material.uniformsNeedUpdate = false; // #15581
  51181. }
  51182. }
  51183. function refreshUniformsCommon( uniforms, material ) {
  51184. uniforms.opacity.value = material.opacity;
  51185. if ( material.color ) {
  51186. uniforms.diffuse.value.copy( material.color );
  51187. }
  51188. if ( material.emissive ) {
  51189. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51190. }
  51191. if ( material.map ) {
  51192. uniforms.map.value = material.map;
  51193. refreshTransformUniform( material.map, uniforms.mapTransform );
  51194. }
  51195. if ( material.alphaMap ) {
  51196. uniforms.alphaMap.value = material.alphaMap;
  51197. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51198. }
  51199. if ( material.bumpMap ) {
  51200. uniforms.bumpMap.value = material.bumpMap;
  51201. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51202. uniforms.bumpScale.value = material.bumpScale;
  51203. if ( material.side === BackSide ) {
  51204. uniforms.bumpScale.value *= -1;
  51205. }
  51206. }
  51207. if ( material.normalMap ) {
  51208. uniforms.normalMap.value = material.normalMap;
  51209. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51210. uniforms.normalScale.value.copy( material.normalScale );
  51211. if ( material.side === BackSide ) {
  51212. uniforms.normalScale.value.negate();
  51213. }
  51214. }
  51215. if ( material.displacementMap ) {
  51216. uniforms.displacementMap.value = material.displacementMap;
  51217. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51218. uniforms.displacementScale.value = material.displacementScale;
  51219. uniforms.displacementBias.value = material.displacementBias;
  51220. }
  51221. if ( material.emissiveMap ) {
  51222. uniforms.emissiveMap.value = material.emissiveMap;
  51223. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51224. }
  51225. if ( material.specularMap ) {
  51226. uniforms.specularMap.value = material.specularMap;
  51227. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51228. }
  51229. if ( material.alphaTest > 0 ) {
  51230. uniforms.alphaTest.value = material.alphaTest;
  51231. }
  51232. const materialProperties = properties.get( material );
  51233. const envMap = materialProperties.envMap;
  51234. const envMapRotation = materialProperties.envMapRotation;
  51235. if ( envMap ) {
  51236. uniforms.envMap.value = envMap;
  51237. _e1.copy( envMapRotation );
  51238. // accommodate left-handed frame
  51239. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51240. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51241. // environment maps which are not cube render targets or PMREMs follow a different convention
  51242. _e1.y *= -1;
  51243. _e1.z *= -1;
  51244. }
  51245. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51246. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51247. uniforms.reflectivity.value = material.reflectivity;
  51248. uniforms.ior.value = material.ior;
  51249. uniforms.refractionRatio.value = material.refractionRatio;
  51250. }
  51251. if ( material.lightMap ) {
  51252. uniforms.lightMap.value = material.lightMap;
  51253. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51254. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51255. }
  51256. if ( material.aoMap ) {
  51257. uniforms.aoMap.value = material.aoMap;
  51258. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51259. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51260. }
  51261. }
  51262. function refreshUniformsLine( uniforms, material ) {
  51263. uniforms.diffuse.value.copy( material.color );
  51264. uniforms.opacity.value = material.opacity;
  51265. if ( material.map ) {
  51266. uniforms.map.value = material.map;
  51267. refreshTransformUniform( material.map, uniforms.mapTransform );
  51268. }
  51269. }
  51270. function refreshUniformsDash( uniforms, material ) {
  51271. uniforms.dashSize.value = material.dashSize;
  51272. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51273. uniforms.scale.value = material.scale;
  51274. }
  51275. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51276. uniforms.diffuse.value.copy( material.color );
  51277. uniforms.opacity.value = material.opacity;
  51278. uniforms.size.value = material.size * pixelRatio;
  51279. uniforms.scale.value = height * 0.5;
  51280. if ( material.map ) {
  51281. uniforms.map.value = material.map;
  51282. refreshTransformUniform( material.map, uniforms.uvTransform );
  51283. }
  51284. if ( material.alphaMap ) {
  51285. uniforms.alphaMap.value = material.alphaMap;
  51286. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51287. }
  51288. if ( material.alphaTest > 0 ) {
  51289. uniforms.alphaTest.value = material.alphaTest;
  51290. }
  51291. }
  51292. function refreshUniformsSprites( uniforms, material ) {
  51293. uniforms.diffuse.value.copy( material.color );
  51294. uniforms.opacity.value = material.opacity;
  51295. uniforms.rotation.value = material.rotation;
  51296. if ( material.map ) {
  51297. uniforms.map.value = material.map;
  51298. refreshTransformUniform( material.map, uniforms.mapTransform );
  51299. }
  51300. if ( material.alphaMap ) {
  51301. uniforms.alphaMap.value = material.alphaMap;
  51302. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51303. }
  51304. if ( material.alphaTest > 0 ) {
  51305. uniforms.alphaTest.value = material.alphaTest;
  51306. }
  51307. }
  51308. function refreshUniformsPhong( uniforms, material ) {
  51309. uniforms.specular.value.copy( material.specular );
  51310. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51311. }
  51312. function refreshUniformsToon( uniforms, material ) {
  51313. if ( material.gradientMap ) {
  51314. uniforms.gradientMap.value = material.gradientMap;
  51315. }
  51316. }
  51317. function refreshUniformsStandard( uniforms, material ) {
  51318. uniforms.metalness.value = material.metalness;
  51319. if ( material.metalnessMap ) {
  51320. uniforms.metalnessMap.value = material.metalnessMap;
  51321. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51322. }
  51323. uniforms.roughness.value = material.roughness;
  51324. if ( material.roughnessMap ) {
  51325. uniforms.roughnessMap.value = material.roughnessMap;
  51326. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51327. }
  51328. if ( material.envMap ) {
  51329. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51330. uniforms.envMapIntensity.value = material.envMapIntensity;
  51331. }
  51332. }
  51333. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51334. uniforms.ior.value = material.ior; // also part of uniforms common
  51335. if ( material.sheen > 0 ) {
  51336. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51337. uniforms.sheenRoughness.value = material.sheenRoughness;
  51338. if ( material.sheenColorMap ) {
  51339. uniforms.sheenColorMap.value = material.sheenColorMap;
  51340. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51341. }
  51342. if ( material.sheenRoughnessMap ) {
  51343. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51344. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51345. }
  51346. }
  51347. if ( material.clearcoat > 0 ) {
  51348. uniforms.clearcoat.value = material.clearcoat;
  51349. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51350. if ( material.clearcoatMap ) {
  51351. uniforms.clearcoatMap.value = material.clearcoatMap;
  51352. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51353. }
  51354. if ( material.clearcoatRoughnessMap ) {
  51355. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51356. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51357. }
  51358. if ( material.clearcoatNormalMap ) {
  51359. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51360. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51361. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51362. if ( material.side === BackSide ) {
  51363. uniforms.clearcoatNormalScale.value.negate();
  51364. }
  51365. }
  51366. }
  51367. if ( material.dispersion > 0 ) {
  51368. uniforms.dispersion.value = material.dispersion;
  51369. }
  51370. if ( material.iridescence > 0 ) {
  51371. uniforms.iridescence.value = material.iridescence;
  51372. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51373. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51374. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51375. if ( material.iridescenceMap ) {
  51376. uniforms.iridescenceMap.value = material.iridescenceMap;
  51377. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51378. }
  51379. if ( material.iridescenceThicknessMap ) {
  51380. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51381. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51382. }
  51383. }
  51384. if ( material.transmission > 0 ) {
  51385. uniforms.transmission.value = material.transmission;
  51386. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51387. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51388. if ( material.transmissionMap ) {
  51389. uniforms.transmissionMap.value = material.transmissionMap;
  51390. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51391. }
  51392. uniforms.thickness.value = material.thickness;
  51393. if ( material.thicknessMap ) {
  51394. uniforms.thicknessMap.value = material.thicknessMap;
  51395. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51396. }
  51397. uniforms.attenuationDistance.value = material.attenuationDistance;
  51398. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51399. }
  51400. if ( material.anisotropy > 0 ) {
  51401. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51402. if ( material.anisotropyMap ) {
  51403. uniforms.anisotropyMap.value = material.anisotropyMap;
  51404. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51405. }
  51406. }
  51407. uniforms.specularIntensity.value = material.specularIntensity;
  51408. uniforms.specularColor.value.copy( material.specularColor );
  51409. if ( material.specularColorMap ) {
  51410. uniforms.specularColorMap.value = material.specularColorMap;
  51411. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  51412. }
  51413. if ( material.specularIntensityMap ) {
  51414. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  51415. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  51416. }
  51417. }
  51418. function refreshUniformsMatcap( uniforms, material ) {
  51419. if ( material.matcap ) {
  51420. uniforms.matcap.value = material.matcap;
  51421. }
  51422. }
  51423. function refreshUniformsDistance( uniforms, material ) {
  51424. const light = properties.get( material ).light;
  51425. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  51426. uniforms.nearDistance.value = light.shadow.camera.near;
  51427. uniforms.farDistance.value = light.shadow.camera.far;
  51428. }
  51429. return {
  51430. refreshFogUniforms: refreshFogUniforms,
  51431. refreshMaterialUniforms: refreshMaterialUniforms
  51432. };
  51433. }
  51434. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  51435. let buffers = {};
  51436. let updateList = {};
  51437. let allocatedBindingPoints = [];
  51438. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  51439. function bind( uniformsGroup, program ) {
  51440. const webglProgram = program.program;
  51441. state.uniformBlockBinding( uniformsGroup, webglProgram );
  51442. }
  51443. function update( uniformsGroup, program ) {
  51444. let buffer = buffers[ uniformsGroup.id ];
  51445. if ( buffer === undefined ) {
  51446. prepareUniformsGroup( uniformsGroup );
  51447. buffer = createBuffer( uniformsGroup );
  51448. buffers[ uniformsGroup.id ] = buffer;
  51449. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  51450. }
  51451. // ensure to update the binding points/block indices mapping for this program
  51452. const webglProgram = program.program;
  51453. state.updateUBOMapping( uniformsGroup, webglProgram );
  51454. // update UBO once per frame
  51455. const frame = info.render.frame;
  51456. if ( updateList[ uniformsGroup.id ] !== frame ) {
  51457. updateBufferData( uniformsGroup );
  51458. updateList[ uniformsGroup.id ] = frame;
  51459. }
  51460. }
  51461. function createBuffer( uniformsGroup ) {
  51462. // the setup of an UBO is independent of a particular shader program but global
  51463. const bindingPointIndex = allocateBindingPointIndex();
  51464. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  51465. const buffer = gl.createBuffer();
  51466. const size = uniformsGroup.__size;
  51467. const usage = uniformsGroup.usage;
  51468. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51469. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  51470. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51471. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  51472. return buffer;
  51473. }
  51474. function allocateBindingPointIndex() {
  51475. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  51476. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  51477. allocatedBindingPoints.push( i );
  51478. return i;
  51479. }
  51480. }
  51481. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  51482. return 0;
  51483. }
  51484. function updateBufferData( uniformsGroup ) {
  51485. const buffer = buffers[ uniformsGroup.id ];
  51486. const uniforms = uniformsGroup.uniforms;
  51487. const cache = uniformsGroup.__cache;
  51488. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51489. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  51490. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51491. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51492. const uniform = uniformArray[ j ];
  51493. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  51494. const offset = uniform.__offset;
  51495. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51496. let arrayOffset = 0;
  51497. for ( let k = 0; k < values.length; k ++ ) {
  51498. const value = values[ k ];
  51499. const info = getUniformSize( value );
  51500. // TODO add integer and struct support
  51501. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51502. uniform.__data[ 0 ] = value;
  51503. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  51504. } else if ( value.isMatrix3 ) {
  51505. // manually converting 3x3 to 3x4
  51506. uniform.__data[ 0 ] = value.elements[ 0 ];
  51507. uniform.__data[ 1 ] = value.elements[ 1 ];
  51508. uniform.__data[ 2 ] = value.elements[ 2 ];
  51509. uniform.__data[ 3 ] = 0;
  51510. uniform.__data[ 4 ] = value.elements[ 3 ];
  51511. uniform.__data[ 5 ] = value.elements[ 4 ];
  51512. uniform.__data[ 6 ] = value.elements[ 5 ];
  51513. uniform.__data[ 7 ] = 0;
  51514. uniform.__data[ 8 ] = value.elements[ 6 ];
  51515. uniform.__data[ 9 ] = value.elements[ 7 ];
  51516. uniform.__data[ 10 ] = value.elements[ 8 ];
  51517. uniform.__data[ 11 ] = 0;
  51518. } else {
  51519. value.toArray( uniform.__data, arrayOffset );
  51520. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  51521. }
  51522. }
  51523. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  51524. }
  51525. }
  51526. }
  51527. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51528. }
  51529. function hasUniformChanged( uniform, index, indexArray, cache ) {
  51530. const value = uniform.value;
  51531. const indexString = index + '_' + indexArray;
  51532. if ( cache[ indexString ] === undefined ) {
  51533. // cache entry does not exist so far
  51534. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51535. cache[ indexString ] = value;
  51536. } else {
  51537. cache[ indexString ] = value.clone();
  51538. }
  51539. return true;
  51540. } else {
  51541. const cachedObject = cache[ indexString ];
  51542. // compare current value with cached entry
  51543. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51544. if ( cachedObject !== value ) {
  51545. cache[ indexString ] = value;
  51546. return true;
  51547. }
  51548. } else {
  51549. if ( cachedObject.equals( value ) === false ) {
  51550. cachedObject.copy( value );
  51551. return true;
  51552. }
  51553. }
  51554. }
  51555. return false;
  51556. }
  51557. function prepareUniformsGroup( uniformsGroup ) {
  51558. // determine total buffer size according to the STD140 layout
  51559. // Hint: STD140 is the only supported layout in WebGL 2
  51560. const uniforms = uniformsGroup.uniforms;
  51561. let offset = 0; // global buffer offset in bytes
  51562. const chunkSize = 16; // size of a chunk in bytes
  51563. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  51564. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51565. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51566. const uniform = uniformArray[ j ];
  51567. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51568. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  51569. const value = values[ k ];
  51570. const info = getUniformSize( value );
  51571. const chunkOffset = offset % chunkSize; // offset in the current chunk
  51572. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  51573. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  51574. offset += chunkPadding;
  51575. // Check for chunk overflow
  51576. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  51577. // Add padding and adjust offset
  51578. offset += ( chunkSize - chunkStart );
  51579. }
  51580. // the following two properties will be used for partial buffer updates
  51581. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  51582. uniform.__offset = offset;
  51583. // Update the global offset
  51584. offset += info.storage;
  51585. }
  51586. }
  51587. }
  51588. // ensure correct final padding
  51589. const chunkOffset = offset % chunkSize;
  51590. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  51591. //
  51592. uniformsGroup.__size = offset;
  51593. uniformsGroup.__cache = {};
  51594. return this;
  51595. }
  51596. function getUniformSize( value ) {
  51597. const info = {
  51598. boundary: 0, // bytes
  51599. storage: 0 // bytes
  51600. };
  51601. // determine sizes according to STD140
  51602. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51603. // float/int/bool
  51604. info.boundary = 4;
  51605. info.storage = 4;
  51606. } else if ( value.isVector2 ) {
  51607. // vec2
  51608. info.boundary = 8;
  51609. info.storage = 8;
  51610. } else if ( value.isVector3 || value.isColor ) {
  51611. // vec3
  51612. info.boundary = 16;
  51613. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  51614. } else if ( value.isVector4 ) {
  51615. // vec4
  51616. info.boundary = 16;
  51617. info.storage = 16;
  51618. } else if ( value.isMatrix3 ) {
  51619. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  51620. info.boundary = 48;
  51621. info.storage = 48;
  51622. } else if ( value.isMatrix4 ) {
  51623. // mat4
  51624. info.boundary = 64;
  51625. info.storage = 64;
  51626. } else if ( value.isTexture ) {
  51627. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  51628. } else {
  51629. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  51630. }
  51631. return info;
  51632. }
  51633. function onUniformsGroupsDispose( event ) {
  51634. const uniformsGroup = event.target;
  51635. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  51636. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  51637. allocatedBindingPoints.splice( index, 1 );
  51638. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  51639. delete buffers[ uniformsGroup.id ];
  51640. delete updateList[ uniformsGroup.id ];
  51641. }
  51642. function dispose() {
  51643. for ( const id in buffers ) {
  51644. gl.deleteBuffer( buffers[ id ] );
  51645. }
  51646. allocatedBindingPoints = [];
  51647. buffers = {};
  51648. updateList = {};
  51649. }
  51650. return {
  51651. bind: bind,
  51652. update: update,
  51653. dispose: dispose
  51654. };
  51655. }
  51656. /**
  51657. * This renderer uses WebGL 2 to display scenes.
  51658. *
  51659. * WebGL 1 is not supported since `r163`.
  51660. */
  51661. class WebGLRenderer {
  51662. /**
  51663. * Constructs a new WebGL renderer.
  51664. *
  51665. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  51666. */
  51667. constructor( parameters = {} ) {
  51668. const {
  51669. canvas = createCanvasElement(),
  51670. context = null,
  51671. depth = true,
  51672. stencil = false,
  51673. alpha = false,
  51674. antialias = false,
  51675. premultipliedAlpha = true,
  51676. preserveDrawingBuffer = false,
  51677. powerPreference = 'default',
  51678. failIfMajorPerformanceCaveat = false,
  51679. reversedDepthBuffer = false,
  51680. } = parameters;
  51681. /**
  51682. * This flag can be used for type testing.
  51683. *
  51684. * @type {boolean}
  51685. * @readonly
  51686. * @default true
  51687. */
  51688. this.isWebGLRenderer = true;
  51689. let _alpha;
  51690. if ( context !== null ) {
  51691. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  51692. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  51693. }
  51694. _alpha = context.getContextAttributes().alpha;
  51695. } else {
  51696. _alpha = alpha;
  51697. }
  51698. const uintClearColor = new Uint32Array( 4 );
  51699. const intClearColor = new Int32Array( 4 );
  51700. let currentRenderList = null;
  51701. let currentRenderState = null;
  51702. // render() can be called from within a callback triggered by another render.
  51703. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  51704. const renderListStack = [];
  51705. const renderStateStack = [];
  51706. // public properties
  51707. /**
  51708. * A canvas where the renderer draws its output.This is automatically created by the renderer
  51709. * in the constructor (if not provided already); you just need to add it to your page like so:
  51710. * ```js
  51711. * document.body.appendChild( renderer.domElement );
  51712. * ```
  51713. *
  51714. * @type {HTMLCanvasElement|OffscreenCanvas}
  51715. */
  51716. this.domElement = canvas;
  51717. /**
  51718. * A object with debug configuration settings.
  51719. *
  51720. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  51721. * checked for errors during compilation and linkage process. It may be useful to disable
  51722. * this check in production for performance gain. It is strongly recommended to keep these
  51723. * checks enabled during development. If the shader does not compile and link - it will not
  51724. * work and associated material will not render.
  51725. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  51726. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  51727. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  51728. * Assigning a custom function disables the default error reporting.
  51729. *
  51730. * @type {Object}
  51731. */
  51732. this.debug = {
  51733. /**
  51734. * Enables error checking and reporting when shader programs are being compiled.
  51735. * @type {boolean}
  51736. */
  51737. checkShaderErrors: true,
  51738. /**
  51739. * Callback for custom error reporting.
  51740. * @type {?Function}
  51741. */
  51742. onShaderError: null
  51743. };
  51744. // clearing
  51745. /**
  51746. * Whether the renderer should automatically clear its output before rendering a frame or not.
  51747. *
  51748. * @type {boolean}
  51749. * @default true
  51750. */
  51751. this.autoClear = true;
  51752. /**
  51753. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51754. * the color buffer or not.
  51755. *
  51756. * @type {boolean}
  51757. * @default true
  51758. */
  51759. this.autoClearColor = true;
  51760. /**
  51761. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51762. * the depth buffer or not.
  51763. *
  51764. * @type {boolean}
  51765. * @default true
  51766. */
  51767. this.autoClearDepth = true;
  51768. /**
  51769. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  51770. * the stencil buffer or not.
  51771. *
  51772. * @type {boolean}
  51773. * @default true
  51774. */
  51775. this.autoClearStencil = true;
  51776. // scene graph
  51777. /**
  51778. * Whether the renderer should sort objects or not.
  51779. *
  51780. * Note: Sorting is used to attempt to properly render objects that have some
  51781. * degree of transparency. By definition, sorting objects may not work in all
  51782. * cases. Depending on the needs of application, it may be necessary to turn
  51783. * off sorting and use other methods to deal with transparency rendering e.g.
  51784. * manually determining each object's rendering order.
  51785. *
  51786. * @type {boolean}
  51787. * @default true
  51788. */
  51789. this.sortObjects = true;
  51790. // user-defined clipping
  51791. /**
  51792. * User-defined clipping planes specified in world space. These planes apply globally.
  51793. * Points in space whose dot product with the plane is negative are cut away.
  51794. *
  51795. * @type {Array<Plane>}
  51796. */
  51797. this.clippingPlanes = [];
  51798. /**
  51799. * Whether the renderer respects object-level clipping planes or not.
  51800. *
  51801. * @type {boolean}
  51802. * @default false
  51803. */
  51804. this.localClippingEnabled = false;
  51805. // tone mapping
  51806. /**
  51807. * The tone mapping technique of the renderer.
  51808. *
  51809. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  51810. * @default NoToneMapping
  51811. */
  51812. this.toneMapping = NoToneMapping;
  51813. /**
  51814. * Exposure level of tone mapping.
  51815. *
  51816. * @type {number}
  51817. * @default 1
  51818. */
  51819. this.toneMappingExposure = 1.0;
  51820. // transmission
  51821. /**
  51822. * The normalized resolution scale for the transmission render target, measured in percentage
  51823. * of viewport dimensions. Lowering this value can result in significant performance improvements
  51824. * when using {@link MeshPhysicalMaterial#transmission}.
  51825. *
  51826. * @type {number}
  51827. * @default 1
  51828. */
  51829. this.transmissionResolutionScale = 1.0;
  51830. // internal properties
  51831. const _this = this;
  51832. let _isContextLost = false;
  51833. // internal state cache
  51834. this._outputColorSpace = SRGBColorSpace;
  51835. let _currentActiveCubeFace = 0;
  51836. let _currentActiveMipmapLevel = 0;
  51837. let _currentRenderTarget = null;
  51838. let _currentMaterialId = -1;
  51839. let _currentCamera = null;
  51840. const _currentViewport = new Vector4();
  51841. const _currentScissor = new Vector4();
  51842. let _currentScissorTest = null;
  51843. const _currentClearColor = new Color( 0x000000 );
  51844. let _currentClearAlpha = 0;
  51845. //
  51846. let _width = canvas.width;
  51847. let _height = canvas.height;
  51848. let _pixelRatio = 1;
  51849. let _opaqueSort = null;
  51850. let _transparentSort = null;
  51851. const _viewport = new Vector4( 0, 0, _width, _height );
  51852. const _scissor = new Vector4( 0, 0, _width, _height );
  51853. let _scissorTest = false;
  51854. // frustum
  51855. const _frustum = new Frustum();
  51856. // clipping
  51857. let _clippingEnabled = false;
  51858. let _localClippingEnabled = false;
  51859. // camera matrices cache
  51860. const _projScreenMatrix = new Matrix4();
  51861. const _vector3 = new Vector3();
  51862. const _vector4 = new Vector4();
  51863. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  51864. let _renderBackground = false;
  51865. function getTargetPixelRatio() {
  51866. return _currentRenderTarget === null ? _pixelRatio : 1;
  51867. }
  51868. // initialize
  51869. let _gl = context;
  51870. function getContext( contextName, contextAttributes ) {
  51871. return canvas.getContext( contextName, contextAttributes );
  51872. }
  51873. try {
  51874. const contextAttributes = {
  51875. alpha: true,
  51876. depth,
  51877. stencil,
  51878. antialias,
  51879. premultipliedAlpha,
  51880. preserveDrawingBuffer,
  51881. powerPreference,
  51882. failIfMajorPerformanceCaveat,
  51883. };
  51884. // OffscreenCanvas does not have setAttribute, see #22811
  51885. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  51886. // event listeners must be registered before WebGL context is created, see #12753
  51887. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  51888. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  51889. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  51890. if ( _gl === null ) {
  51891. const contextName = 'webgl2';
  51892. _gl = getContext( contextName, contextAttributes );
  51893. if ( _gl === null ) {
  51894. if ( getContext( contextName ) ) {
  51895. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  51896. } else {
  51897. throw new Error( 'Error creating WebGL context.' );
  51898. }
  51899. }
  51900. }
  51901. } catch ( error ) {
  51902. error( 'WebGLRenderer: ' + error.message );
  51903. throw error;
  51904. }
  51905. let extensions, capabilities, state, info;
  51906. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  51907. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  51908. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  51909. let utils, bindingStates, uniformsGroups;
  51910. function initGLContext() {
  51911. extensions = new WebGLExtensions( _gl );
  51912. extensions.init();
  51913. utils = new WebGLUtils( _gl, extensions );
  51914. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  51915. state = new WebGLState( _gl, extensions );
  51916. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  51917. state.buffers.depth.setReversed( true );
  51918. }
  51919. info = new WebGLInfo( _gl );
  51920. properties = new WebGLProperties();
  51921. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  51922. cubemaps = new WebGLCubeMaps( _this );
  51923. cubeuvmaps = new WebGLCubeUVMaps( _this );
  51924. attributes = new WebGLAttributes( _gl );
  51925. bindingStates = new WebGLBindingStates( _gl, attributes );
  51926. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  51927. objects = new WebGLObjects( _gl, geometries, attributes, info );
  51928. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  51929. clipping = new WebGLClipping( properties );
  51930. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  51931. materials = new WebGLMaterials( _this, properties );
  51932. renderLists = new WebGLRenderLists();
  51933. renderStates = new WebGLRenderStates( extensions );
  51934. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  51935. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  51936. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  51937. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  51938. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  51939. info.programs = programCache.programs;
  51940. /**
  51941. * Holds details about the capabilities of the current rendering context.
  51942. *
  51943. * @name WebGLRenderer#capabilities
  51944. * @type {WebGLRenderer~Capabilities}
  51945. */
  51946. _this.capabilities = capabilities;
  51947. /**
  51948. * Provides methods for retrieving and testing WebGL extensions.
  51949. *
  51950. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  51951. * and return the extension object if available.
  51952. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  51953. *
  51954. * @name WebGLRenderer#extensions
  51955. * @type {Object}
  51956. */
  51957. _this.extensions = extensions;
  51958. /**
  51959. * Used to track properties of other objects like native WebGL objects.
  51960. *
  51961. * @name WebGLRenderer#properties
  51962. * @type {Object}
  51963. */
  51964. _this.properties = properties;
  51965. /**
  51966. * Manages the render lists of the renderer.
  51967. *
  51968. * @name WebGLRenderer#renderLists
  51969. * @type {Object}
  51970. */
  51971. _this.renderLists = renderLists;
  51972. /**
  51973. * Interface for managing shadows.
  51974. *
  51975. * @name WebGLRenderer#shadowMap
  51976. * @type {WebGLRenderer~ShadowMap}
  51977. */
  51978. _this.shadowMap = shadowMap;
  51979. /**
  51980. * Interface for managing the WebGL state.
  51981. *
  51982. * @name WebGLRenderer#state
  51983. * @type {Object}
  51984. */
  51985. _this.state = state;
  51986. /**
  51987. * Holds a series of statistical information about the GPU memory
  51988. * and the rendering process. Useful for debugging and monitoring.
  51989. *
  51990. * By default these data are reset at each render call but when having
  51991. * multiple render passes per frame (e.g. when using post processing) it can
  51992. * be preferred to reset with a custom pattern. First, set `autoReset` to
  51993. * `false`.
  51994. * ```js
  51995. * renderer.info.autoReset = false;
  51996. * ```
  51997. * Call `reset()` whenever you have finished to render a single frame.
  51998. * ```js
  51999. * renderer.info.reset();
  52000. * ```
  52001. *
  52002. * @name WebGLRenderer#info
  52003. * @type {WebGLRenderer~Info}
  52004. */
  52005. _this.info = info;
  52006. }
  52007. initGLContext();
  52008. // xr
  52009. const xr = new WebXRManager( _this, _gl );
  52010. /**
  52011. * A reference to the XR manager.
  52012. *
  52013. * @type {WebXRManager}
  52014. */
  52015. this.xr = xr;
  52016. /**
  52017. * Returns the rendering context.
  52018. *
  52019. * @return {WebGL2RenderingContext} The rendering context.
  52020. */
  52021. this.getContext = function () {
  52022. return _gl;
  52023. };
  52024. /**
  52025. * Returns the rendering context attributes.
  52026. *
  52027. * @return {WebGLContextAttributes} The rendering context attributes.
  52028. */
  52029. this.getContextAttributes = function () {
  52030. return _gl.getContextAttributes();
  52031. };
  52032. /**
  52033. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52034. */
  52035. this.forceContextLoss = function () {
  52036. const extension = extensions.get( 'WEBGL_lose_context' );
  52037. if ( extension ) extension.loseContext();
  52038. };
  52039. /**
  52040. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52041. */
  52042. this.forceContextRestore = function () {
  52043. const extension = extensions.get( 'WEBGL_lose_context' );
  52044. if ( extension ) extension.restoreContext();
  52045. };
  52046. /**
  52047. * Returns the pixel ratio.
  52048. *
  52049. * @return {number} The pixel ratio.
  52050. */
  52051. this.getPixelRatio = function () {
  52052. return _pixelRatio;
  52053. };
  52054. /**
  52055. * Sets the given pixel ratio and resizes the canvas if necessary.
  52056. *
  52057. * @param {number} value - The pixel ratio.
  52058. */
  52059. this.setPixelRatio = function ( value ) {
  52060. if ( value === undefined ) return;
  52061. _pixelRatio = value;
  52062. this.setSize( _width, _height, false );
  52063. };
  52064. /**
  52065. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52066. *
  52067. * @param {Vector2} target - The method writes the result in this target object.
  52068. * @return {Vector2} The renderer's size in logical pixels.
  52069. */
  52070. this.getSize = function ( target ) {
  52071. return target.set( _width, _height );
  52072. };
  52073. /**
  52074. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52075. * into account, and also sets the viewport to fit that size, starting in (0,
  52076. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52077. *
  52078. * @param {number} width - The width in logical pixels.
  52079. * @param {number} height - The height in logical pixels.
  52080. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52081. */
  52082. this.setSize = function ( width, height, updateStyle = true ) {
  52083. if ( xr.isPresenting ) {
  52084. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52085. return;
  52086. }
  52087. _width = width;
  52088. _height = height;
  52089. canvas.width = Math.floor( width * _pixelRatio );
  52090. canvas.height = Math.floor( height * _pixelRatio );
  52091. if ( updateStyle === true ) {
  52092. canvas.style.width = width + 'px';
  52093. canvas.style.height = height + 'px';
  52094. }
  52095. this.setViewport( 0, 0, width, height );
  52096. };
  52097. /**
  52098. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52099. *
  52100. * @param {Vector2} target - The method writes the result in this target object.
  52101. * @return {Vector2} The drawing buffer size.
  52102. */
  52103. this.getDrawingBufferSize = function ( target ) {
  52104. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52105. };
  52106. /**
  52107. * This method allows to define the drawing buffer size by specifying
  52108. * width, height and pixel ratio all at once. The size of the drawing
  52109. * buffer is computed with this formula:
  52110. * ```js
  52111. * size.x = width * pixelRatio;
  52112. * size.y = height * pixelRatio;
  52113. * ```
  52114. *
  52115. * @param {number} width - The width in logical pixels.
  52116. * @param {number} height - The height in logical pixels.
  52117. * @param {number} pixelRatio - The pixel ratio.
  52118. */
  52119. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52120. _width = width;
  52121. _height = height;
  52122. _pixelRatio = pixelRatio;
  52123. canvas.width = Math.floor( width * pixelRatio );
  52124. canvas.height = Math.floor( height * pixelRatio );
  52125. this.setViewport( 0, 0, width, height );
  52126. };
  52127. /**
  52128. * Returns the current viewport definition.
  52129. *
  52130. * @param {Vector2} target - The method writes the result in this target object.
  52131. * @return {Vector2} The current viewport definition.
  52132. */
  52133. this.getCurrentViewport = function ( target ) {
  52134. return target.copy( _currentViewport );
  52135. };
  52136. /**
  52137. * Returns the viewport definition.
  52138. *
  52139. * @param {Vector4} target - The method writes the result in this target object.
  52140. * @return {Vector4} The viewport definition.
  52141. */
  52142. this.getViewport = function ( target ) {
  52143. return target.copy( _viewport );
  52144. };
  52145. /**
  52146. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52147. *
  52148. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52149. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52150. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52151. * @param {number} width - The width of the viewport in logical pixel unit.
  52152. * @param {number} height - The height of the viewport in logical pixel unit.
  52153. */
  52154. this.setViewport = function ( x, y, width, height ) {
  52155. if ( x.isVector4 ) {
  52156. _viewport.set( x.x, x.y, x.z, x.w );
  52157. } else {
  52158. _viewport.set( x, y, width, height );
  52159. }
  52160. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52161. };
  52162. /**
  52163. * Returns the scissor region.
  52164. *
  52165. * @param {Vector4} target - The method writes the result in this target object.
  52166. * @return {Vector4} The scissor region.
  52167. */
  52168. this.getScissor = function ( target ) {
  52169. return target.copy( _scissor );
  52170. };
  52171. /**
  52172. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52173. *
  52174. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52175. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52176. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52177. * @param {number} width - The width of the scissor region in logical pixel unit.
  52178. * @param {number} height - The height of the scissor region in logical pixel unit.
  52179. */
  52180. this.setScissor = function ( x, y, width, height ) {
  52181. if ( x.isVector4 ) {
  52182. _scissor.set( x.x, x.y, x.z, x.w );
  52183. } else {
  52184. _scissor.set( x, y, width, height );
  52185. }
  52186. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52187. };
  52188. /**
  52189. * Returns `true` if the scissor test is enabled.
  52190. *
  52191. * @return {boolean} Whether the scissor test is enabled or not.
  52192. */
  52193. this.getScissorTest = function () {
  52194. return _scissorTest;
  52195. };
  52196. /**
  52197. * Enable or disable the scissor test. When this is enabled, only the pixels
  52198. * within the defined scissor area will be affected by further renderer
  52199. * actions.
  52200. *
  52201. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52202. */
  52203. this.setScissorTest = function ( boolean ) {
  52204. state.setScissorTest( _scissorTest = boolean );
  52205. };
  52206. /**
  52207. * Sets a custom opaque sort function for the render lists. Pass `null`
  52208. * to use the default `painterSortStable` function.
  52209. *
  52210. * @param {?Function} method - The opaque sort function.
  52211. */
  52212. this.setOpaqueSort = function ( method ) {
  52213. _opaqueSort = method;
  52214. };
  52215. /**
  52216. * Sets a custom transparent sort function for the render lists. Pass `null`
  52217. * to use the default `reversePainterSortStable` function.
  52218. *
  52219. * @param {?Function} method - The opaque sort function.
  52220. */
  52221. this.setTransparentSort = function ( method ) {
  52222. _transparentSort = method;
  52223. };
  52224. // Clearing
  52225. /**
  52226. * Returns the clear color.
  52227. *
  52228. * @param {Color} target - The method writes the result in this target object.
  52229. * @return {Color} The clear color.
  52230. */
  52231. this.getClearColor = function ( target ) {
  52232. return target.copy( background.getClearColor() );
  52233. };
  52234. /**
  52235. * Sets the clear color and alpha.
  52236. *
  52237. * @param {Color} color - The clear color.
  52238. * @param {number} [alpha=1] - The clear alpha.
  52239. */
  52240. this.setClearColor = function () {
  52241. background.setClearColor( ...arguments );
  52242. };
  52243. /**
  52244. * Returns the clear alpha. Ranges within `[0,1]`.
  52245. *
  52246. * @return {number} The clear alpha.
  52247. */
  52248. this.getClearAlpha = function () {
  52249. return background.getClearAlpha();
  52250. };
  52251. /**
  52252. * Sets the clear alpha.
  52253. *
  52254. * @param {number} alpha - The clear alpha.
  52255. */
  52256. this.setClearAlpha = function () {
  52257. background.setClearAlpha( ...arguments );
  52258. };
  52259. /**
  52260. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52261. * This method initializes the buffers to the current clear color values.
  52262. *
  52263. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52264. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52265. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52266. */
  52267. this.clear = function ( color = true, depth = true, stencil = true ) {
  52268. let bits = 0;
  52269. if ( color ) {
  52270. // check if we're trying to clear an integer target
  52271. let isIntegerFormat = false;
  52272. if ( _currentRenderTarget !== null ) {
  52273. const targetFormat = _currentRenderTarget.texture.format;
  52274. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  52275. targetFormat === RGIntegerFormat ||
  52276. targetFormat === RedIntegerFormat;
  52277. }
  52278. // use the appropriate clear functions to clear the target if it's a signed
  52279. // or unsigned integer target
  52280. if ( isIntegerFormat ) {
  52281. const targetType = _currentRenderTarget.texture.type;
  52282. const isUnsignedType = targetType === UnsignedByteType ||
  52283. targetType === UnsignedIntType ||
  52284. targetType === UnsignedShortType ||
  52285. targetType === UnsignedInt248Type ||
  52286. targetType === UnsignedShort4444Type ||
  52287. targetType === UnsignedShort5551Type;
  52288. const clearColor = background.getClearColor();
  52289. const a = background.getClearAlpha();
  52290. const r = clearColor.r;
  52291. const g = clearColor.g;
  52292. const b = clearColor.b;
  52293. if ( isUnsignedType ) {
  52294. uintClearColor[ 0 ] = r;
  52295. uintClearColor[ 1 ] = g;
  52296. uintClearColor[ 2 ] = b;
  52297. uintClearColor[ 3 ] = a;
  52298. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52299. } else {
  52300. intClearColor[ 0 ] = r;
  52301. intClearColor[ 1 ] = g;
  52302. intClearColor[ 2 ] = b;
  52303. intClearColor[ 3 ] = a;
  52304. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52305. }
  52306. } else {
  52307. bits |= _gl.COLOR_BUFFER_BIT;
  52308. }
  52309. }
  52310. if ( depth ) {
  52311. bits |= _gl.DEPTH_BUFFER_BIT;
  52312. }
  52313. if ( stencil ) {
  52314. bits |= _gl.STENCIL_BUFFER_BIT;
  52315. this.state.buffers.stencil.setMask( 0xffffffff );
  52316. }
  52317. _gl.clear( bits );
  52318. };
  52319. /**
  52320. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52321. */
  52322. this.clearColor = function () {
  52323. this.clear( true, false, false );
  52324. };
  52325. /**
  52326. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52327. */
  52328. this.clearDepth = function () {
  52329. this.clear( false, true, false );
  52330. };
  52331. /**
  52332. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  52333. */
  52334. this.clearStencil = function () {
  52335. this.clear( false, false, true );
  52336. };
  52337. /**
  52338. * Frees the GPU-related resources allocated by this instance. Call this
  52339. * method whenever this instance is no longer used in your app.
  52340. */
  52341. this.dispose = function () {
  52342. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  52343. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  52344. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52345. background.dispose();
  52346. renderLists.dispose();
  52347. renderStates.dispose();
  52348. properties.dispose();
  52349. cubemaps.dispose();
  52350. cubeuvmaps.dispose();
  52351. objects.dispose();
  52352. bindingStates.dispose();
  52353. uniformsGroups.dispose();
  52354. programCache.dispose();
  52355. xr.dispose();
  52356. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  52357. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  52358. animation.stop();
  52359. };
  52360. // Events
  52361. function onContextLost( event ) {
  52362. event.preventDefault();
  52363. log( 'WebGLRenderer: Context Lost.' );
  52364. _isContextLost = true;
  52365. }
  52366. function onContextRestore( /* event */ ) {
  52367. log( 'WebGLRenderer: Context Restored.' );
  52368. _isContextLost = false;
  52369. const infoAutoReset = info.autoReset;
  52370. const shadowMapEnabled = shadowMap.enabled;
  52371. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  52372. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  52373. const shadowMapType = shadowMap.type;
  52374. initGLContext();
  52375. info.autoReset = infoAutoReset;
  52376. shadowMap.enabled = shadowMapEnabled;
  52377. shadowMap.autoUpdate = shadowMapAutoUpdate;
  52378. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  52379. shadowMap.type = shadowMapType;
  52380. }
  52381. function onContextCreationError( event ) {
  52382. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  52383. }
  52384. function onMaterialDispose( event ) {
  52385. const material = event.target;
  52386. material.removeEventListener( 'dispose', onMaterialDispose );
  52387. deallocateMaterial( material );
  52388. }
  52389. // Buffer deallocation
  52390. function deallocateMaterial( material ) {
  52391. releaseMaterialProgramReferences( material );
  52392. properties.remove( material );
  52393. }
  52394. function releaseMaterialProgramReferences( material ) {
  52395. const programs = properties.get( material ).programs;
  52396. if ( programs !== undefined ) {
  52397. programs.forEach( function ( program ) {
  52398. programCache.releaseProgram( program );
  52399. } );
  52400. if ( material.isShaderMaterial ) {
  52401. programCache.releaseShaderCache( material );
  52402. }
  52403. }
  52404. }
  52405. // Buffer rendering
  52406. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  52407. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  52408. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  52409. const program = setProgram( camera, scene, geometry, material, object );
  52410. state.setMaterial( material, frontFaceCW );
  52411. //
  52412. let index = geometry.index;
  52413. let rangeFactor = 1;
  52414. if ( material.wireframe === true ) {
  52415. index = geometries.getWireframeAttribute( geometry );
  52416. if ( index === undefined ) return;
  52417. rangeFactor = 2;
  52418. }
  52419. //
  52420. const drawRange = geometry.drawRange;
  52421. const position = geometry.attributes.position;
  52422. let drawStart = drawRange.start * rangeFactor;
  52423. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  52424. if ( group !== null ) {
  52425. drawStart = Math.max( drawStart, group.start * rangeFactor );
  52426. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  52427. }
  52428. if ( index !== null ) {
  52429. drawStart = Math.max( drawStart, 0 );
  52430. drawEnd = Math.min( drawEnd, index.count );
  52431. } else if ( position !== undefined && position !== null ) {
  52432. drawStart = Math.max( drawStart, 0 );
  52433. drawEnd = Math.min( drawEnd, position.count );
  52434. }
  52435. const drawCount = drawEnd - drawStart;
  52436. if ( drawCount < 0 || drawCount === Infinity ) return;
  52437. //
  52438. bindingStates.setup( object, material, program, geometry, index );
  52439. let attribute;
  52440. let renderer = bufferRenderer;
  52441. if ( index !== null ) {
  52442. attribute = attributes.get( index );
  52443. renderer = indexedBufferRenderer;
  52444. renderer.setIndex( attribute );
  52445. }
  52446. //
  52447. if ( object.isMesh ) {
  52448. if ( material.wireframe === true ) {
  52449. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  52450. renderer.setMode( _gl.LINES );
  52451. } else {
  52452. renderer.setMode( _gl.TRIANGLES );
  52453. }
  52454. } else if ( object.isLine ) {
  52455. let lineWidth = material.linewidth;
  52456. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  52457. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  52458. if ( object.isLineSegments ) {
  52459. renderer.setMode( _gl.LINES );
  52460. } else if ( object.isLineLoop ) {
  52461. renderer.setMode( _gl.LINE_LOOP );
  52462. } else {
  52463. renderer.setMode( _gl.LINE_STRIP );
  52464. }
  52465. } else if ( object.isPoints ) {
  52466. renderer.setMode( _gl.POINTS );
  52467. } else if ( object.isSprite ) {
  52468. renderer.setMode( _gl.TRIANGLES );
  52469. }
  52470. if ( object.isBatchedMesh ) {
  52471. if ( object._multiDrawInstances !== null ) {
  52472. // @deprecated, r174
  52473. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52474. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  52475. } else {
  52476. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  52477. const starts = object._multiDrawStarts;
  52478. const counts = object._multiDrawCounts;
  52479. const drawCount = object._multiDrawCount;
  52480. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  52481. const uniforms = properties.get( material ).currentProgram.getUniforms();
  52482. for ( let i = 0; i < drawCount; i ++ ) {
  52483. uniforms.setValue( _gl, '_gl_DrawID', i );
  52484. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  52485. }
  52486. } else {
  52487. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  52488. }
  52489. }
  52490. } else if ( object.isInstancedMesh ) {
  52491. renderer.renderInstances( drawStart, drawCount, object.count );
  52492. } else if ( geometry.isInstancedBufferGeometry ) {
  52493. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  52494. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  52495. renderer.renderInstances( drawStart, drawCount, instanceCount );
  52496. } else {
  52497. renderer.render( drawStart, drawCount );
  52498. }
  52499. };
  52500. // Compile
  52501. function prepareMaterial( material, scene, object ) {
  52502. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52503. material.side = BackSide;
  52504. material.needsUpdate = true;
  52505. getProgram( material, scene, object );
  52506. material.side = FrontSide;
  52507. material.needsUpdate = true;
  52508. getProgram( material, scene, object );
  52509. material.side = DoubleSide;
  52510. } else {
  52511. getProgram( material, scene, object );
  52512. }
  52513. }
  52514. /**
  52515. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  52516. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  52517. * optional parameter for applying the target scene.
  52518. *
  52519. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  52520. *
  52521. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52522. * @param {Camera} camera - The camera.
  52523. * @param {?Scene} [targetScene=null] - The target scene.
  52524. * @return {Set<Material>} The precompiled materials.
  52525. */
  52526. this.compile = function ( scene, camera, targetScene = null ) {
  52527. if ( targetScene === null ) targetScene = scene;
  52528. currentRenderState = renderStates.get( targetScene );
  52529. currentRenderState.init( camera );
  52530. renderStateStack.push( currentRenderState );
  52531. // gather lights from both the target scene and the new object that will be added to the scene.
  52532. targetScene.traverseVisible( function ( object ) {
  52533. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52534. currentRenderState.pushLight( object );
  52535. if ( object.castShadow ) {
  52536. currentRenderState.pushShadow( object );
  52537. }
  52538. }
  52539. } );
  52540. if ( scene !== targetScene ) {
  52541. scene.traverseVisible( function ( object ) {
  52542. if ( object.isLight && object.layers.test( camera.layers ) ) {
  52543. currentRenderState.pushLight( object );
  52544. if ( object.castShadow ) {
  52545. currentRenderState.pushShadow( object );
  52546. }
  52547. }
  52548. } );
  52549. }
  52550. currentRenderState.setupLights();
  52551. // Only initialize materials in the new scene, not the targetScene.
  52552. const materials = new Set();
  52553. scene.traverse( function ( object ) {
  52554. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  52555. return;
  52556. }
  52557. const material = object.material;
  52558. if ( material ) {
  52559. if ( Array.isArray( material ) ) {
  52560. for ( let i = 0; i < material.length; i ++ ) {
  52561. const material2 = material[ i ];
  52562. prepareMaterial( material2, targetScene, object );
  52563. materials.add( material2 );
  52564. }
  52565. } else {
  52566. prepareMaterial( material, targetScene, object );
  52567. materials.add( material );
  52568. }
  52569. }
  52570. } );
  52571. currentRenderState = renderStateStack.pop();
  52572. return materials;
  52573. };
  52574. // compileAsync
  52575. /**
  52576. * Asynchronous version of {@link WebGLRenderer#compile}.
  52577. *
  52578. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  52579. * it is recommended to use this version of `compile()` whenever possible.
  52580. *
  52581. * @async
  52582. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  52583. * @param {Camera} camera - The camera.
  52584. * @param {?Scene} [targetScene=null] - The target scene.
  52585. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  52586. */
  52587. this.compileAsync = function ( scene, camera, targetScene = null ) {
  52588. const materials = this.compile( scene, camera, targetScene );
  52589. // Wait for all the materials in the new object to indicate that they're
  52590. // ready to be used before resolving the promise.
  52591. return new Promise( ( resolve ) => {
  52592. function checkMaterialsReady() {
  52593. materials.forEach( function ( material ) {
  52594. const materialProperties = properties.get( material );
  52595. const program = materialProperties.currentProgram;
  52596. if ( program.isReady() ) {
  52597. // remove any programs that report they're ready to use from the list
  52598. materials.delete( material );
  52599. }
  52600. } );
  52601. // once the list of compiling materials is empty, call the callback
  52602. if ( materials.size === 0 ) {
  52603. resolve( scene );
  52604. return;
  52605. }
  52606. // if some materials are still not ready, wait a bit and check again
  52607. setTimeout( checkMaterialsReady, 10 );
  52608. }
  52609. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  52610. // If we can check the compilation status of the materials without
  52611. // blocking then do so right away.
  52612. checkMaterialsReady();
  52613. } else {
  52614. // Otherwise start by waiting a bit to give the materials we just
  52615. // initialized a chance to finish.
  52616. setTimeout( checkMaterialsReady, 10 );
  52617. }
  52618. } );
  52619. };
  52620. // Animation Loop
  52621. let onAnimationFrameCallback = null;
  52622. function onAnimationFrame( time ) {
  52623. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  52624. }
  52625. function onXRSessionStart() {
  52626. animation.stop();
  52627. }
  52628. function onXRSessionEnd() {
  52629. animation.start();
  52630. }
  52631. const animation = new WebGLAnimation();
  52632. animation.setAnimationLoop( onAnimationFrame );
  52633. if ( typeof self !== 'undefined' ) animation.setContext( self );
  52634. this.setAnimationLoop = function ( callback ) {
  52635. onAnimationFrameCallback = callback;
  52636. xr.setAnimationLoop( callback );
  52637. ( callback === null ) ? animation.stop() : animation.start();
  52638. };
  52639. xr.addEventListener( 'sessionstart', onXRSessionStart );
  52640. xr.addEventListener( 'sessionend', onXRSessionEnd );
  52641. // Rendering
  52642. /**
  52643. * Renders the given scene (or other type of 3D object) using the given camera.
  52644. *
  52645. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  52646. * or to the canvas as usual.
  52647. *
  52648. * By default render buffers are cleared before rendering but you can prevent
  52649. * this by setting the property `autoClear` to `false`. If you want to prevent
  52650. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  52651. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  52652. *
  52653. * @param {Object3D} scene - The scene to render.
  52654. * @param {Camera} camera - The camera.
  52655. */
  52656. this.render = function ( scene, camera ) {
  52657. if ( camera !== undefined && camera.isCamera !== true ) {
  52658. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  52659. return;
  52660. }
  52661. if ( _isContextLost === true ) return;
  52662. // update scene graph
  52663. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  52664. // update camera matrices and frustum
  52665. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  52666. if ( xr.enabled === true && xr.isPresenting === true ) {
  52667. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  52668. camera = xr.getCamera(); // use XR camera for rendering
  52669. }
  52670. //
  52671. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  52672. currentRenderState = renderStates.get( scene, renderStateStack.length );
  52673. currentRenderState.init( camera );
  52674. renderStateStack.push( currentRenderState );
  52675. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  52676. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  52677. _localClippingEnabled = this.localClippingEnabled;
  52678. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  52679. currentRenderList = renderLists.get( scene, renderListStack.length );
  52680. currentRenderList.init();
  52681. renderListStack.push( currentRenderList );
  52682. if ( xr.enabled === true && xr.isPresenting === true ) {
  52683. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  52684. if ( depthSensingMesh !== null ) {
  52685. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  52686. }
  52687. }
  52688. projectObject( scene, camera, 0, _this.sortObjects );
  52689. currentRenderList.finish();
  52690. if ( _this.sortObjects === true ) {
  52691. currentRenderList.sort( _opaqueSort, _transparentSort );
  52692. }
  52693. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  52694. if ( _renderBackground ) {
  52695. background.addToRenderList( currentRenderList, scene );
  52696. }
  52697. //
  52698. this.info.render.frame ++;
  52699. if ( _clippingEnabled === true ) clipping.beginShadows();
  52700. const shadowsArray = currentRenderState.state.shadowsArray;
  52701. shadowMap.render( shadowsArray, scene, camera );
  52702. if ( _clippingEnabled === true ) clipping.endShadows();
  52703. //
  52704. if ( this.info.autoReset === true ) this.info.reset();
  52705. // render scene
  52706. const opaqueObjects = currentRenderList.opaque;
  52707. const transmissiveObjects = currentRenderList.transmissive;
  52708. currentRenderState.setupLights();
  52709. if ( camera.isArrayCamera ) {
  52710. const cameras = camera.cameras;
  52711. if ( transmissiveObjects.length > 0 ) {
  52712. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52713. const camera2 = cameras[ i ];
  52714. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  52715. }
  52716. }
  52717. if ( _renderBackground ) background.render( scene );
  52718. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  52719. const camera2 = cameras[ i ];
  52720. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  52721. }
  52722. } else {
  52723. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  52724. if ( _renderBackground ) background.render( scene );
  52725. renderScene( currentRenderList, scene, camera );
  52726. }
  52727. //
  52728. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  52729. // resolve multisample renderbuffers to a single-sample texture if necessary
  52730. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  52731. // Generate mipmap if we're using any kind of mipmap filtering
  52732. textures.updateRenderTargetMipmap( _currentRenderTarget );
  52733. }
  52734. //
  52735. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  52736. // _gl.finish();
  52737. bindingStates.resetDefaultState();
  52738. _currentMaterialId = -1;
  52739. _currentCamera = null;
  52740. renderStateStack.pop();
  52741. if ( renderStateStack.length > 0 ) {
  52742. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  52743. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  52744. } else {
  52745. currentRenderState = null;
  52746. }
  52747. renderListStack.pop();
  52748. if ( renderListStack.length > 0 ) {
  52749. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  52750. } else {
  52751. currentRenderList = null;
  52752. }
  52753. };
  52754. function projectObject( object, camera, groupOrder, sortObjects ) {
  52755. if ( object.visible === false ) return;
  52756. const visible = object.layers.test( camera.layers );
  52757. if ( visible ) {
  52758. if ( object.isGroup ) {
  52759. groupOrder = object.renderOrder;
  52760. } else if ( object.isLOD ) {
  52761. if ( object.autoUpdate === true ) object.update( camera );
  52762. } else if ( object.isLight ) {
  52763. currentRenderState.pushLight( object );
  52764. if ( object.castShadow ) {
  52765. currentRenderState.pushShadow( object );
  52766. }
  52767. } else if ( object.isSprite ) {
  52768. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  52769. if ( sortObjects ) {
  52770. _vector4.setFromMatrixPosition( object.matrixWorld )
  52771. .applyMatrix4( _projScreenMatrix );
  52772. }
  52773. const geometry = objects.update( object );
  52774. const material = object.material;
  52775. if ( material.visible ) {
  52776. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52777. }
  52778. }
  52779. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  52780. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  52781. const geometry = objects.update( object );
  52782. const material = object.material;
  52783. if ( sortObjects ) {
  52784. if ( object.boundingSphere !== undefined ) {
  52785. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  52786. _vector4.copy( object.boundingSphere.center );
  52787. } else {
  52788. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  52789. _vector4.copy( geometry.boundingSphere.center );
  52790. }
  52791. _vector4
  52792. .applyMatrix4( object.matrixWorld )
  52793. .applyMatrix4( _projScreenMatrix );
  52794. }
  52795. if ( Array.isArray( material ) ) {
  52796. const groups = geometry.groups;
  52797. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  52798. const group = groups[ i ];
  52799. const groupMaterial = material[ group.materialIndex ];
  52800. if ( groupMaterial && groupMaterial.visible ) {
  52801. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  52802. }
  52803. }
  52804. } else if ( material.visible ) {
  52805. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  52806. }
  52807. }
  52808. }
  52809. }
  52810. const children = object.children;
  52811. for ( let i = 0, l = children.length; i < l; i ++ ) {
  52812. projectObject( children[ i ], camera, groupOrder, sortObjects );
  52813. }
  52814. }
  52815. function renderScene( currentRenderList, scene, camera, viewport ) {
  52816. const opaqueObjects = currentRenderList.opaque;
  52817. const transmissiveObjects = currentRenderList.transmissive;
  52818. const transparentObjects = currentRenderList.transparent;
  52819. currentRenderState.setupLightsView( camera );
  52820. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52821. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  52822. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  52823. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  52824. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  52825. // Ensure depth buffer writing is enabled so it can be cleared on next render
  52826. state.buffers.depth.setTest( true );
  52827. state.buffers.depth.setMask( true );
  52828. state.buffers.color.setMask( true );
  52829. state.setPolygonOffset( false );
  52830. }
  52831. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  52832. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52833. if ( overrideMaterial !== null ) {
  52834. return;
  52835. }
  52836. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  52837. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  52838. generateMipmaps: true,
  52839. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  52840. minFilter: LinearMipmapLinearFilter,
  52841. samples: 4,
  52842. stencilBuffer: stencil,
  52843. resolveDepthBuffer: false,
  52844. resolveStencilBuffer: false,
  52845. colorSpace: ColorManagement.workingColorSpace,
  52846. } );
  52847. // debug
  52848. /*
  52849. const geometry = new PlaneGeometry();
  52850. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  52851. const mesh = new Mesh( geometry, material );
  52852. scene.add( mesh );
  52853. */
  52854. }
  52855. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  52856. const activeViewport = camera.viewport || _currentViewport;
  52857. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  52858. //
  52859. const currentRenderTarget = _this.getRenderTarget();
  52860. const currentActiveCubeFace = _this.getActiveCubeFace();
  52861. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  52862. _this.setRenderTarget( transmissionRenderTarget );
  52863. _this.getClearColor( _currentClearColor );
  52864. _currentClearAlpha = _this.getClearAlpha();
  52865. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  52866. _this.clear();
  52867. if ( _renderBackground ) background.render( scene );
  52868. // Turn off the features which can affect the frag color for opaque objects pass.
  52869. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  52870. const currentToneMapping = _this.toneMapping;
  52871. _this.toneMapping = NoToneMapping;
  52872. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  52873. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  52874. const currentCameraViewport = camera.viewport;
  52875. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  52876. currentRenderState.setupLightsView( camera );
  52877. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  52878. renderObjects( opaqueObjects, scene, camera );
  52879. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52880. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52881. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  52882. let renderTargetNeedsUpdate = false;
  52883. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  52884. const renderItem = transmissiveObjects[ i ];
  52885. const object = renderItem.object;
  52886. const geometry = renderItem.geometry;
  52887. const material = renderItem.material;
  52888. const group = renderItem.group;
  52889. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  52890. const currentSide = material.side;
  52891. material.side = BackSide;
  52892. material.needsUpdate = true;
  52893. renderObject( object, scene, camera, geometry, material, group );
  52894. material.side = currentSide;
  52895. material.needsUpdate = true;
  52896. renderTargetNeedsUpdate = true;
  52897. }
  52898. }
  52899. if ( renderTargetNeedsUpdate === true ) {
  52900. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  52901. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  52902. }
  52903. }
  52904. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  52905. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  52906. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  52907. _this.toneMapping = currentToneMapping;
  52908. }
  52909. function renderObjects( renderList, scene, camera ) {
  52910. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  52911. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  52912. const renderItem = renderList[ i ];
  52913. const object = renderItem.object;
  52914. const geometry = renderItem.geometry;
  52915. const group = renderItem.group;
  52916. let material = renderItem.material;
  52917. if ( material.allowOverride === true && overrideMaterial !== null ) {
  52918. material = overrideMaterial;
  52919. }
  52920. if ( object.layers.test( camera.layers ) ) {
  52921. renderObject( object, scene, camera, geometry, material, group );
  52922. }
  52923. }
  52924. }
  52925. function renderObject( object, scene, camera, geometry, material, group ) {
  52926. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  52927. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  52928. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  52929. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  52930. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  52931. material.side = BackSide;
  52932. material.needsUpdate = true;
  52933. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52934. material.side = FrontSide;
  52935. material.needsUpdate = true;
  52936. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52937. material.side = DoubleSide;
  52938. } else {
  52939. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  52940. }
  52941. object.onAfterRender( _this, scene, camera, geometry, material, group );
  52942. }
  52943. function getProgram( material, scene, object ) {
  52944. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  52945. const materialProperties = properties.get( material );
  52946. const lights = currentRenderState.state.lights;
  52947. const shadowsArray = currentRenderState.state.shadowsArray;
  52948. const lightsStateVersion = lights.state.version;
  52949. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  52950. const programCacheKey = programCache.getProgramCacheKey( parameters );
  52951. let programs = materialProperties.programs;
  52952. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  52953. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  52954. materialProperties.fog = scene.fog;
  52955. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  52956. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  52957. if ( programs === undefined ) {
  52958. // new material
  52959. material.addEventListener( 'dispose', onMaterialDispose );
  52960. programs = new Map();
  52961. materialProperties.programs = programs;
  52962. }
  52963. let program = programs.get( programCacheKey );
  52964. if ( program !== undefined ) {
  52965. // early out if program and light state is identical
  52966. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  52967. updateCommonMaterialProperties( material, parameters );
  52968. return program;
  52969. }
  52970. } else {
  52971. parameters.uniforms = programCache.getUniforms( material );
  52972. material.onBeforeCompile( parameters, _this );
  52973. program = programCache.acquireProgram( parameters, programCacheKey );
  52974. programs.set( programCacheKey, program );
  52975. materialProperties.uniforms = parameters.uniforms;
  52976. }
  52977. const uniforms = materialProperties.uniforms;
  52978. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  52979. uniforms.clippingPlanes = clipping.uniform;
  52980. }
  52981. updateCommonMaterialProperties( material, parameters );
  52982. // store the light setup it was created for
  52983. materialProperties.needsLights = materialNeedsLights( material );
  52984. materialProperties.lightsStateVersion = lightsStateVersion;
  52985. if ( materialProperties.needsLights ) {
  52986. // wire up the material to this renderer's lighting state
  52987. uniforms.ambientLightColor.value = lights.state.ambient;
  52988. uniforms.lightProbe.value = lights.state.probe;
  52989. uniforms.directionalLights.value = lights.state.directional;
  52990. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  52991. uniforms.spotLights.value = lights.state.spot;
  52992. uniforms.spotLightShadows.value = lights.state.spotShadow;
  52993. uniforms.rectAreaLights.value = lights.state.rectArea;
  52994. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  52995. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  52996. uniforms.pointLights.value = lights.state.point;
  52997. uniforms.pointLightShadows.value = lights.state.pointShadow;
  52998. uniforms.hemisphereLights.value = lights.state.hemi;
  52999. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  53000. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53001. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  53002. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53003. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53004. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  53005. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53006. // TODO (abelnation): add area lights shadow info to uniforms
  53007. }
  53008. materialProperties.currentProgram = program;
  53009. materialProperties.uniformsList = null;
  53010. return program;
  53011. }
  53012. function getUniformList( materialProperties ) {
  53013. if ( materialProperties.uniformsList === null ) {
  53014. const progUniforms = materialProperties.currentProgram.getUniforms();
  53015. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53016. }
  53017. return materialProperties.uniformsList;
  53018. }
  53019. function updateCommonMaterialProperties( material, parameters ) {
  53020. const materialProperties = properties.get( material );
  53021. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53022. materialProperties.batching = parameters.batching;
  53023. materialProperties.batchingColor = parameters.batchingColor;
  53024. materialProperties.instancing = parameters.instancing;
  53025. materialProperties.instancingColor = parameters.instancingColor;
  53026. materialProperties.instancingMorph = parameters.instancingMorph;
  53027. materialProperties.skinning = parameters.skinning;
  53028. materialProperties.morphTargets = parameters.morphTargets;
  53029. materialProperties.morphNormals = parameters.morphNormals;
  53030. materialProperties.morphColors = parameters.morphColors;
  53031. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53032. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53033. materialProperties.numIntersection = parameters.numClipIntersection;
  53034. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53035. materialProperties.vertexTangents = parameters.vertexTangents;
  53036. materialProperties.toneMapping = parameters.toneMapping;
  53037. }
  53038. function setProgram( camera, scene, geometry, material, object ) {
  53039. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53040. textures.resetTextureUnits();
  53041. const fog = scene.fog;
  53042. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53043. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53044. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53045. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53046. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53047. const morphTargets = !! geometry.morphAttributes.position;
  53048. const morphNormals = !! geometry.morphAttributes.normal;
  53049. const morphColors = !! geometry.morphAttributes.color;
  53050. let toneMapping = NoToneMapping;
  53051. if ( material.toneMapped ) {
  53052. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53053. toneMapping = _this.toneMapping;
  53054. }
  53055. }
  53056. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53057. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53058. const materialProperties = properties.get( material );
  53059. const lights = currentRenderState.state.lights;
  53060. if ( _clippingEnabled === true ) {
  53061. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53062. const useCache =
  53063. camera === _currentCamera &&
  53064. material.id === _currentMaterialId;
  53065. // we might want to call this function with some ClippingGroup
  53066. // object instead of the material, once it becomes feasible
  53067. // (#8465, #8379)
  53068. clipping.setState( material, camera, useCache );
  53069. }
  53070. }
  53071. //
  53072. let needsProgramChange = false;
  53073. if ( material.version === materialProperties.__version ) {
  53074. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53075. needsProgramChange = true;
  53076. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53077. needsProgramChange = true;
  53078. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53079. needsProgramChange = true;
  53080. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53081. needsProgramChange = true;
  53082. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53083. needsProgramChange = true;
  53084. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53085. needsProgramChange = true;
  53086. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53087. needsProgramChange = true;
  53088. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53089. needsProgramChange = true;
  53090. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53091. needsProgramChange = true;
  53092. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53093. needsProgramChange = true;
  53094. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53095. needsProgramChange = true;
  53096. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53097. needsProgramChange = true;
  53098. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53099. needsProgramChange = true;
  53100. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53101. needsProgramChange = true;
  53102. } else if ( materialProperties.envMap !== envMap ) {
  53103. needsProgramChange = true;
  53104. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53105. needsProgramChange = true;
  53106. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53107. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53108. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53109. needsProgramChange = true;
  53110. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53111. needsProgramChange = true;
  53112. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53113. needsProgramChange = true;
  53114. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53115. needsProgramChange = true;
  53116. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53117. needsProgramChange = true;
  53118. } else if ( materialProperties.morphColors !== morphColors ) {
  53119. needsProgramChange = true;
  53120. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53121. needsProgramChange = true;
  53122. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53123. needsProgramChange = true;
  53124. }
  53125. } else {
  53126. needsProgramChange = true;
  53127. materialProperties.__version = material.version;
  53128. }
  53129. //
  53130. let program = materialProperties.currentProgram;
  53131. if ( needsProgramChange === true ) {
  53132. program = getProgram( material, scene, object );
  53133. }
  53134. let refreshProgram = false;
  53135. let refreshMaterial = false;
  53136. let refreshLights = false;
  53137. const p_uniforms = program.getUniforms(),
  53138. m_uniforms = materialProperties.uniforms;
  53139. if ( state.useProgram( program.program ) ) {
  53140. refreshProgram = true;
  53141. refreshMaterial = true;
  53142. refreshLights = true;
  53143. }
  53144. if ( material.id !== _currentMaterialId ) {
  53145. _currentMaterialId = material.id;
  53146. refreshMaterial = true;
  53147. }
  53148. if ( refreshProgram || _currentCamera !== camera ) {
  53149. // common camera uniforms
  53150. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53151. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53152. camera._reversedDepth = true;
  53153. camera.updateProjectionMatrix();
  53154. }
  53155. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53156. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53157. const uCamPos = p_uniforms.map.cameraPosition;
  53158. if ( uCamPos !== undefined ) {
  53159. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53160. }
  53161. if ( capabilities.logarithmicDepthBuffer ) {
  53162. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53163. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53164. }
  53165. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53166. if ( material.isMeshPhongMaterial ||
  53167. material.isMeshToonMaterial ||
  53168. material.isMeshLambertMaterial ||
  53169. material.isMeshBasicMaterial ||
  53170. material.isMeshStandardMaterial ||
  53171. material.isShaderMaterial ) {
  53172. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53173. }
  53174. if ( _currentCamera !== camera ) {
  53175. _currentCamera = camera;
  53176. // lighting uniforms depend on the camera so enforce an update
  53177. // now, in case this material supports lights - or later, when
  53178. // the next material that does gets activated:
  53179. refreshMaterial = true; // set to true on material change
  53180. refreshLights = true; // remains set until update done
  53181. }
  53182. }
  53183. // skinning and morph target uniforms must be set even if material didn't change
  53184. // auto-setting of texture unit for bone and morph texture must go before other textures
  53185. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53186. if ( object.isSkinnedMesh ) {
  53187. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53188. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53189. const skeleton = object.skeleton;
  53190. if ( skeleton ) {
  53191. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53192. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53193. }
  53194. }
  53195. if ( object.isBatchedMesh ) {
  53196. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53197. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53198. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53199. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53200. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53201. if ( object._colorsTexture !== null ) {
  53202. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53203. }
  53204. }
  53205. const morphAttributes = geometry.morphAttributes;
  53206. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53207. morphtargets.update( object, geometry, program );
  53208. }
  53209. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53210. materialProperties.receiveShadow = object.receiveShadow;
  53211. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53212. }
  53213. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53214. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53215. m_uniforms.envMap.value = envMap;
  53216. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53217. }
  53218. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53219. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53220. }
  53221. if ( refreshMaterial ) {
  53222. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53223. if ( materialProperties.needsLights ) {
  53224. // the current material requires lighting info
  53225. // note: all lighting uniforms are always set correctly
  53226. // they simply reference the renderer's state for their
  53227. // values
  53228. //
  53229. // use the current material's .needsUpdate flags to set
  53230. // the GL state when required
  53231. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53232. }
  53233. // refresh uniforms common to several materials
  53234. if ( fog && material.fog === true ) {
  53235. materials.refreshFogUniforms( m_uniforms, fog );
  53236. }
  53237. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53238. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53239. }
  53240. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53241. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53242. material.uniformsNeedUpdate = false;
  53243. }
  53244. if ( material.isSpriteMaterial ) {
  53245. p_uniforms.setValue( _gl, 'center', object.center );
  53246. }
  53247. // common matrices
  53248. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53249. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53250. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53251. // UBOs
  53252. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53253. const groups = material.uniformsGroups;
  53254. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53255. const group = groups[ i ];
  53256. uniformsGroups.update( group, program );
  53257. uniformsGroups.bind( group, program );
  53258. }
  53259. }
  53260. return program;
  53261. }
  53262. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53263. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53264. uniforms.ambientLightColor.needsUpdate = value;
  53265. uniforms.lightProbe.needsUpdate = value;
  53266. uniforms.directionalLights.needsUpdate = value;
  53267. uniforms.directionalLightShadows.needsUpdate = value;
  53268. uniforms.pointLights.needsUpdate = value;
  53269. uniforms.pointLightShadows.needsUpdate = value;
  53270. uniforms.spotLights.needsUpdate = value;
  53271. uniforms.spotLightShadows.needsUpdate = value;
  53272. uniforms.rectAreaLights.needsUpdate = value;
  53273. uniforms.hemisphereLights.needsUpdate = value;
  53274. }
  53275. function materialNeedsLights( material ) {
  53276. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53277. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53278. ( material.isShaderMaterial && material.lights === true );
  53279. }
  53280. /**
  53281. * Returns the active cube face.
  53282. *
  53283. * @return {number} The active cube face.
  53284. */
  53285. this.getActiveCubeFace = function () {
  53286. return _currentActiveCubeFace;
  53287. };
  53288. /**
  53289. * Returns the active mipmap level.
  53290. *
  53291. * @return {number} The active mipmap level.
  53292. */
  53293. this.getActiveMipmapLevel = function () {
  53294. return _currentActiveMipmapLevel;
  53295. };
  53296. /**
  53297. * Returns the active render target.
  53298. *
  53299. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53300. * is currently set.
  53301. */
  53302. this.getRenderTarget = function () {
  53303. return _currentRenderTarget;
  53304. };
  53305. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  53306. const renderTargetProperties = properties.get( renderTarget );
  53307. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  53308. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  53309. // The multisample_render_to_texture extension doesn't work properly if there
  53310. // are midframe flushes and an external depth buffer. Disable use of the extension.
  53311. renderTargetProperties.__useRenderToTexture = false;
  53312. }
  53313. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  53314. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  53315. renderTargetProperties.__hasExternalTextures = true;
  53316. };
  53317. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  53318. const renderTargetProperties = properties.get( renderTarget );
  53319. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  53320. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  53321. };
  53322. const _scratchFrameBuffer = _gl.createFramebuffer();
  53323. /**
  53324. * Sets the active rendertarget.
  53325. *
  53326. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  53327. * the canvas is set as the active render target instead.
  53328. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  53329. * Indicates the z layer to render in to when using 3D or array render targets.
  53330. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  53331. */
  53332. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  53333. _currentRenderTarget = renderTarget;
  53334. _currentActiveCubeFace = activeCubeFace;
  53335. _currentActiveMipmapLevel = activeMipmapLevel;
  53336. let useDefaultFramebuffer = true;
  53337. let framebuffer = null;
  53338. let isCube = false;
  53339. let isRenderTarget3D = false;
  53340. if ( renderTarget ) {
  53341. const renderTargetProperties = properties.get( renderTarget );
  53342. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  53343. // We need to make sure to rebind the framebuffer.
  53344. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  53345. useDefaultFramebuffer = false;
  53346. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  53347. textures.setupRenderTarget( renderTarget );
  53348. } else if ( renderTargetProperties.__hasExternalTextures ) {
  53349. // Color and depth texture must be rebound in order for the swapchain to update.
  53350. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  53351. } else if ( renderTarget.depthBuffer ) {
  53352. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  53353. const depthTexture = renderTarget.depthTexture;
  53354. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  53355. // check if the depth texture is compatible
  53356. if (
  53357. depthTexture !== null &&
  53358. properties.has( depthTexture ) &&
  53359. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  53360. ) {
  53361. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  53362. }
  53363. // Swap the depth buffer to the currently attached one
  53364. textures.setupDepthRenderbuffer( renderTarget );
  53365. }
  53366. }
  53367. const texture = renderTarget.texture;
  53368. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53369. isRenderTarget3D = true;
  53370. }
  53371. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53372. if ( renderTarget.isWebGLCubeRenderTarget ) {
  53373. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  53374. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  53375. } else {
  53376. framebuffer = __webglFramebuffer[ activeCubeFace ];
  53377. }
  53378. isCube = true;
  53379. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  53380. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  53381. } else {
  53382. if ( Array.isArray( __webglFramebuffer ) ) {
  53383. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  53384. } else {
  53385. framebuffer = __webglFramebuffer;
  53386. }
  53387. }
  53388. _currentViewport.copy( renderTarget.viewport );
  53389. _currentScissor.copy( renderTarget.scissor );
  53390. _currentScissorTest = renderTarget.scissorTest;
  53391. } else {
  53392. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  53393. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  53394. _currentScissorTest = _scissorTest;
  53395. }
  53396. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  53397. // being bound that are different sizes.
  53398. if ( activeMipmapLevel !== 0 ) {
  53399. framebuffer = _scratchFrameBuffer;
  53400. }
  53401. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53402. if ( framebufferBound && useDefaultFramebuffer ) {
  53403. state.drawBuffers( renderTarget, framebuffer );
  53404. }
  53405. state.viewport( _currentViewport );
  53406. state.scissor( _currentScissor );
  53407. state.setScissorTest( _currentScissorTest );
  53408. if ( isCube ) {
  53409. const textureProperties = properties.get( renderTarget.texture );
  53410. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  53411. } else if ( isRenderTarget3D ) {
  53412. const layer = activeCubeFace;
  53413. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  53414. const textureProperties = properties.get( renderTarget.textures[ i ] );
  53415. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  53416. }
  53417. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  53418. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  53419. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  53420. const textureProperties = properties.get( renderTarget.texture );
  53421. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  53422. }
  53423. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  53424. };
  53425. /**
  53426. * Reads the pixel data from the given render target into the given buffer.
  53427. *
  53428. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53429. * @param {number} x - The `x` coordinate of the copy region's origin.
  53430. * @param {number} y - The `y` coordinate of the copy region's origin.
  53431. * @param {number} width - The width of the copy region.
  53432. * @param {number} height - The height of the copy region.
  53433. * @param {TypedArray} buffer - The result buffer.
  53434. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53435. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53436. */
  53437. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53438. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53439. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53440. return;
  53441. }
  53442. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53443. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53444. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53445. }
  53446. if ( framebuffer ) {
  53447. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53448. try {
  53449. const texture = renderTarget.textures[ textureIndex ];
  53450. const textureFormat = texture.format;
  53451. const textureType = texture.type;
  53452. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53453. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  53454. return;
  53455. }
  53456. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53457. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53458. return;
  53459. }
  53460. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53461. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53462. // when using MRT, select the correct color buffer for the subsequent read command
  53463. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53464. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  53465. }
  53466. } finally {
  53467. // restore framebuffer of current render target if necessary
  53468. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53469. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53470. }
  53471. }
  53472. };
  53473. /**
  53474. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  53475. *
  53476. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  53477. *
  53478. * @async
  53479. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53480. * @param {number} x - The `x` coordinate of the copy region's origin.
  53481. * @param {number} y - The `y` coordinate of the copy region's origin.
  53482. * @param {number} width - The width of the copy region.
  53483. * @param {number} height - The height of the copy region.
  53484. * @param {TypedArray} buffer - The result buffer.
  53485. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53486. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53487. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  53488. */
  53489. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53490. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53491. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53492. }
  53493. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53494. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53495. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53496. }
  53497. if ( framebuffer ) {
  53498. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53499. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53500. // set the active frame buffer to the one we want to read
  53501. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53502. const texture = renderTarget.textures[ textureIndex ];
  53503. const textureFormat = texture.format;
  53504. const textureType = texture.type;
  53505. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53506. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  53507. }
  53508. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53509. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53510. }
  53511. const glBuffer = _gl.createBuffer();
  53512. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53513. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  53514. // when using MRT, select the correct color buffer for the subsequent read command
  53515. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53516. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  53517. // reset the frame buffer to the currently set buffer before waiting
  53518. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53519. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  53520. // check if the commands have finished every 8 ms
  53521. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  53522. _gl.flush();
  53523. await probeAsync( _gl, sync, 4 );
  53524. // read the data and delete the buffer
  53525. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  53526. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  53527. _gl.deleteBuffer( glBuffer );
  53528. _gl.deleteSync( sync );
  53529. return buffer;
  53530. } else {
  53531. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  53532. }
  53533. }
  53534. };
  53535. /**
  53536. * Copies pixels from the current bound framebuffer into the given texture.
  53537. *
  53538. * @param {FramebufferTexture} texture - The texture.
  53539. * @param {?Vector2} [position=null] - The start position of the copy operation.
  53540. * @param {number} [level=0] - The mip level. The default represents the base mip.
  53541. */
  53542. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  53543. const levelScale = Math.pow( 2, - level );
  53544. const width = Math.floor( texture.image.width * levelScale );
  53545. const height = Math.floor( texture.image.height * levelScale );
  53546. const x = position !== null ? position.x : 0;
  53547. const y = position !== null ? position.y : 0;
  53548. textures.setTexture2D( texture, 0 );
  53549. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  53550. state.unbindTexture();
  53551. };
  53552. const _srcFramebuffer = _gl.createFramebuffer();
  53553. const _dstFramebuffer = _gl.createFramebuffer();
  53554. /**
  53555. * Copies data of the given source texture into a destination texture.
  53556. *
  53557. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  53558. * {@link WebGLRenderer#initRenderTarget}.
  53559. *
  53560. * @param {Texture} srcTexture - The source texture.
  53561. * @param {Texture} dstTexture - The destination texture.
  53562. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  53563. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  53564. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  53565. * @param {?number} [dstLevel=null] - The destination mipmap level.
  53566. */
  53567. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  53568. // support the previous signature with just a single dst mipmap level
  53569. if ( dstLevel === null ) {
  53570. if ( srcLevel !== 0 ) {
  53571. // @deprecated, r171
  53572. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  53573. dstLevel = srcLevel;
  53574. srcLevel = 0;
  53575. } else {
  53576. dstLevel = 0;
  53577. }
  53578. }
  53579. // gather the necessary dimensions to copy
  53580. let width, height, depth, minX, minY, minZ;
  53581. let dstX, dstY, dstZ;
  53582. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  53583. if ( srcRegion !== null ) {
  53584. width = srcRegion.max.x - srcRegion.min.x;
  53585. height = srcRegion.max.y - srcRegion.min.y;
  53586. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  53587. minX = srcRegion.min.x;
  53588. minY = srcRegion.min.y;
  53589. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  53590. } else {
  53591. const levelScale = Math.pow( 2, - srcLevel );
  53592. width = Math.floor( image.width * levelScale );
  53593. height = Math.floor( image.height * levelScale );
  53594. if ( srcTexture.isDataArrayTexture ) {
  53595. depth = image.depth;
  53596. } else if ( srcTexture.isData3DTexture ) {
  53597. depth = Math.floor( image.depth * levelScale );
  53598. } else {
  53599. depth = 1;
  53600. }
  53601. minX = 0;
  53602. minY = 0;
  53603. minZ = 0;
  53604. }
  53605. if ( dstPosition !== null ) {
  53606. dstX = dstPosition.x;
  53607. dstY = dstPosition.y;
  53608. dstZ = dstPosition.z;
  53609. } else {
  53610. dstX = 0;
  53611. dstY = 0;
  53612. dstZ = 0;
  53613. }
  53614. // Set up the destination target
  53615. const glFormat = utils.convert( dstTexture.format );
  53616. const glType = utils.convert( dstTexture.type );
  53617. let glTarget;
  53618. if ( dstTexture.isData3DTexture ) {
  53619. textures.setTexture3D( dstTexture, 0 );
  53620. glTarget = _gl.TEXTURE_3D;
  53621. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  53622. textures.setTexture2DArray( dstTexture, 0 );
  53623. glTarget = _gl.TEXTURE_2D_ARRAY;
  53624. } else {
  53625. textures.setTexture2D( dstTexture, 0 );
  53626. glTarget = _gl.TEXTURE_2D;
  53627. }
  53628. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  53629. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  53630. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  53631. // used for copying data from cpu
  53632. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  53633. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  53634. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  53635. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  53636. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  53637. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  53638. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  53639. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  53640. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  53641. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  53642. // set up the src texture
  53643. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  53644. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  53645. if ( srcTexture.isDepthTexture ) {
  53646. const srcTextureProperties = properties.get( srcTexture );
  53647. const dstTextureProperties = properties.get( dstTexture );
  53648. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  53649. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  53650. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  53651. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  53652. for ( let i = 0; i < depth; i ++ ) {
  53653. // if the source or destination are a 3d target then a layer needs to be bound
  53654. if ( isSrc3D ) {
  53655. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  53656. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  53657. }
  53658. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  53659. }
  53660. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53661. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53662. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  53663. // get the appropriate frame buffers
  53664. const srcTextureProperties = properties.get( srcTexture );
  53665. const dstTextureProperties = properties.get( dstTexture );
  53666. // bind the frame buffer targets
  53667. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  53668. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  53669. for ( let i = 0; i < depth; i ++ ) {
  53670. // assign the correct layers and mip maps to the frame buffers
  53671. if ( isSrc3D ) {
  53672. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  53673. } else {
  53674. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  53675. }
  53676. if ( isDst3D ) {
  53677. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  53678. } else {
  53679. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  53680. }
  53681. // copy the data using the fastest function that can achieve the copy
  53682. if ( srcLevel !== 0 ) {
  53683. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  53684. } else if ( isDst3D ) {
  53685. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  53686. } else {
  53687. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  53688. }
  53689. }
  53690. // unbind read, draw buffers
  53691. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  53692. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  53693. } else {
  53694. if ( isDst3D ) {
  53695. // copy data into the 3d texture
  53696. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  53697. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  53698. } else if ( dstTexture.isCompressedArrayTexture ) {
  53699. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  53700. } else {
  53701. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  53702. }
  53703. } else {
  53704. // copy data into the 2d texture
  53705. if ( srcTexture.isDataTexture ) {
  53706. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  53707. } else if ( srcTexture.isCompressedTexture ) {
  53708. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  53709. } else {
  53710. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  53711. }
  53712. }
  53713. }
  53714. // reset values
  53715. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  53716. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  53717. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  53718. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  53719. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  53720. // Generate mipmaps only when copying level 0
  53721. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53722. _gl.generateMipmap( glTarget );
  53723. }
  53724. state.unbindTexture();
  53725. };
  53726. /**
  53727. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  53728. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  53729. * rendered to.
  53730. *
  53731. * @param {WebGLRenderTarget} target - The render target.
  53732. */
  53733. this.initRenderTarget = function ( target ) {
  53734. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  53735. textures.setupRenderTarget( target );
  53736. }
  53737. };
  53738. /**
  53739. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  53740. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  53741. *
  53742. * @param {Texture} texture - The texture.
  53743. */
  53744. this.initTexture = function ( texture ) {
  53745. if ( texture.isCubeTexture ) {
  53746. textures.setTextureCube( texture, 0 );
  53747. } else if ( texture.isData3DTexture ) {
  53748. textures.setTexture3D( texture, 0 );
  53749. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53750. textures.setTexture2DArray( texture, 0 );
  53751. } else {
  53752. textures.setTexture2D( texture, 0 );
  53753. }
  53754. state.unbindTexture();
  53755. };
  53756. /**
  53757. * Can be used to reset the internal WebGL state. This method is mostly
  53758. * relevant for applications which share a single WebGL context across
  53759. * multiple WebGL libraries.
  53760. */
  53761. this.resetState = function () {
  53762. _currentActiveCubeFace = 0;
  53763. _currentActiveMipmapLevel = 0;
  53764. _currentRenderTarget = null;
  53765. state.reset();
  53766. bindingStates.reset();
  53767. };
  53768. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  53769. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  53770. }
  53771. }
  53772. /**
  53773. * Defines the coordinate system of the renderer.
  53774. *
  53775. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  53776. *
  53777. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  53778. * @default WebGLCoordinateSystem
  53779. * @readonly
  53780. */
  53781. get coordinateSystem() {
  53782. return WebGLCoordinateSystem;
  53783. }
  53784. /**
  53785. * Defines the output color space of the renderer.
  53786. *
  53787. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  53788. * @default SRGBColorSpace
  53789. */
  53790. get outputColorSpace() {
  53791. return this._outputColorSpace;
  53792. }
  53793. set outputColorSpace( colorSpace ) {
  53794. this._outputColorSpace = colorSpace;
  53795. const gl = this.getContext();
  53796. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  53797. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  53798. }
  53799. }
  53800. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  53801. exports.AddEquation = AddEquation;
  53802. exports.AddOperation = AddOperation;
  53803. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  53804. exports.AdditiveBlending = AdditiveBlending;
  53805. exports.AgXToneMapping = AgXToneMapping;
  53806. exports.AlphaFormat = AlphaFormat;
  53807. exports.AlwaysCompare = AlwaysCompare;
  53808. exports.AlwaysDepth = AlwaysDepth;
  53809. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  53810. exports.AmbientLight = AmbientLight;
  53811. exports.AnimationAction = AnimationAction;
  53812. exports.AnimationClip = AnimationClip;
  53813. exports.AnimationLoader = AnimationLoader;
  53814. exports.AnimationMixer = AnimationMixer;
  53815. exports.AnimationObjectGroup = AnimationObjectGroup;
  53816. exports.AnimationUtils = AnimationUtils;
  53817. exports.ArcCurve = ArcCurve;
  53818. exports.ArrayCamera = ArrayCamera;
  53819. exports.ArrowHelper = ArrowHelper;
  53820. exports.AttachedBindMode = AttachedBindMode;
  53821. exports.Audio = Audio;
  53822. exports.AudioAnalyser = AudioAnalyser;
  53823. exports.AudioContext = AudioContext;
  53824. exports.AudioListener = AudioListener;
  53825. exports.AudioLoader = AudioLoader;
  53826. exports.AxesHelper = AxesHelper;
  53827. exports.BackSide = BackSide;
  53828. exports.BasicDepthPacking = BasicDepthPacking;
  53829. exports.BasicShadowMap = BasicShadowMap;
  53830. exports.BatchedMesh = BatchedMesh;
  53831. exports.Bone = Bone;
  53832. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  53833. exports.Box2 = Box2;
  53834. exports.Box3 = Box3;
  53835. exports.Box3Helper = Box3Helper;
  53836. exports.BoxGeometry = BoxGeometry;
  53837. exports.BoxHelper = BoxHelper;
  53838. exports.BufferAttribute = BufferAttribute;
  53839. exports.BufferGeometry = BufferGeometry;
  53840. exports.BufferGeometryLoader = BufferGeometryLoader;
  53841. exports.ByteType = ByteType;
  53842. exports.Cache = Cache;
  53843. exports.Camera = Camera;
  53844. exports.CameraHelper = CameraHelper;
  53845. exports.CanvasTexture = CanvasTexture;
  53846. exports.CapsuleGeometry = CapsuleGeometry;
  53847. exports.CatmullRomCurve3 = CatmullRomCurve3;
  53848. exports.CineonToneMapping = CineonToneMapping;
  53849. exports.CircleGeometry = CircleGeometry;
  53850. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  53851. exports.Clock = Clock;
  53852. exports.Color = Color;
  53853. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  53854. exports.ColorManagement = ColorManagement;
  53855. exports.CompressedArrayTexture = CompressedArrayTexture;
  53856. exports.CompressedCubeTexture = CompressedCubeTexture;
  53857. exports.CompressedTexture = CompressedTexture;
  53858. exports.CompressedTextureLoader = CompressedTextureLoader;
  53859. exports.ConeGeometry = ConeGeometry;
  53860. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  53861. exports.ConstantColorFactor = ConstantColorFactor;
  53862. exports.Controls = Controls;
  53863. exports.CubeCamera = CubeCamera;
  53864. exports.CubeReflectionMapping = CubeReflectionMapping;
  53865. exports.CubeRefractionMapping = CubeRefractionMapping;
  53866. exports.CubeTexture = CubeTexture;
  53867. exports.CubeTextureLoader = CubeTextureLoader;
  53868. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  53869. exports.CubicBezierCurve = CubicBezierCurve;
  53870. exports.CubicBezierCurve3 = CubicBezierCurve3;
  53871. exports.CubicInterpolant = CubicInterpolant;
  53872. exports.CullFaceBack = CullFaceBack;
  53873. exports.CullFaceFront = CullFaceFront;
  53874. exports.CullFaceFrontBack = CullFaceFrontBack;
  53875. exports.CullFaceNone = CullFaceNone;
  53876. exports.Curve = Curve;
  53877. exports.CurvePath = CurvePath;
  53878. exports.CustomBlending = CustomBlending;
  53879. exports.CustomToneMapping = CustomToneMapping;
  53880. exports.CylinderGeometry = CylinderGeometry;
  53881. exports.Cylindrical = Cylindrical;
  53882. exports.Data3DTexture = Data3DTexture;
  53883. exports.DataArrayTexture = DataArrayTexture;
  53884. exports.DataTexture = DataTexture;
  53885. exports.DataTextureLoader = DataTextureLoader;
  53886. exports.DataUtils = DataUtils;
  53887. exports.DecrementStencilOp = DecrementStencilOp;
  53888. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  53889. exports.DefaultLoadingManager = DefaultLoadingManager;
  53890. exports.DepthFormat = DepthFormat;
  53891. exports.DepthStencilFormat = DepthStencilFormat;
  53892. exports.DepthTexture = DepthTexture;
  53893. exports.DetachedBindMode = DetachedBindMode;
  53894. exports.DirectionalLight = DirectionalLight;
  53895. exports.DirectionalLightHelper = DirectionalLightHelper;
  53896. exports.DiscreteInterpolant = DiscreteInterpolant;
  53897. exports.DodecahedronGeometry = DodecahedronGeometry;
  53898. exports.DoubleSide = DoubleSide;
  53899. exports.DstAlphaFactor = DstAlphaFactor;
  53900. exports.DstColorFactor = DstColorFactor;
  53901. exports.DynamicCopyUsage = DynamicCopyUsage;
  53902. exports.DynamicDrawUsage = DynamicDrawUsage;
  53903. exports.DynamicReadUsage = DynamicReadUsage;
  53904. exports.EdgesGeometry = EdgesGeometry;
  53905. exports.EllipseCurve = EllipseCurve;
  53906. exports.EqualCompare = EqualCompare;
  53907. exports.EqualDepth = EqualDepth;
  53908. exports.EqualStencilFunc = EqualStencilFunc;
  53909. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  53910. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  53911. exports.Euler = Euler;
  53912. exports.EventDispatcher = EventDispatcher;
  53913. exports.ExternalTexture = ExternalTexture;
  53914. exports.ExtrudeGeometry = ExtrudeGeometry;
  53915. exports.FileLoader = FileLoader;
  53916. exports.Float16BufferAttribute = Float16BufferAttribute;
  53917. exports.Float32BufferAttribute = Float32BufferAttribute;
  53918. exports.FloatType = FloatType;
  53919. exports.Fog = Fog;
  53920. exports.FogExp2 = FogExp2;
  53921. exports.FramebufferTexture = FramebufferTexture;
  53922. exports.FrontSide = FrontSide;
  53923. exports.Frustum = Frustum;
  53924. exports.FrustumArray = FrustumArray;
  53925. exports.GLBufferAttribute = GLBufferAttribute;
  53926. exports.GLSL1 = GLSL1;
  53927. exports.GLSL3 = GLSL3;
  53928. exports.GreaterCompare = GreaterCompare;
  53929. exports.GreaterDepth = GreaterDepth;
  53930. exports.GreaterEqualCompare = GreaterEqualCompare;
  53931. exports.GreaterEqualDepth = GreaterEqualDepth;
  53932. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  53933. exports.GreaterStencilFunc = GreaterStencilFunc;
  53934. exports.GridHelper = GridHelper;
  53935. exports.Group = Group;
  53936. exports.HalfFloatType = HalfFloatType;
  53937. exports.HemisphereLight = HemisphereLight;
  53938. exports.HemisphereLightHelper = HemisphereLightHelper;
  53939. exports.IcosahedronGeometry = IcosahedronGeometry;
  53940. exports.ImageBitmapLoader = ImageBitmapLoader;
  53941. exports.ImageLoader = ImageLoader;
  53942. exports.ImageUtils = ImageUtils;
  53943. exports.IncrementStencilOp = IncrementStencilOp;
  53944. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  53945. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  53946. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  53947. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  53948. exports.InstancedMesh = InstancedMesh;
  53949. exports.Int16BufferAttribute = Int16BufferAttribute;
  53950. exports.Int32BufferAttribute = Int32BufferAttribute;
  53951. exports.Int8BufferAttribute = Int8BufferAttribute;
  53952. exports.IntType = IntType;
  53953. exports.InterleavedBuffer = InterleavedBuffer;
  53954. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  53955. exports.Interpolant = Interpolant;
  53956. exports.InterpolateDiscrete = InterpolateDiscrete;
  53957. exports.InterpolateLinear = InterpolateLinear;
  53958. exports.InterpolateSmooth = InterpolateSmooth;
  53959. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  53960. exports.InterpolationSamplingType = InterpolationSamplingType;
  53961. exports.InvertStencilOp = InvertStencilOp;
  53962. exports.KeepStencilOp = KeepStencilOp;
  53963. exports.KeyframeTrack = KeyframeTrack;
  53964. exports.LOD = LOD;
  53965. exports.LatheGeometry = LatheGeometry;
  53966. exports.Layers = Layers;
  53967. exports.LessCompare = LessCompare;
  53968. exports.LessDepth = LessDepth;
  53969. exports.LessEqualCompare = LessEqualCompare;
  53970. exports.LessEqualDepth = LessEqualDepth;
  53971. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  53972. exports.LessStencilFunc = LessStencilFunc;
  53973. exports.Light = Light;
  53974. exports.LightProbe = LightProbe;
  53975. exports.Line = Line;
  53976. exports.Line3 = Line3;
  53977. exports.LineBasicMaterial = LineBasicMaterial;
  53978. exports.LineCurve = LineCurve;
  53979. exports.LineCurve3 = LineCurve3;
  53980. exports.LineDashedMaterial = LineDashedMaterial;
  53981. exports.LineLoop = LineLoop;
  53982. exports.LineSegments = LineSegments;
  53983. exports.LinearFilter = LinearFilter;
  53984. exports.LinearInterpolant = LinearInterpolant;
  53985. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  53986. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  53987. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  53988. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  53989. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  53990. exports.LinearToneMapping = LinearToneMapping;
  53991. exports.LinearTransfer = LinearTransfer;
  53992. exports.Loader = Loader;
  53993. exports.LoaderUtils = LoaderUtils;
  53994. exports.LoadingManager = LoadingManager;
  53995. exports.LoopOnce = LoopOnce;
  53996. exports.LoopPingPong = LoopPingPong;
  53997. exports.LoopRepeat = LoopRepeat;
  53998. exports.MOUSE = MOUSE;
  53999. exports.Material = Material;
  54000. exports.MaterialLoader = MaterialLoader;
  54001. exports.MathUtils = MathUtils;
  54002. exports.Matrix2 = Matrix2;
  54003. exports.Matrix3 = Matrix3;
  54004. exports.Matrix4 = Matrix4;
  54005. exports.MaxEquation = MaxEquation;
  54006. exports.Mesh = Mesh;
  54007. exports.MeshBasicMaterial = MeshBasicMaterial;
  54008. exports.MeshDepthMaterial = MeshDepthMaterial;
  54009. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54010. exports.MeshLambertMaterial = MeshLambertMaterial;
  54011. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54012. exports.MeshNormalMaterial = MeshNormalMaterial;
  54013. exports.MeshPhongMaterial = MeshPhongMaterial;
  54014. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54015. exports.MeshStandardMaterial = MeshStandardMaterial;
  54016. exports.MeshToonMaterial = MeshToonMaterial;
  54017. exports.MinEquation = MinEquation;
  54018. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54019. exports.MixOperation = MixOperation;
  54020. exports.MultiplyBlending = MultiplyBlending;
  54021. exports.MultiplyOperation = MultiplyOperation;
  54022. exports.NearestFilter = NearestFilter;
  54023. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54024. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54025. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54026. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54027. exports.NeutralToneMapping = NeutralToneMapping;
  54028. exports.NeverCompare = NeverCompare;
  54029. exports.NeverDepth = NeverDepth;
  54030. exports.NeverStencilFunc = NeverStencilFunc;
  54031. exports.NoBlending = NoBlending;
  54032. exports.NoColorSpace = NoColorSpace;
  54033. exports.NoToneMapping = NoToneMapping;
  54034. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54035. exports.NormalBlending = NormalBlending;
  54036. exports.NotEqualCompare = NotEqualCompare;
  54037. exports.NotEqualDepth = NotEqualDepth;
  54038. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54039. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54040. exports.Object3D = Object3D;
  54041. exports.ObjectLoader = ObjectLoader;
  54042. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54043. exports.OctahedronGeometry = OctahedronGeometry;
  54044. exports.OneFactor = OneFactor;
  54045. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54046. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54047. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54048. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54049. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54050. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54051. exports.OrthographicCamera = OrthographicCamera;
  54052. exports.PCFShadowMap = PCFShadowMap;
  54053. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54054. exports.PMREMGenerator = PMREMGenerator;
  54055. exports.Path = Path;
  54056. exports.PerspectiveCamera = PerspectiveCamera;
  54057. exports.Plane = Plane;
  54058. exports.PlaneGeometry = PlaneGeometry;
  54059. exports.PlaneHelper = PlaneHelper;
  54060. exports.PointLight = PointLight;
  54061. exports.PointLightHelper = PointLightHelper;
  54062. exports.Points = Points;
  54063. exports.PointsMaterial = PointsMaterial;
  54064. exports.PolarGridHelper = PolarGridHelper;
  54065. exports.PolyhedronGeometry = PolyhedronGeometry;
  54066. exports.PositionalAudio = PositionalAudio;
  54067. exports.PropertyBinding = PropertyBinding;
  54068. exports.PropertyMixer = PropertyMixer;
  54069. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54070. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54071. exports.Quaternion = Quaternion;
  54072. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54073. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54074. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54075. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54076. exports.REVISION = REVISION;
  54077. exports.RGBADepthPacking = RGBADepthPacking;
  54078. exports.RGBAFormat = RGBAFormat;
  54079. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54080. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54081. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54082. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54083. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54084. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54085. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54086. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54087. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54088. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54089. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54090. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54091. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54092. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54093. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54094. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54095. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54096. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54097. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54098. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54099. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54100. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54101. exports.RGBDepthPacking = RGBDepthPacking;
  54102. exports.RGBFormat = RGBFormat;
  54103. exports.RGBIntegerFormat = RGBIntegerFormat;
  54104. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54105. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54106. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54107. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54108. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54109. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54110. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54111. exports.RGDepthPacking = RGDepthPacking;
  54112. exports.RGFormat = RGFormat;
  54113. exports.RGIntegerFormat = RGIntegerFormat;
  54114. exports.RawShaderMaterial = RawShaderMaterial;
  54115. exports.Ray = Ray;
  54116. exports.Raycaster = Raycaster;
  54117. exports.RectAreaLight = RectAreaLight;
  54118. exports.RedFormat = RedFormat;
  54119. exports.RedIntegerFormat = RedIntegerFormat;
  54120. exports.ReinhardToneMapping = ReinhardToneMapping;
  54121. exports.RenderTarget = RenderTarget;
  54122. exports.RenderTarget3D = RenderTarget3D;
  54123. exports.RepeatWrapping = RepeatWrapping;
  54124. exports.ReplaceStencilOp = ReplaceStencilOp;
  54125. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54126. exports.RingGeometry = RingGeometry;
  54127. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54128. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54129. exports.SRGBColorSpace = SRGBColorSpace;
  54130. exports.SRGBTransfer = SRGBTransfer;
  54131. exports.Scene = Scene;
  54132. exports.ShaderChunk = ShaderChunk;
  54133. exports.ShaderLib = ShaderLib;
  54134. exports.ShaderMaterial = ShaderMaterial;
  54135. exports.ShadowMaterial = ShadowMaterial;
  54136. exports.Shape = Shape;
  54137. exports.ShapeGeometry = ShapeGeometry;
  54138. exports.ShapePath = ShapePath;
  54139. exports.ShapeUtils = ShapeUtils;
  54140. exports.ShortType = ShortType;
  54141. exports.Skeleton = Skeleton;
  54142. exports.SkeletonHelper = SkeletonHelper;
  54143. exports.SkinnedMesh = SkinnedMesh;
  54144. exports.Source = Source;
  54145. exports.Sphere = Sphere;
  54146. exports.SphereGeometry = SphereGeometry;
  54147. exports.Spherical = Spherical;
  54148. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54149. exports.SplineCurve = SplineCurve;
  54150. exports.SpotLight = SpotLight;
  54151. exports.SpotLightHelper = SpotLightHelper;
  54152. exports.Sprite = Sprite;
  54153. exports.SpriteMaterial = SpriteMaterial;
  54154. exports.SrcAlphaFactor = SrcAlphaFactor;
  54155. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54156. exports.SrcColorFactor = SrcColorFactor;
  54157. exports.StaticCopyUsage = StaticCopyUsage;
  54158. exports.StaticDrawUsage = StaticDrawUsage;
  54159. exports.StaticReadUsage = StaticReadUsage;
  54160. exports.StereoCamera = StereoCamera;
  54161. exports.StreamCopyUsage = StreamCopyUsage;
  54162. exports.StreamDrawUsage = StreamDrawUsage;
  54163. exports.StreamReadUsage = StreamReadUsage;
  54164. exports.StringKeyframeTrack = StringKeyframeTrack;
  54165. exports.SubtractEquation = SubtractEquation;
  54166. exports.SubtractiveBlending = SubtractiveBlending;
  54167. exports.TOUCH = TOUCH;
  54168. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54169. exports.TetrahedronGeometry = TetrahedronGeometry;
  54170. exports.Texture = Texture;
  54171. exports.TextureLoader = TextureLoader;
  54172. exports.TextureUtils = TextureUtils;
  54173. exports.Timer = Timer;
  54174. exports.TimestampQuery = TimestampQuery;
  54175. exports.TorusGeometry = TorusGeometry;
  54176. exports.TorusKnotGeometry = TorusKnotGeometry;
  54177. exports.Triangle = Triangle;
  54178. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54179. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54180. exports.TrianglesDrawMode = TrianglesDrawMode;
  54181. exports.TubeGeometry = TubeGeometry;
  54182. exports.UVMapping = UVMapping;
  54183. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54184. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54185. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54186. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54187. exports.Uniform = Uniform;
  54188. exports.UniformsGroup = UniformsGroup;
  54189. exports.UniformsLib = UniformsLib;
  54190. exports.UniformsUtils = UniformsUtils;
  54191. exports.UnsignedByteType = UnsignedByteType;
  54192. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  54193. exports.UnsignedInt248Type = UnsignedInt248Type;
  54194. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54195. exports.UnsignedIntType = UnsignedIntType;
  54196. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54197. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54198. exports.UnsignedShortType = UnsignedShortType;
  54199. exports.VSMShadowMap = VSMShadowMap;
  54200. exports.Vector2 = Vector2;
  54201. exports.Vector3 = Vector3;
  54202. exports.Vector4 = Vector4;
  54203. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54204. exports.VideoFrameTexture = VideoFrameTexture;
  54205. exports.VideoTexture = VideoTexture;
  54206. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54207. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54208. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54209. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54210. exports.WebGLRenderTarget = WebGLRenderTarget;
  54211. exports.WebGLRenderer = WebGLRenderer;
  54212. exports.WebGLUtils = WebGLUtils;
  54213. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54214. exports.WebXRController = WebXRController;
  54215. exports.WireframeGeometry = WireframeGeometry;
  54216. exports.WrapAroundEnding = WrapAroundEnding;
  54217. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54218. exports.ZeroFactor = ZeroFactor;
  54219. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54220. exports.ZeroStencilOp = ZeroStencilOp;
  54221. exports.createCanvasElement = createCanvasElement;
  54222. exports.error = error;
  54223. exports.getConsoleFunction = getConsoleFunction;
  54224. exports.log = log;
  54225. exports.setConsoleFunction = setConsoleFunction;
  54226. exports.warn = warn;
  54227. exports.warnOnce = warnOnce;
粤ICP备19079148号